title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
C# | Char.IsControl(String, Int32) Method - GeeksforGeeks
|
01 Feb, 2019
This method is used to indicates whether the character at the specified position in a specified string is categorized as a control character.
Syntax:
public static bool IsControl (string s, int index);
Parameters:
s: It is the String.
index: It is the character position in s.
Return Value: This method returns true if the character at position index in s is a control character otherwise it returns, false.
Exceptions:
ArgumentNullException: If the s is null.
ArgumentOutOfRangeException: If the index is less than zero or greater than the last position in s.
Note: Control characters are formatting and other non-printing characters, such as ACK, BEL, CR, FF, LF, and VT.
Below programs illustrate the use of Char.IsControl(String, Int32) Method:
Example 1:
// C# program to demonstrate the// Char.IsControl(String, Int32) // Methodusing System; class GFG { // Main Method public static void Main() { try { // calling check() Method check("1234", 3); check("Tsunami", 3); check("psyc0lo", 4); check("a" + Environment.NewLine + "b", 1); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining check() method public static void check(string s, int i) { // checking condition // using GetNumericValue() Method bool val = Char.IsControl(s, i); // checking if (val) Console.WriteLine("Control character \\U{0} "+ "found in position {1}.", Convert.ToInt32(s[i]).ToString("X4"), i); else Console.WriteLine("String '{0}' does't contain control "+ "character at index {1}", s, i); }}
String '1234' does't contain control character at index 3
String 'Tsunami' does't contain control character at index 3
String 'psyc0lo' does't contain control character at index 4
Control character \U000A found in position 1.
Example 2: For ArgumentNullException
// C# program to demonstrate the// Char.IsControl(String, Int32) // Methodusing System; class GFG { // Main Method public static void Main() { try { // calling check() Method check("1234", 3); check("psyc0lo", 4); check("a" + Environment.NewLine + "b", 1); Console.WriteLine(""); Console.WriteLine("s is null"); check(null, 4); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining check() method public static void check(string s, int i) { // checking condition // using GetNumericValue() Method bool val = Char.IsControl(s, i); // checking if (val) Console.WriteLine("Control character \\U{0} found"+ " in position {1}.", Convert.ToInt32(s[i]).ToString("X4"), i); else Console.WriteLine("String '{0}' does't contain "+ "control character at index {1}", s, i); }}
String '1234' does't contain control character at index 3
String 'psyc0lo' does't contain control character at index 4
Control character \U000A found in position 1.
s is null
Exception Thrown: System.ArgumentNullException
Example 3: For ArgumentOutOfRangeException
// C# program to demonstrate the// Char.IsControl(String, Int32) // Methodusing System; class GFG { // Main Method public static void Main() { try { // calling check() Method check("1234", 3); check("psyc0lo", 4); check("a" + Environment.NewLine + "b", 1); Console.WriteLine(""); Console.WriteLine("index is less than zero"); check("null", -1); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining check() method public static void check(string s, int i) { // checking condition // using GetNumericValue() Method bool val = Char.IsControl(s, i); // checking if (val) Console.WriteLine("Control character \\U{0} found "+ "in position {1}.", Convert.ToInt32(s[i]).ToString("X4"), i); else Console.WriteLine("String '{0}' does't contain control"+ " character at index {1}", s, i); }}
String '1234' does't contain control character at index 3
String 'psyc0lo' does't contain control character at index 4
Control character \U000A found in position 1.
index is less than zero
Exception Thrown: System.ArgumentOutOfRangeException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.char.iscontrol?view=netframework-4.7.2#System_Char_IsControl_System_String_System_Int32_
CSharp-Char-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Abstract Class and Interface in C#
C# | IsNullOrEmpty() Method
C# | How to check whether a List contains a specified element
C# Dictionary with examples
String.Split() Method in C# with Examples
C# | Method Overriding
C# | Arrays of Strings
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Constructors
|
[
{
"code": null,
"e": 24032,
"s": 24004,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24174,
"s": 24032,
"text": "This method is used to indicates whether the character at the specified position in a specified string is categorized as a control character."
},
{
"code": null,
"e": 24182,
"s": 24174,
"text": "Syntax:"
},
{
"code": null,
"e": 24234,
"s": 24182,
"text": "public static bool IsControl (string s, int index);"
},
{
"code": null,
"e": 24246,
"s": 24234,
"text": "Parameters:"
},
{
"code": null,
"e": 24267,
"s": 24246,
"text": "s: It is the String."
},
{
"code": null,
"e": 24309,
"s": 24267,
"text": "index: It is the character position in s."
},
{
"code": null,
"e": 24440,
"s": 24309,
"text": "Return Value: This method returns true if the character at position index in s is a control character otherwise it returns, false."
},
{
"code": null,
"e": 24452,
"s": 24440,
"text": "Exceptions:"
},
{
"code": null,
"e": 24493,
"s": 24452,
"text": "ArgumentNullException: If the s is null."
},
{
"code": null,
"e": 24593,
"s": 24493,
"text": "ArgumentOutOfRangeException: If the index is less than zero or greater than the last position in s."
},
{
"code": null,
"e": 24706,
"s": 24593,
"text": "Note: Control characters are formatting and other non-printing characters, such as ACK, BEL, CR, FF, LF, and VT."
},
{
"code": null,
"e": 24781,
"s": 24706,
"text": "Below programs illustrate the use of Char.IsControl(String, Int32) Method:"
},
{
"code": null,
"e": 24792,
"s": 24781,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Char.IsControl(String, Int32) // Methodusing System; class GFG { // Main Method public static void Main() { try { // calling check() Method check(\"1234\", 3); check(\"Tsunami\", 3); check(\"psyc0lo\", 4); check(\"a\" + Environment.NewLine + \"b\", 1); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining check() method public static void check(string s, int i) { // checking condition // using GetNumericValue() Method bool val = Char.IsControl(s, i); // checking if (val) Console.WriteLine(\"Control character \\\\U{0} \"+ \"found in position {1}.\", Convert.ToInt32(s[i]).ToString(\"X4\"), i); else Console.WriteLine(\"String '{0}' does't contain control \"+ \"character at index {1}\", s, i); }}",
"e": 26051,
"s": 24792,
"text": null
},
{
"code": null,
"e": 26278,
"s": 26051,
"text": "String '1234' does't contain control character at index 3\nString 'Tsunami' does't contain control character at index 3\nString 'psyc0lo' does't contain control character at index 4\nControl character \\U000A found in position 1.\n"
},
{
"code": null,
"e": 26315,
"s": 26278,
"text": "Example 2: For ArgumentNullException"
},
{
"code": "// C# program to demonstrate the// Char.IsControl(String, Int32) // Methodusing System; class GFG { // Main Method public static void Main() { try { // calling check() Method check(\"1234\", 3); check(\"psyc0lo\", 4); check(\"a\" + Environment.NewLine + \"b\", 1); Console.WriteLine(\"\"); Console.WriteLine(\"s is null\"); check(null, 4); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining check() method public static void check(string s, int i) { // checking condition // using GetNumericValue() Method bool val = Char.IsControl(s, i); // checking if (val) Console.WriteLine(\"Control character \\\\U{0} found\"+ \" in position {1}.\", Convert.ToInt32(s[i]).ToString(\"X4\"), i); else Console.WriteLine(\"String '{0}' does't contain \"+ \"control character at index {1}\", s, i); }}",
"e": 27634,
"s": 26315,
"text": null
},
{
"code": null,
"e": 27858,
"s": 27634,
"text": "String '1234' does't contain control character at index 3\nString 'psyc0lo' does't contain control character at index 4\nControl character \\U000A found in position 1.\n\ns is null\nException Thrown: System.ArgumentNullException\n"
},
{
"code": null,
"e": 27901,
"s": 27858,
"text": "Example 3: For ArgumentOutOfRangeException"
},
{
"code": "// C# program to demonstrate the// Char.IsControl(String, Int32) // Methodusing System; class GFG { // Main Method public static void Main() { try { // calling check() Method check(\"1234\", 3); check(\"psyc0lo\", 4); check(\"a\" + Environment.NewLine + \"b\", 1); Console.WriteLine(\"\"); Console.WriteLine(\"index is less than zero\"); check(\"null\", -1); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining check() method public static void check(string s, int i) { // checking condition // using GetNumericValue() Method bool val = Char.IsControl(s, i); // checking if (val) Console.WriteLine(\"Control character \\\\U{0} found \"+ \"in position {1}.\", Convert.ToInt32(s[i]).ToString(\"X4\"), i); else Console.WriteLine(\"String '{0}' does't contain control\"+ \" character at index {1}\", s, i); }}",
"e": 29259,
"s": 27901,
"text": null
},
{
"code": null,
"e": 29503,
"s": 29259,
"text": "String '1234' does't contain control character at index 3\nString 'psyc0lo' does't contain control character at index 4\nControl character \\U000A found in position 1.\n\nindex is less than zero\nException Thrown: System.ArgumentOutOfRangeException\n"
},
{
"code": null,
"e": 29514,
"s": 29503,
"text": "Reference:"
},
{
"code": null,
"e": 29654,
"s": 29514,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.char.iscontrol?view=netframework-4.7.2#System_Char_IsControl_System_String_System_Int32_"
},
{
"code": null,
"e": 29673,
"s": 29654,
"text": "CSharp-Char-Struct"
},
{
"code": null,
"e": 29687,
"s": 29673,
"text": "CSharp-method"
},
{
"code": null,
"e": 29690,
"s": 29687,
"text": "C#"
},
{
"code": null,
"e": 29788,
"s": 29690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29797,
"s": 29788,
"text": "Comments"
},
{
"code": null,
"e": 29810,
"s": 29797,
"text": "Old Comments"
},
{
"code": null,
"e": 29864,
"s": 29810,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 29892,
"s": 29864,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 29954,
"s": 29892,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 29982,
"s": 29954,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 30024,
"s": 29982,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 30047,
"s": 30024,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 30070,
"s": 30047,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 30092,
"s": 30070,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 30138,
"s": 30092,
"text": "Difference between Ref and Out keywords in C#"
}
] |
Paraphrase any question with T5 (Text-To-Text Transfer Transformer) — Pretrained model and training script provided | by Ramsri Goutham | Towards Data Science
|
The input to our program will be any general question that you can think of -
Which course should I take to get started in data Science?
The output will be paraphrased versions of the same question. Paraphrasing a question means, you create a new question that expresses the same meaning using a different choice of words.
Paraphrased Questions generated from our T5 Model ::0: What should I learn to become a data scientist?1: How do I get started with data science?2: How would you start a data science career?3: How can I start learning data science?4: How do you get started in data science?5: What's the best course for data science?6: Which course should I start with for data science?7: What courses should I follow to get started in data science?8: What degree should be taken by a data scientist?9: Which course should I follow to become a Data Scientist?
As you can see we generated about 10 questions that are paraphrases to the original question — “Which course should I take to get started in data science?”
Today we will see how we can train a T5 model from Huggingface’s transformers library to generate these paraphrased questions. We will also see how we can use the pre-trained model provided to generate these paraphrased questions.
Imagine a middle school teacher preparing a quiz for the class. Instead of giving a fixed question to every student he/she can generate multiple variants of a given question and distribute them across students. The school can also augment their question bank with several variants of a given question using this technique.
Let’s get started —
I used the Quora Question Pairs dataset to collect all the questions marked as duplicates and prepared training and validation sets. Questions that are duplicates serve our purpose of getting paraphrase pairs.
We will discuss in detail how you can -
Use my pre-trained model to generate paraphrased questions for any given question.Use my training code and dataset to replicate the results on your own GPU machine.
Use my pre-trained model to generate paraphrased questions for any given question.
Use my training code and dataset to replicate the results on your own GPU machine.
T5 is a new transformer model from Google that is trained in an end-to-end manner with text as input and modified text as output. You can read more about it here.
It achieves state-of-the-art results on multiple NLP tasks like summarization, question answering, machine translation, etc using a text-to-text transformer trained on a large text corpus.
I trained T5 with the original sentence as input and paraphrased (duplicate sentence from Quora Question pairs) sentence as output.
Use the Google Colab link in the “Using Pre-trained model” section to test this out. All the code for using training the model with given data is available at -
github.com
The Google Colab notebook t5-pretrained-question-paraphraser contains the code presented below.
First, install the necessary libraries -
!pip install transformers==2.8.0
Run inference with any question as input and see the paraphrased results.
The output from the above code is -
device cpuOriginal Question ::Which course should I take to get started in data science?Paraphrased Questions :: 0: What should I learn to become a data scientist?1: How do I get started with data science?2: How would you start a data science career?3: How can I start learning data science?4: How do you get started in data science?5: What's the best course for data science?6: Which course should I start with for data science?7: What courses should I follow to get started in data science?8: What degree should be taken by a data scientist?9: Which course should I follow to become a Data Scientist?
Again all the training code and dataset used for training are available in the Github repo mentioned earlier. We will go through the steps that I used to train the model.
First I downloaded the Quora Question pairs tsv file (quora_duplicate_questions.tsv) as mentioned in this link.
Extracted only the rows that have is_duplicate =1 since they are the paraphrased question sentences. Then I had split the data into train and validation sets and stored them in separate CSV files.
In the end, each of the CSV files has two columns “question1” and “question2”. “question2” is a paraphrased version of “question1”. Since T5 expects a text as input, I gave “question1” as the input source and asked it to generate “question2” as target output.
The code used to generate the train and validation CSV files is shown below. The CSV files are available under the paraphrase_data folder in the Github repo.
filename = "quora_duplicate_questions.tsv"import pandas as pdquestion_pairs = pd.read_csv(filename, sep='\t')question_pairs.drop(['qid1', 'qid2'], axis = 1,inplace = True)question_pairs_correct_paraphrased = question_pairs[question_pairs['is_duplicate']==1]question_pairs_correct_paraphrased.drop(['id', 'is_duplicate'], axis = 1,inplace = True)from sklearn.model_selection import train_test_splittrain, test = train_test_split(question_pairs_correct_paraphrased, test_size=0.1)train.to_csv('Quora_Paraphrasing_train.csv', index = False)test.to_csv('Quora_Paraphrasing_val.csv', index = False)
Thanks to Suraj Patil for the amazing Colab notebook on training T5 for any text-to-text task. I borrowed most of the training code from the Colab notebook, changing only the dataset class and training parameters. I adapted the dataset class to our Quora Question Pair dataset.
The training code is available as train.py in the Github Repo.
All you need to do is clone the repo on any GPU machine, install requirements.txt, and run train.py to train the T5 model.
Training this model for 2 epochs (default) took about 20 hrs on p2.xlarge (AWS ec2).
The dataset class looks like below —
The key is how we give our input and output to the T5 model trainer. For any given question pair from the dataset, I gave input (source) and output (target) to the T5 model as shown below -
Input format to T5 for training
paraphrase: What are the ingredients required to make a perfect cake? </s>
Output format to T5 for training
How do you bake a delicious cake? </s>
That’s it! You have a state-of-the-art question paraphraser in your hand.
Perhaps this is the first work of it's kind out there to generate paraphrased questions from any given question!
Happy coding!
I launched a very interesting Udemy course titled “Question generation using NLP” expanding on some of the techniques discussed in this blog post. If you would like to take a look at it, here is the link.
|
[
{
"code": null,
"e": 250,
"s": 172,
"text": "The input to our program will be any general question that you can think of -"
},
{
"code": null,
"e": 326,
"s": 250,
"text": "Which course should I take to get started in data Science? "
},
{
"code": null,
"e": 512,
"s": 326,
"text": "The output will be paraphrased versions of the same question. Paraphrasing a question means, you create a new question that expresses the same meaning using a different choice of words."
},
{
"code": null,
"e": 1054,
"s": 512,
"text": "Paraphrased Questions generated from our T5 Model ::0: What should I learn to become a data scientist?1: How do I get started with data science?2: How would you start a data science career?3: How can I start learning data science?4: How do you get started in data science?5: What's the best course for data science?6: Which course should I start with for data science?7: What courses should I follow to get started in data science?8: What degree should be taken by a data scientist?9: Which course should I follow to become a Data Scientist?"
},
{
"code": null,
"e": 1210,
"s": 1054,
"text": "As you can see we generated about 10 questions that are paraphrases to the original question — “Which course should I take to get started in data science?”"
},
{
"code": null,
"e": 1441,
"s": 1210,
"text": "Today we will see how we can train a T5 model from Huggingface’s transformers library to generate these paraphrased questions. We will also see how we can use the pre-trained model provided to generate these paraphrased questions."
},
{
"code": null,
"e": 1764,
"s": 1441,
"text": "Imagine a middle school teacher preparing a quiz for the class. Instead of giving a fixed question to every student he/she can generate multiple variants of a given question and distribute them across students. The school can also augment their question bank with several variants of a given question using this technique."
},
{
"code": null,
"e": 1784,
"s": 1764,
"text": "Let’s get started —"
},
{
"code": null,
"e": 1994,
"s": 1784,
"text": "I used the Quora Question Pairs dataset to collect all the questions marked as duplicates and prepared training and validation sets. Questions that are duplicates serve our purpose of getting paraphrase pairs."
},
{
"code": null,
"e": 2034,
"s": 1994,
"text": "We will discuss in detail how you can -"
},
{
"code": null,
"e": 2199,
"s": 2034,
"text": "Use my pre-trained model to generate paraphrased questions for any given question.Use my training code and dataset to replicate the results on your own GPU machine."
},
{
"code": null,
"e": 2282,
"s": 2199,
"text": "Use my pre-trained model to generate paraphrased questions for any given question."
},
{
"code": null,
"e": 2365,
"s": 2282,
"text": "Use my training code and dataset to replicate the results on your own GPU machine."
},
{
"code": null,
"e": 2528,
"s": 2365,
"text": "T5 is a new transformer model from Google that is trained in an end-to-end manner with text as input and modified text as output. You can read more about it here."
},
{
"code": null,
"e": 2717,
"s": 2528,
"text": "It achieves state-of-the-art results on multiple NLP tasks like summarization, question answering, machine translation, etc using a text-to-text transformer trained on a large text corpus."
},
{
"code": null,
"e": 2849,
"s": 2717,
"text": "I trained T5 with the original sentence as input and paraphrased (duplicate sentence from Quora Question pairs) sentence as output."
},
{
"code": null,
"e": 3010,
"s": 2849,
"text": "Use the Google Colab link in the “Using Pre-trained model” section to test this out. All the code for using training the model with given data is available at -"
},
{
"code": null,
"e": 3021,
"s": 3010,
"text": "github.com"
},
{
"code": null,
"e": 3117,
"s": 3021,
"text": "The Google Colab notebook t5-pretrained-question-paraphraser contains the code presented below."
},
{
"code": null,
"e": 3158,
"s": 3117,
"text": "First, install the necessary libraries -"
},
{
"code": null,
"e": 3191,
"s": 3158,
"text": "!pip install transformers==2.8.0"
},
{
"code": null,
"e": 3265,
"s": 3191,
"text": "Run inference with any question as input and see the paraphrased results."
},
{
"code": null,
"e": 3301,
"s": 3265,
"text": "The output from the above code is -"
},
{
"code": null,
"e": 3905,
"s": 3301,
"text": "device cpuOriginal Question ::Which course should I take to get started in data science?Paraphrased Questions :: 0: What should I learn to become a data scientist?1: How do I get started with data science?2: How would you start a data science career?3: How can I start learning data science?4: How do you get started in data science?5: What's the best course for data science?6: Which course should I start with for data science?7: What courses should I follow to get started in data science?8: What degree should be taken by a data scientist?9: Which course should I follow to become a Data Scientist?"
},
{
"code": null,
"e": 4076,
"s": 3905,
"text": "Again all the training code and dataset used for training are available in the Github repo mentioned earlier. We will go through the steps that I used to train the model."
},
{
"code": null,
"e": 4188,
"s": 4076,
"text": "First I downloaded the Quora Question pairs tsv file (quora_duplicate_questions.tsv) as mentioned in this link."
},
{
"code": null,
"e": 4385,
"s": 4188,
"text": "Extracted only the rows that have is_duplicate =1 since they are the paraphrased question sentences. Then I had split the data into train and validation sets and stored them in separate CSV files."
},
{
"code": null,
"e": 4645,
"s": 4385,
"text": "In the end, each of the CSV files has two columns “question1” and “question2”. “question2” is a paraphrased version of “question1”. Since T5 expects a text as input, I gave “question1” as the input source and asked it to generate “question2” as target output."
},
{
"code": null,
"e": 4803,
"s": 4645,
"text": "The code used to generate the train and validation CSV files is shown below. The CSV files are available under the paraphrase_data folder in the Github repo."
},
{
"code": null,
"e": 5397,
"s": 4803,
"text": "filename = \"quora_duplicate_questions.tsv\"import pandas as pdquestion_pairs = pd.read_csv(filename, sep='\\t')question_pairs.drop(['qid1', 'qid2'], axis = 1,inplace = True)question_pairs_correct_paraphrased = question_pairs[question_pairs['is_duplicate']==1]question_pairs_correct_paraphrased.drop(['id', 'is_duplicate'], axis = 1,inplace = True)from sklearn.model_selection import train_test_splittrain, test = train_test_split(question_pairs_correct_paraphrased, test_size=0.1)train.to_csv('Quora_Paraphrasing_train.csv', index = False)test.to_csv('Quora_Paraphrasing_val.csv', index = False)"
},
{
"code": null,
"e": 5675,
"s": 5397,
"text": "Thanks to Suraj Patil for the amazing Colab notebook on training T5 for any text-to-text task. I borrowed most of the training code from the Colab notebook, changing only the dataset class and training parameters. I adapted the dataset class to our Quora Question Pair dataset."
},
{
"code": null,
"e": 5738,
"s": 5675,
"text": "The training code is available as train.py in the Github Repo."
},
{
"code": null,
"e": 5861,
"s": 5738,
"text": "All you need to do is clone the repo on any GPU machine, install requirements.txt, and run train.py to train the T5 model."
},
{
"code": null,
"e": 5946,
"s": 5861,
"text": "Training this model for 2 epochs (default) took about 20 hrs on p2.xlarge (AWS ec2)."
},
{
"code": null,
"e": 5983,
"s": 5946,
"text": "The dataset class looks like below —"
},
{
"code": null,
"e": 6173,
"s": 5983,
"text": "The key is how we give our input and output to the T5 model trainer. For any given question pair from the dataset, I gave input (source) and output (target) to the T5 model as shown below -"
},
{
"code": null,
"e": 6205,
"s": 6173,
"text": "Input format to T5 for training"
},
{
"code": null,
"e": 6280,
"s": 6205,
"text": "paraphrase: What are the ingredients required to make a perfect cake? </s>"
},
{
"code": null,
"e": 6313,
"s": 6280,
"text": "Output format to T5 for training"
},
{
"code": null,
"e": 6352,
"s": 6313,
"text": "How do you bake a delicious cake? </s>"
},
{
"code": null,
"e": 6426,
"s": 6352,
"text": "That’s it! You have a state-of-the-art question paraphraser in your hand."
},
{
"code": null,
"e": 6539,
"s": 6426,
"text": "Perhaps this is the first work of it's kind out there to generate paraphrased questions from any given question!"
},
{
"code": null,
"e": 6553,
"s": 6539,
"text": "Happy coding!"
}
] |
How to get all the keys from a Scala map - GeeksforGeeks
|
29 Jul, 2019
In order to get all the keys from a Scala map, we need to use either keySet method (to get all the keys as a set) or we can use keys method and if you want to get the keys as an iterator, you need to use keysIterator method. Now, lets check some examples.Example #1:
// Scala program of keySet()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs") // Applying keySet method val result = m1.keySet // Displays output println(result) }}
Set(3, 4, 2)
Here, keySet method is utilized.Example #2:
// Scala program of keys()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs") // Applying keys method val result = m1.keys // Displays output println(result) }}
Set(3, 4, 2)
Here, keys method is utilized.Example #3:
// Scala program of keysIterator()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs") // Applying keysIterator method val result = m1.keysIterator // Displays output println(result) }}
non-empty iterator
Here, keysIterator method is utilized.
Scala
Scala-Map
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Type Casting in Scala
Scala Lists
Class and Object in Scala
Break statement in Scala
Scala String substring() method with example
Lambda Expression in Scala
Scala String replace() method with example
Operators in Scala
Scala | Arrays
|
[
{
"code": null,
"e": 23621,
"s": 23593,
"text": "\n29 Jul, 2019"
},
{
"code": null,
"e": 23888,
"s": 23621,
"text": "In order to get all the keys from a Scala map, we need to use either keySet method (to get all the keys as a set) or we can use keys method and if you want to get the keys as an iterator, you need to use keysIterator method. Now, lets check some examples.Example #1:"
},
{
"code": "// Scala program of keySet()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 4 -> \"for\", 2 -> \"cs\") // Applying keySet method val result = m1.keySet // Displays output println(result) }}",
"e": 24247,
"s": 23888,
"text": null
},
{
"code": null,
"e": 24261,
"s": 24247,
"text": "Set(3, 4, 2)\n"
},
{
"code": null,
"e": 24305,
"s": 24261,
"text": "Here, keySet method is utilized.Example #2:"
},
{
"code": "// Scala program of keys()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 4 -> \"for\", 2 -> \"cs\") // Applying keys method val result = m1.keys // Displays output println(result) }}",
"e": 24658,
"s": 24305,
"text": null
},
{
"code": null,
"e": 24672,
"s": 24658,
"text": "Set(3, 4, 2)\n"
},
{
"code": null,
"e": 24714,
"s": 24672,
"text": "Here, keys method is utilized.Example #3:"
},
{
"code": "// Scala program of keysIterator()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 4 -> \"for\", 2 -> \"cs\") // Applying keysIterator method val result = m1.keysIterator // Displays output println(result) }}",
"e": 25091,
"s": 24714,
"text": null
},
{
"code": null,
"e": 25111,
"s": 25091,
"text": "non-empty iterator\n"
},
{
"code": null,
"e": 25150,
"s": 25111,
"text": "Here, keysIterator method is utilized."
},
{
"code": null,
"e": 25156,
"s": 25150,
"text": "Scala"
},
{
"code": null,
"e": 25166,
"s": 25156,
"text": "Scala-Map"
},
{
"code": null,
"e": 25172,
"s": 25166,
"text": "Scala"
},
{
"code": null,
"e": 25270,
"s": 25172,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25279,
"s": 25270,
"text": "Comments"
},
{
"code": null,
"e": 25292,
"s": 25279,
"text": "Old Comments"
},
{
"code": null,
"e": 25345,
"s": 25292,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 25367,
"s": 25345,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 25379,
"s": 25367,
"text": "Scala Lists"
},
{
"code": null,
"e": 25405,
"s": 25379,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 25430,
"s": 25405,
"text": "Break statement in Scala"
},
{
"code": null,
"e": 25475,
"s": 25430,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 25502,
"s": 25475,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 25545,
"s": 25502,
"text": "Scala String replace() method with example"
},
{
"code": null,
"e": 25564,
"s": 25545,
"text": "Operators in Scala"
}
] |
Go switch
|
Use the switch statement to select one of many code blocks to be executed.
The switch statement in Go is similar to the ones in C, C++, Java, JavaScript, and PHP. The difference is that it only runs the matched case so it does not need a break statement.
This is how it works:
The expression is evaluated once
The value of the switch expression is compared with the values of each case
If there is a match, the associated block of code is executed
The default keyword is optional. It
specifies some code to run if there is no case
match
The example below uses a weekday number to calculate the weekday name:
Result:
The default keyword specifies some code to run if there is no case match:
Result:
All the case values should have the same type as the switch expression. Otherwise, the compiler will raise an error:
Result:
Insert the missing parts to complete the following switch statement.
package main
import ("fmt")
func main() {
var day = 2
switch {
(1):
fmt.Print("Saturday")
(2):
fmt.Print("Sunday")
}
}
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 75,
"s": 0,
"text": "Use the switch statement to select one of many code blocks to be executed."
},
{
"code": null,
"e": 255,
"s": 75,
"text": "The switch statement in Go is similar to the ones in C, C++, Java, JavaScript, and PHP. The difference is that it only runs the matched case so it does not need a break statement."
},
{
"code": null,
"e": 277,
"s": 255,
"text": "This is how it works:"
},
{
"code": null,
"e": 310,
"s": 277,
"text": "The expression is evaluated once"
},
{
"code": null,
"e": 386,
"s": 310,
"text": "The value of the switch expression is compared with the values of each case"
},
{
"code": null,
"e": 448,
"s": 386,
"text": "If there is a match, the associated block of code is executed"
},
{
"code": null,
"e": 540,
"s": 448,
"text": "The default keyword is optional. It \nspecifies some code to run if there is no case \nmatch"
},
{
"code": null,
"e": 611,
"s": 540,
"text": "The example below uses a weekday number to calculate the weekday name:"
},
{
"code": null,
"e": 619,
"s": 611,
"text": "Result:"
},
{
"code": null,
"e": 693,
"s": 619,
"text": "The default keyword specifies some code to run if there is no case match:"
},
{
"code": null,
"e": 701,
"s": 693,
"text": "Result:"
},
{
"code": null,
"e": 818,
"s": 701,
"text": "All the case values should have the same type as the switch expression. Otherwise, the compiler will raise an error:"
},
{
"code": null,
"e": 826,
"s": 818,
"text": "Result:"
},
{
"code": null,
"e": 895,
"s": 826,
"text": "Insert the missing parts to complete the following switch statement."
},
{
"code": null,
"e": 1042,
"s": 895,
"text": "package main \nimport (\"fmt\") \nfunc main() {\n var day = 2\n switch {\n (1):\n fmt.Print(\"Saturday\")\n (2):\n fmt.Print(\"Sunday\") \n }\n}\n"
},
{
"code": null,
"e": 1061,
"s": 1042,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1094,
"s": 1061,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1136,
"s": 1094,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1243,
"s": 1136,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1262,
"s": 1243,
"text": "help@w3schools.com"
}
] |
Convert JSON object to Java object using Gson library in Java?
|
A Gson is a json library for java, which is created by Google and it can be used to generate a JSON. By using Gson, we can generate JSON and convert JSON to java objects. We can call the fromJson() method of Gson class to convert a JSON object to Java Object.
public <T> fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException
import com.google.gson.*;
public class JSONtoJavaObjTest {
public static void main(String[] args) {
Gson gson = new Gson();
Emp emp = gson.fromJson("{'name':'raja','age':25}", Emp.class);
System.out.println(emp.getName());
System.out.println(emp.getAge());
}
}
// Emp class
class Emp {
String name;
int age;
public Emp() {
super();
}
public Emp(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
raja
25
|
[
{
"code": null,
"e": 1322,
"s": 1062,
"text": "A Gson is a json library for java, which is created by Google and it can be used to generate a JSON. By using Gson, we can generate JSON and convert JSON to java objects. We can call the fromJson() method of Gson class to convert a JSON object to Java Object."
},
{
"code": null,
"e": 1421,
"s": 1322,
"text": "public <T> fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException"
},
{
"code": null,
"e": 2141,
"s": 1421,
"text": "import com.google.gson.*;\npublic class JSONtoJavaObjTest {\n public static void main(String[] args) {\n Gson gson = new Gson();\n Emp emp = gson.fromJson(\"{'name':'raja','age':25}\", Emp.class);\n System.out.println(emp.getName());\n System.out.println(emp.getAge());\n }\n}\n// Emp class\nclass Emp {\n String name;\n int age;\n public Emp() {\n super();\n }\n public Emp(String name, int age) {\n super();\n this.name = name;\n this.age = age;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n \n public void setAge(int age) {\n this.age = age;\n }\n}"
},
{
"code": null,
"e": 2149,
"s": 2141,
"text": "raja\n25"
}
] |
Fastest way to Convert Integers to Strings in Pandas DataFrame - GeeksforGeeks
|
01 Aug, 2020
Pandas – An open-source library which is used by any programmer. It is a useful library that is used for analyzing the data and for manipulating the data. It is fast, flexible, and understandable, handles the missing data easily. Not only it provides but also enhances the performance of data manipulation and analysis tools with the powerful data structure.
There are four ways of converting integers to strings in pandas.
Method 1: map(str)
frame[‘DataFrame Column’]= frame[‘DataFrame Column’].map(str)
Method 2: apply(str)
frame[‘DataFrame Column’]= frame[‘DataFrame Column’].apply(str)
Method 3: astype(str)
frame[‘DataFrame Column’]= frame[‘DataFrame Column’].astype(str)
Method 4: values.astype(str)
frame[‘DataFrame Column’]= frame[‘DataFrame Column’].values.astype(str)
In order to find out the fastest method we find the time taken by each method required for converting integers to the string. The method which requires the minimum time for conversion is considered to be the fastest method.
import pandas as pdimport sysimport timeimport numpy as np print('Version Of Python: ' + sys.version)print('Version Of Pandas: ' + pd.__version__)print('Version Of Numpy: ' + np.version.version) frame1 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random'])frame2 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random'])frame3 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random'])frame4 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random']) # Using map(str) methodt1 = time.time()frame1['random'] = frame1['random'].map(str)output1 = (time.time() - t1) print('Time taken in seconds using map(str): ' + str(output1)) # Using apply(str) methodt2 = time.time()frame2['random'] = frame2['random'].apply(str)output2 = (time.time() - t2) print('Time taken in seconds using apply(str): ' + str(output2)) # Using astype(str) methodt3 = time.time()frame3['random'] = frame3['random'].astype(str)output3 = (time.time() - t3) print('Time taken in seconds using astype(str): ' + str(output3)) # Using values.astype(str) methodt4 = time.time()frame4['random'] = frame4['random'].values.astype(str)output4 = (time.time() - t4) print('Time taken in seconds using values.astype(str): ' + str(output4)) l =[output1, output2, output3, output4]m =['map(str)', 'apply(str)', 'astype(str)', 'values.astype(str)'] # Fastest way to convert into stringminimum = min(l)k = l.index(minimum)fastest = m[k] # It will print the fastest conversion method.print(fastest+" is the fastest method")
Output:
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24260,
"s": 23901,
"text": "Pandas – An open-source library which is used by any programmer. It is a useful library that is used for analyzing the data and for manipulating the data. It is fast, flexible, and understandable, handles the missing data easily. Not only it provides but also enhances the performance of data manipulation and analysis tools with the powerful data structure."
},
{
"code": null,
"e": 24325,
"s": 24260,
"text": "There are four ways of converting integers to strings in pandas."
},
{
"code": null,
"e": 24344,
"s": 24325,
"text": "Method 1: map(str)"
},
{
"code": null,
"e": 24406,
"s": 24344,
"text": "frame[‘DataFrame Column’]= frame[‘DataFrame Column’].map(str)"
},
{
"code": null,
"e": 24427,
"s": 24406,
"text": "Method 2: apply(str)"
},
{
"code": null,
"e": 24491,
"s": 24427,
"text": "frame[‘DataFrame Column’]= frame[‘DataFrame Column’].apply(str)"
},
{
"code": null,
"e": 24513,
"s": 24491,
"text": "Method 3: astype(str)"
},
{
"code": null,
"e": 24578,
"s": 24513,
"text": "frame[‘DataFrame Column’]= frame[‘DataFrame Column’].astype(str)"
},
{
"code": null,
"e": 24607,
"s": 24578,
"text": "Method 4: values.astype(str)"
},
{
"code": null,
"e": 24679,
"s": 24607,
"text": "frame[‘DataFrame Column’]= frame[‘DataFrame Column’].values.astype(str)"
},
{
"code": null,
"e": 24903,
"s": 24679,
"text": "In order to find out the fastest method we find the time taken by each method required for converting integers to the string. The method which requires the minimum time for conversion is considered to be the fastest method."
},
{
"code": "import pandas as pdimport sysimport timeimport numpy as np print('Version Of Python: ' + sys.version)print('Version Of Pandas: ' + pd.__version__)print('Version Of Numpy: ' + np.version.version) frame1 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random'])frame2 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random'])frame3 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random'])frame4 = pd.DataFrame(np.random.randint(0, 90, size =(5000000, 1)), columns =['random']) # Using map(str) methodt1 = time.time()frame1['random'] = frame1['random'].map(str)output1 = (time.time() - t1) print('Time taken in seconds using map(str): ' + str(output1)) # Using apply(str) methodt2 = time.time()frame2['random'] = frame2['random'].apply(str)output2 = (time.time() - t2) print('Time taken in seconds using apply(str): ' + str(output2)) # Using astype(str) methodt3 = time.time()frame3['random'] = frame3['random'].astype(str)output3 = (time.time() - t3) print('Time taken in seconds using astype(str): ' + str(output3)) # Using values.astype(str) methodt4 = time.time()frame4['random'] = frame4['random'].values.astype(str)output4 = (time.time() - t4) print('Time taken in seconds using values.astype(str): ' + str(output4)) l =[output1, output2, output3, output4]m =['map(str)', 'apply(str)', 'astype(str)', 'values.astype(str)'] # Fastest way to convert into stringminimum = min(l)k = l.index(minimum)fastest = m[k] # It will print the fastest conversion method.print(fastest+\" is the fastest method\")",
"e": 26490,
"s": 24903,
"text": null
},
{
"code": null,
"e": 26498,
"s": 26490,
"text": "Output:"
},
{
"code": null,
"e": 26512,
"s": 26498,
"text": "Python-pandas"
},
{
"code": null,
"e": 26519,
"s": 26512,
"text": "Python"
},
{
"code": null,
"e": 26617,
"s": 26519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26626,
"s": 26617,
"text": "Comments"
},
{
"code": null,
"e": 26639,
"s": 26626,
"text": "Old Comments"
},
{
"code": null,
"e": 26671,
"s": 26639,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26727,
"s": 26671,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26769,
"s": 26727,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26811,
"s": 26769,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26847,
"s": 26811,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26869,
"s": 26847,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26908,
"s": 26869,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26935,
"s": 26908,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26966,
"s": 26935,
"text": "Python | os.path.join() method"
}
] |
How to convert a bean to JSON object using Exclude Filter in Java?
|
The JsonConfig class can be used to configure the serialization process. We can use the setJsonPropertyFilter() method of JsonConfig to set the property filter when serializing to JSON. We need to implement a custom PropertyFilter class by overriding the apply() method of the PropertyFilter interface. It returns true if the property will be filtered out or false otherwise.
public void setJsonPropertyFilter(PropertyFilter jsonPropertyFilter)
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
public class ConvertBeanToJsonExcludeFilterTest {
public static void main(String[] args) {
Student student = new Student("Sai", "Chaitanya", 20, "Hyderabad");
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter(new CustomPropertyFilter());
JSONObject jsonObj = JSONObject.fromObject(student, jsonConfig);
System.out.println(jsonObj.toString(3)); //pretty print JSON
}
public static class Student {
private String firstName, lastName, address;
public int age;
public Student(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
}
}
// CustomPropertyFilter class
class CustomPropertyFilter implements PropertyFilter {
@Override
public boolean apply(Object source, String name, Object value) {
if(Number.class.isAssignableFrom(value.getClass()) || String.class.isAssignableFrom(value.getClass())) {
return false;
}
return true;
}
}
{
"firstName": "Sai",
"lastName": "Chaitanya",
"address": "Hyderabad",
"age": 20
}
|
[
{
"code": null,
"e": 1438,
"s": 1062,
"text": "The JsonConfig class can be used to configure the serialization process. We can use the setJsonPropertyFilter() method of JsonConfig to set the property filter when serializing to JSON. We need to implement a custom PropertyFilter class by overriding the apply() method of the PropertyFilter interface. It returns true if the property will be filtered out or false otherwise."
},
{
"code": null,
"e": 1507,
"s": 1438,
"text": "public void setJsonPropertyFilter(PropertyFilter jsonPropertyFilter)"
},
{
"code": null,
"e": 2997,
"s": 1507,
"text": "import net.sf.json.JSONObject;\nimport net.sf.json.JsonConfig;\nimport net.sf.json.util.PropertyFilter;\npublic class ConvertBeanToJsonExcludeFilterTest {\n public static void main(String[] args) {\n Student student = new Student(\"Sai\", \"Chaitanya\", 20, \"Hyderabad\");\n JsonConfig jsonConfig = new JsonConfig();\n jsonConfig.setJsonPropertyFilter(new CustomPropertyFilter());\n\n JSONObject jsonObj = JSONObject.fromObject(student, jsonConfig);\n System.out.println(jsonObj.toString(3)); //pretty print JSON\n }\n public static class Student {\n private String firstName, lastName, address;\n public int age;\n public Student(String firstName, String lastName, int age, String address) {\n super();\n this.firstName = firstName;\n this.lastName = lastName;\n this.age = age;\n this.address = address;\n }\n public String getFirstName() {\n return firstName;\n }\n public String getLastName() {\n return lastName;\n }\n public int getAge() {\n return age;\n }\n public String getAddress() {\n return address;\n }\n }\n}\n// CustomPropertyFilter class\nclass CustomPropertyFilter implements PropertyFilter {\n @Override\n public boolean apply(Object source, String name, Object value) {\n if(Number.class.isAssignableFrom(value.getClass()) || String.class.isAssignableFrom(value.getClass())) {\n return false;\n }\n return true;\n }\n}"
},
{
"code": null,
"e": 3088,
"s": 2997,
"text": "{\n \"firstName\": \"Sai\",\n \"lastName\": \"Chaitanya\",\n \"address\": \"Hyderabad\",\n \"age\": 20\n}"
}
] |
How to get top activity name in activity stack?
|
This example demonstrate about How to get top activity name in activity stack.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken text view to show top activity name.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.view.WindowManager;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
ActivityManager result = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> services = result
.getRunningTasks(Integer.MAX_VALUE);
textView.setText("" +services.get(0).topActivity.toString());
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "This example demonstrate about How to get top activity name in activity stack."
},
{
"code": null,
"e": 1270,
"s": 1141,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1335,
"s": 1270,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1931,
"s": 1335,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2001,
"s": 1931,
"text": "In the above code, we have taken text view to show top activity name."
},
{
"code": null,
"e": 2058,
"s": 2001,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3162,
"s": 2058,
"text": "package com.example.myapplication;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.telephony.TelephonyManager;\nimport android.view.WindowManager;\nimport android.widget.TextView;\nimport java.util.List;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,\n WindowManager.LayoutParams.FLAG_BLUR_BEHIND);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n ActivityManager result = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);\n List<ActivityManager.RunningTaskInfo> services = result\n .getRunningTasks(Integer.MAX_VALUE);\n textView.setText(\"\" +services.get(0).topActivity.toString());\n }\n}"
},
{
"code": null,
"e": 3509,
"s": 3162,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 3549,
"s": 3509,
"text": "Click here to download the project code"
}
] |
How to print Narcissistic(Armstrong) Numbers with Python?
|
To print Narcissistic Numbers, let's first look at the definition of it. It is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 1, 153, 370 are all Narcissistic numbers. You can print these numbers by running the following code
def print_narcissistic_nums(start, end):
for i in range(start, end + 1):
# Get the digits from the number in a list:
digits = list(map(int, str(i)))
total = 0
length = len(digits)
for d in digits:
total += d ** length
if total == i:
print(i)
print_narcissistic_nums(1, 380)
This will give the output
1
2
3
4
5
6
7
8
9
153
370
371
|
[
{
"code": null,
"e": 1347,
"s": 1062,
"text": "To print Narcissistic Numbers, let's first look at the definition of it. It is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 1, 153, 370 are all Narcissistic numbers. You can print these numbers by running the following code"
},
{
"code": null,
"e": 1651,
"s": 1347,
"text": "def print_narcissistic_nums(start, end):\nfor i in range(start, end + 1):\n # Get the digits from the number in a list:\n digits = list(map(int, str(i)))\n total = 0\n length = len(digits)\n for d in digits:\n total += d ** length\n if total == i:\n print(i)\nprint_narcissistic_nums(1, 380)"
},
{
"code": null,
"e": 1677,
"s": 1651,
"text": "This will give the output"
},
{
"code": null,
"e": 1707,
"s": 1677,
"text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n153\n370\n371"
}
] |
Append the last M nodes to the beginning of the given linked list. - GeeksforGeeks
|
23 Dec, 2021
Given a linked list and an integer M, the task is to append the last M nodes of the linked list to the front.Examples:
Input: List = 4 -> 5 -> 6 -> 1 -> 2 -> 3 -> NULL, M = 3 Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLInput: List = 8 -> 7 -> 0 -> 4 -> 1 -> NULL, M = 2 Output: 4 -> 1 -> 8 -> 7 -> 0 -> NULL
Approach: Find the first node of the last M nodes in the list, this node will be the new head node so make the next pointer of the previous node as NULL and point the last node of the original list to the head of the original list. Finally, print the updated list.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Class for a node of// the linked liststruct Node { // Data and the pointer // to the next node int data; Node* next; Node(int data) { this->data = data; this->next = NULL; }}; // Function to print the linked listvoid printList(Node* node){ while (node != NULL) { cout << (node->data) << " -> "; node = node->next; } cout << "NULL";} // Recursive function to return the// count of nodes in the linked listint cntNodes(Node* node){ if (node == NULL) return 0; return (1 + cntNodes(node->next));} // Function to update and print// the updated list nodesvoid updateList(Node* head, int m){ // Total nodes in the list int cnt = cntNodes(head); if (cnt != m && m < cnt) { // Count of nodes to be skipped // from the beginning int skip = cnt - m; Node* prev = NULL; Node* curr = head; // Skip the nodes while (skip > 0) { prev = curr; curr = curr->next; skip--; } // Change the pointers prev->next = NULL; Node* tempHead = head; head = curr; // Find the last node while (curr->next != NULL) curr = curr->next; // Connect it to the head // of the sub list curr->next = tempHead; } // Print the updated list printList(head);} // Driver codeint main(){ // Create the list Node* head = new Node(4); head->next = new Node(5); head->next->next = new Node(6); head->next->next->next = new Node(1); head->next->next->next->next = new Node(2); head->next->next->next->next->next = new Node(3); int m = 3; updateList(head, m); return 0;} // This code is contributed by rutvik_56
// Java implementation of the approachclass GFG { // Class for a node of // the linked list static class Node { // Data and the pointer // to the next node int data; Node next; Node(int data) { this.data = data; this.next = null; } } // Function to print the linked list static void printList(Node node) { while (node != null) { System.out.print(node.data + " -> "); node = node.next; } System.out.print("NULL"); } // Recursive function to return the // count of nodes in the linked list static int cntNodes(Node node) { if (node == null) return 0; return (1 + cntNodes(node.next)); } // Function to update and print // the updated list nodes static void updateList(Node head, int m) { // Total nodes in the list int cnt = cntNodes(head); if (cnt != m && m < cnt) { // Count of nodes to be skipped // from the beginning int skip = cnt - m; Node prev = null; Node curr = head; // Skip the nodes while (skip > 0) { prev = curr; curr = curr.next; skip--; } // Change the pointers prev.next = null; Node tempHead = head; head = curr; // Find the last node while (curr.next != null) curr = curr.next; // Connect it to the head // of the sub list curr.next = tempHead; } // Print the updated list printList(head); } // Driver code public static void main(String[] args) { // Create the list Node head = new Node(4); head.next = new Node(5); head.next.next = new Node(6); head.next.next.next = new Node(1); head.next.next.next.next = new Node(2); head.next.next.next.next.next = new Node(3); int m = 3; updateList(head, m); }}
# Python3 implementation of the approach # Class for a node of# the linked list class newNode: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None # Function to print the linked list def printList(node): while (node != None): print(node.data, "->", end=" ") node = node.next print("NULL") # Recursive function to return the# count of nodes in the linked list def cntNodes(node): if (node == None): return 0 return (1 + cntNodes(node.next)) # Function to update and print# the updated list nodes def updateList(head, m): # Total nodes in the list cnt = cntNodes(head) if (cnt != m and m < cnt): # Count of nodes to be skipped # from the beginning skip = cnt - m prev = None curr = head # Skip the nodes while (skip > 0): prev = curr curr = curr.next skip -= 1 # Change the pointers prev.next = None tempHead = head head = curr # Find the last node while (curr.next != None): curr = curr.next # Connect it to the head # of the sub list curr.next = tempHead # Print the updated list printList(head) # Driver code # Create the listhead = newNode(4)head.next = newNode(5)head.next.next = newNode(6)head.next.next.next = newNode(1)head.next.next.next.next = newNode(2)head.next.next.next.next.next = newNode(3) m = 3 updateList(head, m) # This code is contributed by shubhamsingh10
// C# implementation of the approachusing System; class GFG { // Class for a node of // the linked list class Node { // Data and the pointer // to the next node public int data; public Node next; public Node(int data) { this.data = data; this.next = null; } } // Function to print the linked list static void printList(Node node) { while (node != null) { Console.Write(node.data + " -> "); node = node.next; } Console.Write("NULL"); } // Recursive function to return the // count of nodes in the linked list static int cntNodes(Node node) { if (node == null) return 0; return (1 + cntNodes(node.next)); } // Function to update and print // the updated list nodes static void updateList(Node head, int m) { // Total nodes in the list int cnt = cntNodes(head); if (cnt != m && m < cnt) { // Count of nodes to be skipped // from the beginning int skip = cnt - m; Node prev = null; Node curr = head; // Skip the nodes while (skip > 0) { prev = curr; curr = curr.next; skip--; } // Change the pointers prev.next = null; Node tempHead = head; head = curr; // Find the last node while (curr.next != null) curr = curr.next; // Connect it to the head // of the sub list curr.next = tempHead; } // Print the updated list printList(head); } // Driver code public static void Main(String[] args) { // Create the list Node head = new Node(4); head.next = new Node(5); head.next.next = new Node(6); head.next.next.next = new Node(1); head.next.next.next.next = new Node(2); head.next.next.next.next.next = new Node(3); int m = 3; updateList(head, m); }} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation of the approach // Class for a node of // the linked list class Node { // Data and the pointer // to the next node constructor(data) { this.data = data; this.next = null; } } // Function to print the linked list function printList(node) { while (node != null) { document.write(node.data + " -> "); node = node.next; } document.write("NULL"); } // Recursive function to return the // count of nodes in the linked list function cntNodes(node) { if (node == null) return 0; return 1 + cntNodes(node.next); } // Function to update and print // the updated list nodes function updateList(head, m) { // Total nodes in the list var cnt = cntNodes(head); if (cnt != m && m < cnt) { // Count of nodes to be skipped // from the beginning var skip = cnt - m; var prev = null; var curr = head; // Skip the nodes while (skip > 0) { prev = curr; curr = curr.next; skip--; } // Change the pointers prev.next = null; var tempHead = head; head = curr; // Find the last node while (curr.next != null) curr = curr.next; // Connect it to the head // of the sub list curr.next = tempHead; } // Print the updated list printList(head); } // Driver code // Create the list var head = new Node(4); head.next = new Node(5); head.next.next = new Node(6); head.next.next.next = new Node(1); head.next.next.next.next = new Node(2); head.next.next.next.next.next = new Node(3); var m = 3; updateList(head, m); // This code is contributed by rdtank. </script>
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
METHOD 2:
We Will use modififcation of runner’s technique :-
1. find the kth node from end using runner technique and do the following modifications
2. now we have to update our pointers as
a) fast->next will be pointing to head,
b)slow->next will be new head,
c)last node will be the slow->next hence it should point to null
C++
#include <iostream> using namespace std; struct node { int data; node* next; node(int x) { data = x; next = NULL; }}; void insertAtTail(node*& head, int x){ if (head == NULL) { head = new node(x); return; } node* curr = head; while (curr->next != NULL) { curr = curr->next; } node* t = new node(x); curr->next = t;} void print(node* head){ node* curr = head; while (curr != NULL) { cout << curr->data << " -> "; curr = curr->next; } cout << "NULL\n";} node* appendK(node* head, int k){ node* fast = head; node* slow = head; for (int i = 0; i < k; i++) { fast = fast->next; } while (fast->next != NULL) { slow = slow->next; fast = fast->next; } // cout<<"data"<<" "<<slow->data<<" "<<fast->data<<endl; fast->next = head; head = slow->next; slow->next = NULL; return head;} int main(){ node* head = NULL; int n; n = 6 ; insertAtTail(head, 4); insertAtTail(head, 5); insertAtTail(head, 6); insertAtTail(head, 1); insertAtTail(head, 2); insertAtTail(head, 3); int k; k = 3 ; head = appendK(head, k % n); print(head); return 0;}
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
princiraj1992
SHUBHAMSINGH10
Code_Mech
rutvik_56
rdtank
darkthunderassassin
Data Structures
Linked List
Data Structures
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Queue | Question 11
Multilevel Linked List
Program to create Custom Vector Class in C++
Data Structures | Stack | Question 4
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
|
[
{
"code": null,
"e": 25034,
"s": 25006,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 25155,
"s": 25034,
"text": "Given a linked list and an integer M, the task is to append the last M nodes of the linked list to the front.Examples: "
},
{
"code": null,
"e": 25344,
"s": 25155,
"text": "Input: List = 4 -> 5 -> 6 -> 1 -> 2 -> 3 -> NULL, M = 3 Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLInput: List = 8 -> 7 -> 0 -> 4 -> 1 -> NULL, M = 2 Output: 4 -> 1 -> 8 -> 7 -> 0 -> NULL "
},
{
"code": null,
"e": 25662,
"s": 25346,
"text": "Approach: Find the first node of the last M nodes in the list, this node will be the new head node so make the next pointer of the previous node as NULL and point the last node of the original list to the head of the original list. Finally, print the updated list.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25666,
"s": 25662,
"text": "C++"
},
{
"code": null,
"e": 25671,
"s": 25666,
"text": "Java"
},
{
"code": null,
"e": 25679,
"s": 25671,
"text": "Python3"
},
{
"code": null,
"e": 25682,
"s": 25679,
"text": "C#"
},
{
"code": null,
"e": 25693,
"s": 25682,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Class for a node of// the linked liststruct Node { // Data and the pointer // to the next node int data; Node* next; Node(int data) { this->data = data; this->next = NULL; }}; // Function to print the linked listvoid printList(Node* node){ while (node != NULL) { cout << (node->data) << \" -> \"; node = node->next; } cout << \"NULL\";} // Recursive function to return the// count of nodes in the linked listint cntNodes(Node* node){ if (node == NULL) return 0; return (1 + cntNodes(node->next));} // Function to update and print// the updated list nodesvoid updateList(Node* head, int m){ // Total nodes in the list int cnt = cntNodes(head); if (cnt != m && m < cnt) { // Count of nodes to be skipped // from the beginning int skip = cnt - m; Node* prev = NULL; Node* curr = head; // Skip the nodes while (skip > 0) { prev = curr; curr = curr->next; skip--; } // Change the pointers prev->next = NULL; Node* tempHead = head; head = curr; // Find the last node while (curr->next != NULL) curr = curr->next; // Connect it to the head // of the sub list curr->next = tempHead; } // Print the updated list printList(head);} // Driver codeint main(){ // Create the list Node* head = new Node(4); head->next = new Node(5); head->next->next = new Node(6); head->next->next->next = new Node(1); head->next->next->next->next = new Node(2); head->next->next->next->next->next = new Node(3); int m = 3; updateList(head, m); return 0;} // This code is contributed by rutvik_56",
"e": 27533,
"s": 25693,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Class for a node of // the linked list static class Node { // Data and the pointer // to the next node int data; Node next; Node(int data) { this.data = data; this.next = null; } } // Function to print the linked list static void printList(Node node) { while (node != null) { System.out.print(node.data + \" -> \"); node = node.next; } System.out.print(\"NULL\"); } // Recursive function to return the // count of nodes in the linked list static int cntNodes(Node node) { if (node == null) return 0; return (1 + cntNodes(node.next)); } // Function to update and print // the updated list nodes static void updateList(Node head, int m) { // Total nodes in the list int cnt = cntNodes(head); if (cnt != m && m < cnt) { // Count of nodes to be skipped // from the beginning int skip = cnt - m; Node prev = null; Node curr = head; // Skip the nodes while (skip > 0) { prev = curr; curr = curr.next; skip--; } // Change the pointers prev.next = null; Node tempHead = head; head = curr; // Find the last node while (curr.next != null) curr = curr.next; // Connect it to the head // of the sub list curr.next = tempHead; } // Print the updated list printList(head); } // Driver code public static void main(String[] args) { // Create the list Node head = new Node(4); head.next = new Node(5); head.next.next = new Node(6); head.next.next.next = new Node(1); head.next.next.next.next = new Node(2); head.next.next.next.next.next = new Node(3); int m = 3; updateList(head, m); }}",
"e": 29629,
"s": 27533,
"text": null
},
{
"code": "# Python3 implementation of the approach # Class for a node of# the linked list class newNode: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None # Function to print the linked list def printList(node): while (node != None): print(node.data, \"->\", end=\" \") node = node.next print(\"NULL\") # Recursive function to return the# count of nodes in the linked list def cntNodes(node): if (node == None): return 0 return (1 + cntNodes(node.next)) # Function to update and print# the updated list nodes def updateList(head, m): # Total nodes in the list cnt = cntNodes(head) if (cnt != m and m < cnt): # Count of nodes to be skipped # from the beginning skip = cnt - m prev = None curr = head # Skip the nodes while (skip > 0): prev = curr curr = curr.next skip -= 1 # Change the pointers prev.next = None tempHead = head head = curr # Find the last node while (curr.next != None): curr = curr.next # Connect it to the head # of the sub list curr.next = tempHead # Print the updated list printList(head) # Driver code # Create the listhead = newNode(4)head.next = newNode(5)head.next.next = newNode(6)head.next.next.next = newNode(1)head.next.next.next.next = newNode(2)head.next.next.next.next.next = newNode(3) m = 3 updateList(head, m) # This code is contributed by shubhamsingh10",
"e": 31198,
"s": 29629,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { // Class for a node of // the linked list class Node { // Data and the pointer // to the next node public int data; public Node next; public Node(int data) { this.data = data; this.next = null; } } // Function to print the linked list static void printList(Node node) { while (node != null) { Console.Write(node.data + \" -> \"); node = node.next; } Console.Write(\"NULL\"); } // Recursive function to return the // count of nodes in the linked list static int cntNodes(Node node) { if (node == null) return 0; return (1 + cntNodes(node.next)); } // Function to update and print // the updated list nodes static void updateList(Node head, int m) { // Total nodes in the list int cnt = cntNodes(head); if (cnt != m && m < cnt) { // Count of nodes to be skipped // from the beginning int skip = cnt - m; Node prev = null; Node curr = head; // Skip the nodes while (skip > 0) { prev = curr; curr = curr.next; skip--; } // Change the pointers prev.next = null; Node tempHead = head; head = curr; // Find the last node while (curr.next != null) curr = curr.next; // Connect it to the head // of the sub list curr.next = tempHead; } // Print the updated list printList(head); } // Driver code public static void Main(String[] args) { // Create the list Node head = new Node(4); head.next = new Node(5); head.next.next = new Node(6); head.next.next.next = new Node(1); head.next.next.next.next = new Node(2); head.next.next.next.next.next = new Node(3); int m = 3; updateList(head, m); }} // This code is contributed by PrinciRaj1992",
"e": 33359,
"s": 31198,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Class for a node of // the linked list class Node { // Data and the pointer // to the next node constructor(data) { this.data = data; this.next = null; } } // Function to print the linked list function printList(node) { while (node != null) { document.write(node.data + \" -> \"); node = node.next; } document.write(\"NULL\"); } // Recursive function to return the // count of nodes in the linked list function cntNodes(node) { if (node == null) return 0; return 1 + cntNodes(node.next); } // Function to update and print // the updated list nodes function updateList(head, m) { // Total nodes in the list var cnt = cntNodes(head); if (cnt != m && m < cnt) { // Count of nodes to be skipped // from the beginning var skip = cnt - m; var prev = null; var curr = head; // Skip the nodes while (skip > 0) { prev = curr; curr = curr.next; skip--; } // Change the pointers prev.next = null; var tempHead = head; head = curr; // Find the last node while (curr.next != null) curr = curr.next; // Connect it to the head // of the sub list curr.next = tempHead; } // Print the updated list printList(head); } // Driver code // Create the list var head = new Node(4); head.next = new Node(5); head.next.next = new Node(6); head.next.next.next = new Node(1); head.next.next.next.next = new Node(2); head.next.next.next.next.next = new Node(3); var m = 3; updateList(head, m); // This code is contributed by rdtank. </script>",
"e": 35312,
"s": 33359,
"text": null
},
{
"code": null,
"e": 35347,
"s": 35312,
"text": "1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL"
},
{
"code": null,
"e": 35357,
"s": 35347,
"text": "METHOD 2:"
},
{
"code": null,
"e": 35408,
"s": 35357,
"text": "We Will use modififcation of runner’s technique :-"
},
{
"code": null,
"e": 35496,
"s": 35408,
"text": "1. find the kth node from end using runner technique and do the following modifications"
},
{
"code": null,
"e": 35537,
"s": 35496,
"text": "2. now we have to update our pointers as"
},
{
"code": null,
"e": 35577,
"s": 35537,
"text": "a) fast->next will be pointing to head,"
},
{
"code": null,
"e": 35608,
"s": 35577,
"text": "b)slow->next will be new head,"
},
{
"code": null,
"e": 35673,
"s": 35608,
"text": "c)last node will be the slow->next hence it should point to null"
},
{
"code": null,
"e": 35677,
"s": 35673,
"text": "C++"
},
{
"code": "#include <iostream> using namespace std; struct node { int data; node* next; node(int x) { data = x; next = NULL; }}; void insertAtTail(node*& head, int x){ if (head == NULL) { head = new node(x); return; } node* curr = head; while (curr->next != NULL) { curr = curr->next; } node* t = new node(x); curr->next = t;} void print(node* head){ node* curr = head; while (curr != NULL) { cout << curr->data << \" -> \"; curr = curr->next; } cout << \"NULL\\n\";} node* appendK(node* head, int k){ node* fast = head; node* slow = head; for (int i = 0; i < k; i++) { fast = fast->next; } while (fast->next != NULL) { slow = slow->next; fast = fast->next; } // cout<<\"data\"<<\" \"<<slow->data<<\" \"<<fast->data<<endl; fast->next = head; head = slow->next; slow->next = NULL; return head;} int main(){ node* head = NULL; int n; n = 6 ; insertAtTail(head, 4); insertAtTail(head, 5); insertAtTail(head, 6); insertAtTail(head, 1); insertAtTail(head, 2); insertAtTail(head, 3); int k; k = 3 ; head = appendK(head, k % n); print(head); return 0;}",
"e": 36930,
"s": 35677,
"text": null
},
{
"code": null,
"e": 36966,
"s": 36930,
"text": "1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL\n"
},
{
"code": null,
"e": 36980,
"s": 36966,
"text": "princiraj1992"
},
{
"code": null,
"e": 36995,
"s": 36980,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 37005,
"s": 36995,
"text": "Code_Mech"
},
{
"code": null,
"e": 37015,
"s": 37005,
"text": "rutvik_56"
},
{
"code": null,
"e": 37022,
"s": 37015,
"text": "rdtank"
},
{
"code": null,
"e": 37042,
"s": 37022,
"text": "darkthunderassassin"
},
{
"code": null,
"e": 37058,
"s": 37042,
"text": "Data Structures"
},
{
"code": null,
"e": 37070,
"s": 37058,
"text": "Linked List"
},
{
"code": null,
"e": 37086,
"s": 37070,
"text": "Data Structures"
},
{
"code": null,
"e": 37098,
"s": 37086,
"text": "Linked List"
},
{
"code": null,
"e": 37196,
"s": 37098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37234,
"s": 37196,
"text": "Data Structures | Queue | Question 11"
},
{
"code": null,
"e": 37257,
"s": 37234,
"text": "Multilevel Linked List"
},
{
"code": null,
"e": 37302,
"s": 37257,
"text": "Program to create Custom Vector Class in C++"
},
{
"code": null,
"e": 37339,
"s": 37302,
"text": "Data Structures | Stack | Question 4"
},
{
"code": null,
"e": 37422,
"s": 37339,
"text": "Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]"
},
{
"code": null,
"e": 37457,
"s": 37422,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 37496,
"s": 37457,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 37518,
"s": 37496,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 37566,
"s": 37518,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Dart - Getters and Setters - GeeksforGeeks
|
14 Jul, 2020
Getters and Setters, also called accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively.
Getters or accessors are defined using the get keyword.
Setters or mutators are defined using the set keyword.
A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value.
Syntax: Defining a getter
Return_type get identifier
{
// statements
}
Syntax: Defining a setter
set identifier
{
// statements
}
Example 1:
The following example shows how you can use getters and setters in a Dart class:
Dart
// Dart Program in Dart to illustrate// getters and setters #GFGclass Student { String name; int age; String get stud_name { return name; } void set stud_name(String name) { this.name = name; } void set stud_age(int age) { if(age<= 0) { print("Age should be greater than 5"); } else { this.age = age; } } int get stud_age { return age; } } void main() { Student s1 = new Student(); s1.stud_name = 'Nitin'; s1.stud_age = 0; print(s1.stud_name); print(s1.stud_age); }
Output:
Age should be greater than 5
Nitin
Null
Example 2:
Dart
// Dart program in Dart to illustrate// getters and setters #GFGvoid main() { var cat = new Cat(); // Is cat hungry? true print("Is cat hungry? ${cat.isHungry}"); // Is cat cuddly? false print("Is cat cuddly? ${cat.isCuddly}"); print("Feed cat."); cat.isHungry = false; // Is cat hungry? false print("Is cat hungry? ${cat.isHungry}"); // Is cat cuddly? true print("Is cat cuddly? ${cat.isCuddly}"); } class Cat { bool _isHungry = true; bool get isCuddly => !_isHungry; bool get isHungry => _isHungry; bool set isHungry(bool hungry) => this._isHungry = hungry;}
Output:
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - BoxShadow Widget
Dart Tutorial
ListView Class in Flutter
How to Append or Concatenate Strings in Dart?
Flutter - Flexible Widget
Operators in Dart
Flutter - Stack Widget
|
[
{
"code": null,
"e": 24026,
"s": 23998,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 24170,
"s": 24026,
"text": "Getters and Setters, also called accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. "
},
{
"code": null,
"e": 24226,
"s": 24170,
"text": "Getters or accessors are defined using the get keyword."
},
{
"code": null,
"e": 24281,
"s": 24226,
"text": "Setters or mutators are defined using the set keyword."
},
{
"code": null,
"e": 24532,
"s": 24281,
"text": "A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value."
},
{
"code": null,
"e": 24617,
"s": 24532,
"text": "Syntax: Defining a getter\n \nReturn_type get identifier \n{ \n // statements\n} \n"
},
{
"code": null,
"e": 24686,
"s": 24617,
"text": "Syntax: Defining a setter\n \nset identifier \n{ \n // statements\n}\n"
},
{
"code": null,
"e": 24697,
"s": 24686,
"text": "Example 1:"
},
{
"code": null,
"e": 24778,
"s": 24697,
"text": "The following example shows how you can use getters and setters in a Dart class:"
},
{
"code": null,
"e": 24783,
"s": 24778,
"text": "Dart"
},
{
"code": "// Dart Program in Dart to illustrate// getters and setters #GFGclass Student { String name; int age; String get stud_name { return name; } void set stud_name(String name) { this.name = name; } void set stud_age(int age) { if(age<= 0) { print(\"Age should be greater than 5\"); } else { this.age = age; } } int get stud_age { return age; } } void main() { Student s1 = new Student(); s1.stud_name = 'Nitin'; s1.stud_age = 0; print(s1.stud_name); print(s1.stud_age); }",
"e": 25375,
"s": 24783,
"text": null
},
{
"code": null,
"e": 25383,
"s": 25375,
"text": "Output:"
},
{
"code": null,
"e": 25427,
"s": 25383,
"text": "Age should be greater than 5 \nNitin\nNull \n"
},
{
"code": null,
"e": 25438,
"s": 25427,
"text": "Example 2:"
},
{
"code": null,
"e": 25443,
"s": 25438,
"text": "Dart"
},
{
"code": "// Dart program in Dart to illustrate// getters and setters #GFGvoid main() { var cat = new Cat(); // Is cat hungry? true print(\"Is cat hungry? ${cat.isHungry}\"); // Is cat cuddly? false print(\"Is cat cuddly? ${cat.isCuddly}\"); print(\"Feed cat.\"); cat.isHungry = false; // Is cat hungry? false print(\"Is cat hungry? ${cat.isHungry}\"); // Is cat cuddly? true print(\"Is cat cuddly? ${cat.isCuddly}\"); } class Cat { bool _isHungry = true; bool get isCuddly => !_isHungry; bool get isHungry => _isHungry; bool set isHungry(bool hungry) => this._isHungry = hungry;}",
"e": 26054,
"s": 25443,
"text": null
},
{
"code": null,
"e": 26062,
"s": 26054,
"text": "Output:"
},
{
"code": null,
"e": 26067,
"s": 26062,
"text": "Dart"
},
{
"code": null,
"e": 26165,
"s": 26067,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26197,
"s": 26165,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 26236,
"s": 26197,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 26262,
"s": 26236,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 26289,
"s": 26262,
"text": "Flutter - BoxShadow Widget"
},
{
"code": null,
"e": 26303,
"s": 26289,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 26329,
"s": 26303,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 26375,
"s": 26329,
"text": "How to Append or Concatenate Strings in Dart?"
},
{
"code": null,
"e": 26401,
"s": 26375,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 26419,
"s": 26401,
"text": "Operators in Dart"
}
] |
C# | Total number of elements present in an array - GeeksforGeeks
|
04 Aug, 2021
Array.GetLength(Int32) Method is used to find the total number of elements present in the specified dimension of the Array. Syntax:
public int GetLength (int dimension);
Here, dimension is a zero-based dimension of the Array whose length needs to be determined.Return value: The return type of this method is System.Int32. This method return a 32-bit integer that represents the number of elements in the specified dimension.Exception:This method will give IndexOutOfRangeException if the value of dimension is less than zero or if the value of dimension is equal to or greater than Rank.Below given are some examples to understand the implementation in a better way: Example 1:
CSharp
// C# program to illustrate the// use of GetLength() methodusing System; public class GFG { // Main method static public void Main() { // create and initialize array int[] myarray = {445, 44, 66, 6666667, 78, 878, 1}; // Display the array Console.WriteLine("The elements of myarray :"); foreach(int i in myarray) { Console.WriteLine(i); } // Find the number of element in myarray int result = myarray.GetLength(0); Console.WriteLine("Total Elements: {0}", result); }}
The elements of myarray :
445
44
66
6666667
78
878
1
Total Elements: 7
Example 2:
CSharp
// C# program to check arrays contain// same number of elements or notusing System; public class GFG { // Main method static public void Main() { // create and initializing array int[] myarray1 = {100, 0, 400, 660, 700, 809, 0}; int[] myarray2 = {100, 0, 400, 660, 700}; int[] myarray3 = {100, 0, 400, 660, 700, 809, 0}; // Find the number of element in myarray // using GetLength() method int result1 = myarray1.GetLength(0); int result2 = myarray2.GetLength(0); int result3 = myarray3.GetLength(0); // Check if myarray1, myarray2, myarray3 // contain the same number of elements or not Console.WriteLine("myarray1 and myarray2: {0}", Equals(result1, result2)); Console.WriteLine("myarray1 and myarray3: {0}", Equals(result1, result3)); }}
myarray1 and myarray2: False
myarray1 and myarray3: True
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.getlength?view=netcore-2.1
gabaa406
CSharp-Arrays
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
C# | Constructors
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
|
[
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 24859,
"s": 24725,
"text": "Array.GetLength(Int32) Method is used to find the total number of elements present in the specified dimension of the Array. Syntax: "
},
{
"code": null,
"e": 24897,
"s": 24859,
"text": "public int GetLength (int dimension);"
},
{
"code": null,
"e": 25406,
"s": 24897,
"text": "Here, dimension is a zero-based dimension of the Array whose length needs to be determined.Return value: The return type of this method is System.Int32. This method return a 32-bit integer that represents the number of elements in the specified dimension.Exception:This method will give IndexOutOfRangeException if the value of dimension is less than zero or if the value of dimension is equal to or greater than Rank.Below given are some examples to understand the implementation in a better way: Example 1:"
},
{
"code": null,
"e": 25413,
"s": 25406,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the// use of GetLength() methodusing System; public class GFG { // Main method static public void Main() { // create and initialize array int[] myarray = {445, 44, 66, 6666667, 78, 878, 1}; // Display the array Console.WriteLine(\"The elements of myarray :\"); foreach(int i in myarray) { Console.WriteLine(i); } // Find the number of element in myarray int result = myarray.GetLength(0); Console.WriteLine(\"Total Elements: {0}\", result); }}",
"e": 25991,
"s": 25413,
"text": null
},
{
"code": null,
"e": 26062,
"s": 25991,
"text": "The elements of myarray :\n445\n44\n66\n6666667\n78\n878\n1\nTotal Elements: 7"
},
{
"code": null,
"e": 26075,
"s": 26064,
"text": "Example 2:"
},
{
"code": null,
"e": 26082,
"s": 26075,
"text": "CSharp"
},
{
"code": "// C# program to check arrays contain// same number of elements or notusing System; public class GFG { // Main method static public void Main() { // create and initializing array int[] myarray1 = {100, 0, 400, 660, 700, 809, 0}; int[] myarray2 = {100, 0, 400, 660, 700}; int[] myarray3 = {100, 0, 400, 660, 700, 809, 0}; // Find the number of element in myarray // using GetLength() method int result1 = myarray1.GetLength(0); int result2 = myarray2.GetLength(0); int result3 = myarray3.GetLength(0); // Check if myarray1, myarray2, myarray3 // contain the same number of elements or not Console.WriteLine(\"myarray1 and myarray2: {0}\", Equals(result1, result2)); Console.WriteLine(\"myarray1 and myarray3: {0}\", Equals(result1, result3)); }}",
"e": 27020,
"s": 26082,
"text": null
},
{
"code": null,
"e": 27077,
"s": 27020,
"text": "myarray1 and myarray2: False\nmyarray1 and myarray3: True"
},
{
"code": null,
"e": 27175,
"s": 27079,
"text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.getlength?view=netcore-2.1 "
},
{
"code": null,
"e": 27184,
"s": 27175,
"text": "gabaa406"
},
{
"code": null,
"e": 27198,
"s": 27184,
"text": "CSharp-Arrays"
},
{
"code": null,
"e": 27212,
"s": 27198,
"text": "CSharp-method"
},
{
"code": null,
"e": 27215,
"s": 27212,
"text": "C#"
},
{
"code": null,
"e": 27313,
"s": 27215,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27322,
"s": 27313,
"text": "Comments"
},
{
"code": null,
"e": 27335,
"s": 27322,
"text": "Old Comments"
},
{
"code": null,
"e": 27358,
"s": 27335,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 27386,
"s": 27358,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27432,
"s": 27386,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27447,
"s": 27432,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27487,
"s": 27447,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27518,
"s": 27487,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27536,
"s": 27518,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27559,
"s": 27536,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27581,
"s": 27559,
"text": "C# | Class and Object"
}
] |
Vehicle Detection and Tracking | by Nick Hortovanyi | Towards Data Science
|
In this vehicle detection and tracking project, we detect in a video pipeline, potential boxes, via a sliding window, that may contain a vehicle by using a Support Vector Machine Classifier for prediction to create a heat map. The heat map history is then used to filter out false positives before identification of vehicles by drawing a bounding box around it.
Vehicle Detection Project
The goals / steps of this project are the following:
Perform a Histogram of Oriented Gradients (HOG) feature extraction on a labeled training set of images and train a classifier Linear SVM classifier
Optionally, you can also apply a color transform and append binned color features, as well as histograms of color, to your HOG feature vector.
Note: for those first two steps don’t forget to normalize your features and randomize a selection for training and testing.
Implement a sliding-window technique and use your trained classifier to search for vehicles in images.
Run your pipeline on a video stream (start with the test_video.mp4 and later implement on full project_video.mp4) and create a heat map of recurring detections frame by frame to reject outliers and follow detected vehicles.
Estimate a bounding box for vehicles detected.
A jupyter/iPython data science notebook was used and can be found on github Full Project Repo — Vehicle Detection Project Notebook (Note the interactive ipywidgets are not functional on github). As the notebook got rather large I extracted some code into python files utils.py (functions to extract, loading helpers), features.py (feature extraction and classes), images.py (image and window slice processing), search.py (holds search parameters class), boxes.py (windowing and box classes) and detection.py (main VehicleDetection class that coordinates processing of images). The project is written in python and utilises numpy, OpenCV, scikit learn and MoviePy.
Through a bit of trial and error I found a set of HOG parameters.
A function extract_hog_features was created that took an array of 64x64x3 images and returned a set of features. These are extracted in parallel and it in turn uses HogImageFeatures class.
As the hog algorithm is primarily focused on grey images, I initially used the YCrCB colour space with the Y channel (used to represent a gray images). However I found that it was not selective enough during the detection phase. I thus used all 3 colour channels. To reduce the number of features, I increased the number of HOG pixels per cell. I used an interactive feature in my notebook to find an orient setting of 32 that showed distinctive features of vehicle. Sample follows.
The final parameter settings used color_space = 'YCrCb',orient = 32,pix_per_cell = 16 and hog_channel = 'ALL'. Experimentation occurred with using Colour Histogram Features but it slowed down feature extraction and later increased the number of false positives detected. Per the following visualisation graphic, you can see that the Cr and Cb colour spaces had detectable hog features
Once HOG features (no Colour Hist or Bin Spatial) were extracted from car (GTI Vehicle Image Database and Udacity Extras) and not_car (GTI, KITTI) image sets. They were then stacked and converted to float in the vehicle detection notebook.
Features were then scaled using the Sklearn RobustScaler sample result follows.
Experimentation occurred in the Classifier Experimentation Notebook between LinearSVC (Support Vector Machine Classifier), RandomForest and ExtraTrees classifiers. LinearSVC was chosen as the prediction time was 0.00228 seconds for 10 labels compared to ~0.10 seconds for the other two.
For this project four sizes of windows were chosen — 32x32, 48x48, 64x64 and 128x128 and position at different depth perspective on the bottom right side of the image to cover the road. The larger windows closer to the driver and the smaller closer to the horizon. Overlap in both x,y was set between 0.5 and 0.8 to balance the need for better coverage vs number of boxes generated — currently 937. The more boxes for a sliding window, the more calculations per video image.
Some time was spent on parallelisation of the search using Python async methods and asyncio.gather in the VehicleDetection class. The search extracts the bounded box image of each sized search window and scales it to 64x64 before doing feature extraction and prediction on each window.
The search hot_box_search returns an array of hot boxes that classifier has predicted contains a vehicle.
These boxes overlap and are used to create a clipped at 255, two dimensional heat map. To remove initial false positives counts > 4 are kept. The heat map is then normalised before another threshold is applied
heatmap = apply_threshold(heatmap, 4)heatmap_std = heatmap.std(ddof=1)if heatmap_std != 0.0: heatmap = (heatmap-heatmap.mean())/heatmap_stdheatmap = apply_threshold(heatmap, np.max([heatmap.std(), 1]))
Plotting this stage back onto the image
A history is kept of heat maps
which is then used as input into Scipy Label with a dim binary structure linking dimensions, giving
finally a variance filter is applied on each box, if for one detected label boxes are ignored with a variance < 0.1 (its just a few close points0 or if multiple with a variance < 1.5 (more noise).
The Project VehicleDetection mp4 on GitHub, contains the result (YouTube Copy)
One of the nice features of the scipy.ndimage.measurements.label function is that it can process 3d arrays giving labels in x,y,z spaces. Thus when using the array of heat map history as input, it labels connections in x,y,z. If a returned label box is not represented in at least 3 (heat map history max — 2) z planes then it is rejected as a false positive. The result is that a vehicle is tracked over the heat map history kept.
When construction this pipeline, I spent some time working on parallelising the window search. What I found is that there is most likely little overall performance improvement to be gained by doing so. Images have to be processed in series and whilst generating the video, my cpu was under utilised.
In hindsight I should of used a heavy weight search to detect vehicles and then a more lighter weight, narrower search primed by the last known positions. Heavy weight searching could be run at larger intervals or when a vehicle detection is lost.
My pipeline would fail presently if vehicles were on the left hand side or centre of the car. I suspect trucks, motorbikes, cyclists and pedestrians would not be detected (as they are not in the training data).
|
[
{
"code": null,
"e": 534,
"s": 172,
"text": "In this vehicle detection and tracking project, we detect in a video pipeline, potential boxes, via a sliding window, that may contain a vehicle by using a Support Vector Machine Classifier for prediction to create a heat map. The heat map history is then used to filter out false positives before identification of vehicles by drawing a bounding box around it."
},
{
"code": null,
"e": 560,
"s": 534,
"text": "Vehicle Detection Project"
},
{
"code": null,
"e": 613,
"s": 560,
"text": "The goals / steps of this project are the following:"
},
{
"code": null,
"e": 761,
"s": 613,
"text": "Perform a Histogram of Oriented Gradients (HOG) feature extraction on a labeled training set of images and train a classifier Linear SVM classifier"
},
{
"code": null,
"e": 904,
"s": 761,
"text": "Optionally, you can also apply a color transform and append binned color features, as well as histograms of color, to your HOG feature vector."
},
{
"code": null,
"e": 1028,
"s": 904,
"text": "Note: for those first two steps don’t forget to normalize your features and randomize a selection for training and testing."
},
{
"code": null,
"e": 1131,
"s": 1028,
"text": "Implement a sliding-window technique and use your trained classifier to search for vehicles in images."
},
{
"code": null,
"e": 1355,
"s": 1131,
"text": "Run your pipeline on a video stream (start with the test_video.mp4 and later implement on full project_video.mp4) and create a heat map of recurring detections frame by frame to reject outliers and follow detected vehicles."
},
{
"code": null,
"e": 1402,
"s": 1355,
"text": "Estimate a bounding box for vehicles detected."
},
{
"code": null,
"e": 2066,
"s": 1402,
"text": "A jupyter/iPython data science notebook was used and can be found on github Full Project Repo — Vehicle Detection Project Notebook (Note the interactive ipywidgets are not functional on github). As the notebook got rather large I extracted some code into python files utils.py (functions to extract, loading helpers), features.py (feature extraction and classes), images.py (image and window slice processing), search.py (holds search parameters class), boxes.py (windowing and box classes) and detection.py (main VehicleDetection class that coordinates processing of images). The project is written in python and utilises numpy, OpenCV, scikit learn and MoviePy."
},
{
"code": null,
"e": 2132,
"s": 2066,
"text": "Through a bit of trial and error I found a set of HOG parameters."
},
{
"code": null,
"e": 2321,
"s": 2132,
"text": "A function extract_hog_features was created that took an array of 64x64x3 images and returned a set of features. These are extracted in parallel and it in turn uses HogImageFeatures class."
},
{
"code": null,
"e": 2804,
"s": 2321,
"text": "As the hog algorithm is primarily focused on grey images, I initially used the YCrCB colour space with the Y channel (used to represent a gray images). However I found that it was not selective enough during the detection phase. I thus used all 3 colour channels. To reduce the number of features, I increased the number of HOG pixels per cell. I used an interactive feature in my notebook to find an orient setting of 32 that showed distinctive features of vehicle. Sample follows."
},
{
"code": null,
"e": 3189,
"s": 2804,
"text": "The final parameter settings used color_space = 'YCrCb',orient = 32,pix_per_cell = 16 and hog_channel = 'ALL'. Experimentation occurred with using Colour Histogram Features but it slowed down feature extraction and later increased the number of false positives detected. Per the following visualisation graphic, you can see that the Cr and Cb colour spaces had detectable hog features"
},
{
"code": null,
"e": 3429,
"s": 3189,
"text": "Once HOG features (no Colour Hist or Bin Spatial) were extracted from car (GTI Vehicle Image Database and Udacity Extras) and not_car (GTI, KITTI) image sets. They were then stacked and converted to float in the vehicle detection notebook."
},
{
"code": null,
"e": 3509,
"s": 3429,
"text": "Features were then scaled using the Sklearn RobustScaler sample result follows."
},
{
"code": null,
"e": 3796,
"s": 3509,
"text": "Experimentation occurred in the Classifier Experimentation Notebook between LinearSVC (Support Vector Machine Classifier), RandomForest and ExtraTrees classifiers. LinearSVC was chosen as the prediction time was 0.00228 seconds for 10 labels compared to ~0.10 seconds for the other two."
},
{
"code": null,
"e": 4271,
"s": 3796,
"text": "For this project four sizes of windows were chosen — 32x32, 48x48, 64x64 and 128x128 and position at different depth perspective on the bottom right side of the image to cover the road. The larger windows closer to the driver and the smaller closer to the horizon. Overlap in both x,y was set between 0.5 and 0.8 to balance the need for better coverage vs number of boxes generated — currently 937. The more boxes for a sliding window, the more calculations per video image."
},
{
"code": null,
"e": 4557,
"s": 4271,
"text": "Some time was spent on parallelisation of the search using Python async methods and asyncio.gather in the VehicleDetection class. The search extracts the bounded box image of each sized search window and scales it to 64x64 before doing feature extraction and prediction on each window."
},
{
"code": null,
"e": 4663,
"s": 4557,
"text": "The search hot_box_search returns an array of hot boxes that classifier has predicted contains a vehicle."
},
{
"code": null,
"e": 4873,
"s": 4663,
"text": "These boxes overlap and are used to create a clipped at 255, two dimensional heat map. To remove initial false positives counts > 4 are kept. The heat map is then normalised before another threshold is applied"
},
{
"code": null,
"e": 5078,
"s": 4873,
"text": "heatmap = apply_threshold(heatmap, 4)heatmap_std = heatmap.std(ddof=1)if heatmap_std != 0.0: heatmap = (heatmap-heatmap.mean())/heatmap_stdheatmap = apply_threshold(heatmap, np.max([heatmap.std(), 1]))"
},
{
"code": null,
"e": 5118,
"s": 5078,
"text": "Plotting this stage back onto the image"
},
{
"code": null,
"e": 5149,
"s": 5118,
"text": "A history is kept of heat maps"
},
{
"code": null,
"e": 5249,
"s": 5149,
"text": "which is then used as input into Scipy Label with a dim binary structure linking dimensions, giving"
},
{
"code": null,
"e": 5446,
"s": 5249,
"text": "finally a variance filter is applied on each box, if for one detected label boxes are ignored with a variance < 0.1 (its just a few close points0 or if multiple with a variance < 1.5 (more noise)."
},
{
"code": null,
"e": 5525,
"s": 5446,
"text": "The Project VehicleDetection mp4 on GitHub, contains the result (YouTube Copy)"
},
{
"code": null,
"e": 5957,
"s": 5525,
"text": "One of the nice features of the scipy.ndimage.measurements.label function is that it can process 3d arrays giving labels in x,y,z spaces. Thus when using the array of heat map history as input, it labels connections in x,y,z. If a returned label box is not represented in at least 3 (heat map history max — 2) z planes then it is rejected as a false positive. The result is that a vehicle is tracked over the heat map history kept."
},
{
"code": null,
"e": 6257,
"s": 5957,
"text": "When construction this pipeline, I spent some time working on parallelising the window search. What I found is that there is most likely little overall performance improvement to be gained by doing so. Images have to be processed in series and whilst generating the video, my cpu was under utilised."
},
{
"code": null,
"e": 6505,
"s": 6257,
"text": "In hindsight I should of used a heavy weight search to detect vehicles and then a more lighter weight, narrower search primed by the last known positions. Heavy weight searching could be run at larger intervals or when a vehicle detection is lost."
}
] |
SymPy | Subset.subset() in Python - GeeksforGeeks
|
28 Aug, 2019
Subset.subset() : subset() is a sympy Python library function that returns the subset represented by the current instance.
Syntax :sympy.combinatorics.subset.Subset.subset()
Return :the subset represented by the current instance.
Code #1 : subset() Example
# Python code explaining# SymPy.Subset.subset() # importing SymPy librariesfrom sympy.combinatorics import Permutation, Cyclefrom sympy.combinatorics.subsets import Subset # Using from # sympy.combinatorics.subset.Subsets.subset() # Creating Subseta = Subset(['c', 'd'], ['geek', 'for', 'c', 'd']) # subset valueprint ("Subset a subset : ", a.subset)
Output :
Subset a subset : [‘c’, ‘d’]
Code #2 : subset() Example
# Python code explaining# SymPy.Subset.subset() # importing SymPy librariesfrom sympy.combinatorics import Permutation, Cyclefrom sympy.combinatorics.subsets import Subset # Using from # sympy.combinatorics.subset.Subsets.subset() # Creating Subseta = Subset([2, 3, 4], [1, 2, 3, 4, 5]) # subset valueprint ("Subset a subset : ", a.subset)
Output :
Subset a subset : [2, 3, 4]
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 24415,
"s": 24292,
"text": "Subset.subset() : subset() is a sympy Python library function that returns the subset represented by the current instance."
},
{
"code": null,
"e": 24466,
"s": 24415,
"text": "Syntax :sympy.combinatorics.subset.Subset.subset()"
},
{
"code": null,
"e": 24522,
"s": 24466,
"text": "Return :the subset represented by the current instance."
},
{
"code": null,
"e": 24549,
"s": 24522,
"text": "Code #1 : subset() Example"
},
{
"code": "# Python code explaining# SymPy.Subset.subset() # importing SymPy librariesfrom sympy.combinatorics import Permutation, Cyclefrom sympy.combinatorics.subsets import Subset # Using from # sympy.combinatorics.subset.Subsets.subset() # Creating Subseta = Subset(['c', 'd'], ['geek', 'for', 'c', 'd']) # subset valueprint (\"Subset a subset : \", a.subset)",
"e": 24904,
"s": 24549,
"text": null
},
{
"code": null,
"e": 24913,
"s": 24904,
"text": "Output :"
},
{
"code": null,
"e": 24942,
"s": 24913,
"text": "Subset a subset : [‘c’, ‘d’]"
},
{
"code": null,
"e": 24969,
"s": 24942,
"text": "Code #2 : subset() Example"
},
{
"code": "# Python code explaining# SymPy.Subset.subset() # importing SymPy librariesfrom sympy.combinatorics import Permutation, Cyclefrom sympy.combinatorics.subsets import Subset # Using from # sympy.combinatorics.subset.Subsets.subset() # Creating Subseta = Subset([2, 3, 4], [1, 2, 3, 4, 5]) # subset valueprint (\"Subset a subset : \", a.subset)",
"e": 25313,
"s": 24969,
"text": null
},
{
"code": null,
"e": 25322,
"s": 25313,
"text": "Output :"
},
{
"code": null,
"e": 25350,
"s": 25322,
"text": "Subset a subset : [2, 3, 4]"
},
{
"code": null,
"e": 25357,
"s": 25350,
"text": "Python"
},
{
"code": null,
"e": 25455,
"s": 25357,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25464,
"s": 25455,
"text": "Comments"
},
{
"code": null,
"e": 25477,
"s": 25464,
"text": "Old Comments"
},
{
"code": null,
"e": 25509,
"s": 25477,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25565,
"s": 25509,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25620,
"s": 25565,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25662,
"s": 25620,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25704,
"s": 25662,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25735,
"s": 25704,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25774,
"s": 25735,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25803,
"s": 25774,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 25825,
"s": 25803,
"text": "Defaultdict in Python"
}
] |
Gensim - Creating a Dictionary
|
In last chapter where we discussed about vector and model, you got an idea about the dictionary. Here, we are going to discuss Dictionary object in a bit more detail.
Before getting deep dive into the concept of dictionary, let’s understand some simple NLP concepts −
Token − A token means a ‘word’.
Token − A token means a ‘word’.
Document − A document refers to a sentence or paragraph.
Document − A document refers to a sentence or paragraph.
Corpus − It refers to a collection of documents as a bag of words (BoW).
Corpus − It refers to a collection of documents as a bag of words (BoW).
For all the documents, a corpus always contains each word’s token’s id along with its frequency count in the document.
Let’s move to the concept of dictionary in Gensim. For working on text documents, Gensim also requires the words, i.e. tokens to be converted to their unique ids. For achieving this, it gives us the facility of Dictionary object, which maps each word to their unique integer id. It does this by converting input text to the list of words and then pass it to the corpora.Dictionary() object.
Now the question arises that what is actually the need of dictionary object and where it can be used? In Gensim, the dictionary object is used to create a bag of words (BoW) corpus which further used as the input to topic modelling and other models as well.
There are three different forms of input text, we can provide to Gensim −
As the sentences stored in Python’s native list object (known as str in Python 3)
As the sentences stored in Python’s native list object (known as str in Python 3)
As one single text file (can be small or large one)
As one single text file (can be small or large one)
Multiple text files
Multiple text files
As discussed, in Gensim, the dictionary contains the mapping of all words, a.k.a tokens to their unique integer id. We can create a dictionary from list of sentences, from one or more than one text files (text file containing multiple lines of text). So, first let’s start by creating dictionary using list of sentences.
In the following example we will be creating dictionary from a list of sentences. When we have list of sentences or you can say multiple sentences, we must convert every sentence to a list of words and comprehensions is one of the very common ways to do this.
First, import the required and necessary packages as follows −
import gensim
from gensim import corpora
from pprint import pprint
Next, make the comprehension list from list of sentences/document to use it creating the dictionary −
doc = [
"CNTK formerly known as Computational Network Toolkit",
"is a free easy-to-use open-source commercial-grade toolkit",
"that enable us to train deep learning algorithms to learn like the human brain."
]
Next, we need to split the sentences into words. It is called tokenisation.
text_tokens = [[text for text in doc.split()] for doc in doc]
Now, with the help of following script, we can create the dictionary −
dict_LoS = corpora.Dictionary(text_tokens)
Now let’s get some more information like number of tokens in the dictionary −
print(dict_LoS)
Dictionary(27 unique tokens: ['CNTK', 'Computational', 'Network', 'Toolkit', 'as']...)
We can also see the word to unique integer mapping as follows −
print(dict_LoS.token2id)
{
'CNTK': 0, 'Computational': 1, 'Network': 2, 'Toolkit': 3, 'as': 4,
'formerly': 5, 'known': 6, 'a': 7, 'commercial-grade': 8, 'easy-to-use': 9,
'free': 10, 'is': 11, 'open-source': 12, 'toolkit': 13, 'algorithms': 14,
'brain.': 15, 'deep': 16, 'enable': 17, 'human': 18, 'learn': 19, 'learning': 20,
'like': 21, 'that': 22, 'the': 23, 'to': 24, 'train': 25, 'us': 26
}
import gensim
from gensim import corpora
from pprint import pprint
doc = [
"CNTK formerly known as Computational Network Toolkit",
"is a free easy-to-use open-source commercial-grade toolkit",
"that enable us to train deep learning algorithms to learn like the human brain."
]
text_tokens = [[text for text in doc.split()] for doc in doc]
dict_LoS = corpora.Dictionary(text_tokens)
print(dict_LoS.token2id)
In the following example we will be creating dictionary from a single text file. In the similar fashion, we can also create dictionary from more than one text files (i.e. directory of files).
For this, we have saved the document, used in previous example, in the text file named doc.txt. Gensim will read the file line by line and process one line at a time by using simple_preprocess. In this way, it doesn’t need to load the complete file in memory all at once.
First, import the required and necessary packages as follows −
import gensim
from gensim import corpora
from pprint import pprint
from gensim.utils import simple_preprocess
from smart_open import smart_open
import os
Next line of codes will make gensim dictionary by using the single text file named doc.txt −
dict_STF = corpora.Dictionary(
simple_preprocess(line, deacc =True) for line in open(‘doc.txt’, encoding=’utf-8’)
)
Now let’s get some more information like number of tokens in the dictionary −
print(dict_STF)
Dictionary(27 unique tokens: ['CNTK', 'Computational', 'Network', 'Toolkit', 'as']...)
We can also see the word to unique integer mapping as follows −
print(dict_STF.token2id)
{
'CNTK': 0, 'Computational': 1, 'Network': 2, 'Toolkit': 3, 'as': 4,
'formerly': 5, 'known': 6, 'a': 7, 'commercial-grade': 8, 'easy-to-use': 9,
'free': 10, 'is': 11, 'open-source': 12, 'toolkit': 13, 'algorithms': 14,
'brain.': 15, 'deep': 16, 'enable': 17, 'human': 18, 'learn': 19,
'learning': 20, 'like': 21, 'that': 22, 'the': 23, 'to': 24, 'train': 25, 'us': 26
}
import gensim
from gensim import corpora
from pprint import pprint
from gensim.utils import simple_preprocess
from smart_open import smart_open
import os
dict_STF = corpora.Dictionary(
simple_preprocess(line, deacc =True) for line in open(‘doc.txt’, encoding=’utf-8’)
)
dict_STF = corpora.Dictionary(text_tokens)
print(dict_STF.token2id)
Now let’s create dictionary from multiple files, i.e. more than one text file saved in the same directory. For this example, we have created three different text files namely first.txt, second.txt and third.txtcontaining the three lines from text file (doc.txt), we used for previous example. All these three text files are saved under a directory named ABC.
In order to implement this, we need to define a class with a method that can iterate through all the three text files (First, Second, and Third.txt) in the directory (ABC) and yield the processed list of words tokens.
Let’s define the class named Read_files having a method named __iteration__() as follows −
class Read_files(object):
def __init__(self, directoryname):
elf.directoryname = directoryname
def __iter__(self):
for fname in os.listdir(self.directoryname):
for line in open(os.path.join(self.directoryname, fname), encoding='latin'):
yield simple_preprocess(line)
Next, we need to provide the path of the directory as follows −
path = "ABC"
#provide the path as per your computer system where you saved the directory.
Next steps are similar as we did in previous examples. Next line of codes will make Gensim directory by using the directory having three text files −
dict_MUL = corpora.Dictionary(Read_files(path))
Dictionary(27 unique tokens: ['CNTK', 'Computational', 'Network', 'Toolkit', 'as']...)
Now we can also see the word to unique integer mapping as follows −
print(dict_MUL.token2id)
{
'CNTK': 0, 'Computational': 1, 'Network': 2, 'Toolkit': 3, 'as': 4,
'formerly': 5, 'known': 6, 'a': 7, 'commercial-grade': 8, 'easy-to-use': 9,
'free': 10, 'is': 11, 'open-source': 12, 'toolkit': 13, 'algorithms': 14,
'brain.': 15, 'deep': 16, 'enable': 17, 'human': 18, 'learn': 19,
'learning': 20, 'like': 21, 'that': 22, 'the': 23, 'to': 24, 'train': 25, 'us': 26
}
Gensim support their own native save() method to save dictionary to the disk and load() method to load back dictionary from the disk.
For example, we can save the dictionary with the help of following script −
Gensim.corpora.dictionary.save(filename)
#provide the path where you want to save the dictionary.
Similarly, we can load the saved dictionary by using the load() method. Following script can do this −
Gensim.corpora.dictionary.load(filename)
#provide the path where you have saved the dictionary.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2219,
"s": 2052,
"text": "In last chapter where we discussed about vector and model, you got an idea about the dictionary. Here, we are going to discuss Dictionary object in a bit more detail."
},
{
"code": null,
"e": 2320,
"s": 2219,
"text": "Before getting deep dive into the concept of dictionary, let’s understand some simple NLP concepts −"
},
{
"code": null,
"e": 2352,
"s": 2320,
"text": "Token − A token means a ‘word’."
},
{
"code": null,
"e": 2384,
"s": 2352,
"text": "Token − A token means a ‘word’."
},
{
"code": null,
"e": 2441,
"s": 2384,
"text": "Document − A document refers to a sentence or paragraph."
},
{
"code": null,
"e": 2498,
"s": 2441,
"text": "Document − A document refers to a sentence or paragraph."
},
{
"code": null,
"e": 2571,
"s": 2498,
"text": "Corpus − It refers to a collection of documents as a bag of words (BoW)."
},
{
"code": null,
"e": 2644,
"s": 2571,
"text": "Corpus − It refers to a collection of documents as a bag of words (BoW)."
},
{
"code": null,
"e": 2763,
"s": 2644,
"text": "For all the documents, a corpus always contains each word’s token’s id along with its frequency count in the document."
},
{
"code": null,
"e": 3154,
"s": 2763,
"text": "Let’s move to the concept of dictionary in Gensim. For working on text documents, Gensim also requires the words, i.e. tokens to be converted to their unique ids. For achieving this, it gives us the facility of Dictionary object, which maps each word to their unique integer id. It does this by converting input text to the list of words and then pass it to the corpora.Dictionary() object."
},
{
"code": null,
"e": 3412,
"s": 3154,
"text": "Now the question arises that what is actually the need of dictionary object and where it can be used? In Gensim, the dictionary object is used to create a bag of words (BoW) corpus which further used as the input to topic modelling and other models as well."
},
{
"code": null,
"e": 3486,
"s": 3412,
"text": "There are three different forms of input text, we can provide to Gensim −"
},
{
"code": null,
"e": 3568,
"s": 3486,
"text": "As the sentences stored in Python’s native list object (known as str in Python 3)"
},
{
"code": null,
"e": 3650,
"s": 3568,
"text": "As the sentences stored in Python’s native list object (known as str in Python 3)"
},
{
"code": null,
"e": 3702,
"s": 3650,
"text": "As one single text file (can be small or large one)"
},
{
"code": null,
"e": 3754,
"s": 3702,
"text": "As one single text file (can be small or large one)"
},
{
"code": null,
"e": 3774,
"s": 3754,
"text": "Multiple text files"
},
{
"code": null,
"e": 3794,
"s": 3774,
"text": "Multiple text files"
},
{
"code": null,
"e": 4115,
"s": 3794,
"text": "As discussed, in Gensim, the dictionary contains the mapping of all words, a.k.a tokens to their unique integer id. We can create a dictionary from list of sentences, from one or more than one text files (text file containing multiple lines of text). So, first let’s start by creating dictionary using list of sentences."
},
{
"code": null,
"e": 4375,
"s": 4115,
"text": "In the following example we will be creating dictionary from a list of sentences. When we have list of sentences or you can say multiple sentences, we must convert every sentence to a list of words and comprehensions is one of the very common ways to do this."
},
{
"code": null,
"e": 4438,
"s": 4375,
"text": "First, import the required and necessary packages as follows −"
},
{
"code": null,
"e": 4505,
"s": 4438,
"text": "import gensim\nfrom gensim import corpora\nfrom pprint import pprint"
},
{
"code": null,
"e": 4607,
"s": 4505,
"text": "Next, make the comprehension list from list of sentences/document to use it creating the dictionary −"
},
{
"code": null,
"e": 4826,
"s": 4607,
"text": "doc = [\n \"CNTK formerly known as Computational Network Toolkit\",\n \"is a free easy-to-use open-source commercial-grade toolkit\",\n \"that enable us to train deep learning algorithms to learn like the human brain.\"\n]"
},
{
"code": null,
"e": 4902,
"s": 4826,
"text": "Next, we need to split the sentences into words. It is called tokenisation."
},
{
"code": null,
"e": 4965,
"s": 4902,
"text": "text_tokens = [[text for text in doc.split()] for doc in doc]\n"
},
{
"code": null,
"e": 5036,
"s": 4965,
"text": "Now, with the help of following script, we can create the dictionary −"
},
{
"code": null,
"e": 5080,
"s": 5036,
"text": "dict_LoS = corpora.Dictionary(text_tokens)\n"
},
{
"code": null,
"e": 5158,
"s": 5080,
"text": "Now let’s get some more information like number of tokens in the dictionary −"
},
{
"code": null,
"e": 5174,
"s": 5158,
"text": "print(dict_LoS)"
},
{
"code": null,
"e": 5262,
"s": 5174,
"text": "Dictionary(27 unique tokens: ['CNTK', 'Computational', 'Network', 'Toolkit', 'as']...)\n"
},
{
"code": null,
"e": 5326,
"s": 5262,
"text": "We can also see the word to unique integer mapping as follows −"
},
{
"code": null,
"e": 5351,
"s": 5326,
"text": "print(dict_LoS.token2id)"
},
{
"code": null,
"e": 5739,
"s": 5351,
"text": "{\n 'CNTK': 0, 'Computational': 1, 'Network': 2, 'Toolkit': 3, 'as': 4, \n 'formerly': 5, 'known': 6, 'a': 7, 'commercial-grade': 8, 'easy-to-use': 9,\n 'free': 10, 'is': 11, 'open-source': 12, 'toolkit': 13, 'algorithms': 14,\n 'brain.': 15, 'deep': 16, 'enable': 17, 'human': 18, 'learn': 19, 'learning': 20,\n 'like': 21, 'that': 22, 'the': 23, 'to': 24, 'train': 25, 'us': 26\n}\n"
},
{
"code": null,
"e": 6155,
"s": 5739,
"text": "import gensim\nfrom gensim import corpora\nfrom pprint import pprint\ndoc = [\n \"CNTK formerly known as Computational Network Toolkit\",\n \"is a free easy-to-use open-source commercial-grade toolkit\",\n \"that enable us to train deep learning algorithms to learn like the human brain.\"\n]\ntext_tokens = [[text for text in doc.split()] for doc in doc]\ndict_LoS = corpora.Dictionary(text_tokens)\nprint(dict_LoS.token2id)"
},
{
"code": null,
"e": 6347,
"s": 6155,
"text": "In the following example we will be creating dictionary from a single text file. In the similar fashion, we can also create dictionary from more than one text files (i.e. directory of files)."
},
{
"code": null,
"e": 6619,
"s": 6347,
"text": "For this, we have saved the document, used in previous example, in the text file named doc.txt. Gensim will read the file line by line and process one line at a time by using simple_preprocess. In this way, it doesn’t need to load the complete file in memory all at once."
},
{
"code": null,
"e": 6682,
"s": 6619,
"text": "First, import the required and necessary packages as follows −"
},
{
"code": null,
"e": 6836,
"s": 6682,
"text": "import gensim\nfrom gensim import corpora\nfrom pprint import pprint\nfrom gensim.utils import simple_preprocess\nfrom smart_open import smart_open\nimport os"
},
{
"code": null,
"e": 6929,
"s": 6836,
"text": "Next line of codes will make gensim dictionary by using the single text file named doc.txt −"
},
{
"code": null,
"e": 7048,
"s": 6929,
"text": "dict_STF = corpora.Dictionary(\n simple_preprocess(line, deacc =True) for line in open(‘doc.txt’, encoding=’utf-8’)\n)"
},
{
"code": null,
"e": 7126,
"s": 7048,
"text": "Now let’s get some more information like number of tokens in the dictionary −"
},
{
"code": null,
"e": 7142,
"s": 7126,
"text": "print(dict_STF)"
},
{
"code": null,
"e": 7230,
"s": 7142,
"text": "Dictionary(27 unique tokens: ['CNTK', 'Computational', 'Network', 'Toolkit', 'as']...)\n"
},
{
"code": null,
"e": 7294,
"s": 7230,
"text": "We can also see the word to unique integer mapping as follows −"
},
{
"code": null,
"e": 7319,
"s": 7294,
"text": "print(dict_STF.token2id)"
},
{
"code": null,
"e": 7710,
"s": 7319,
"text": "{\n 'CNTK': 0, 'Computational': 1, 'Network': 2, 'Toolkit': 3, 'as': 4, \n 'formerly': 5, 'known': 6, 'a': 7, 'commercial-grade': 8, 'easy-to-use': 9, \n 'free': 10, 'is': 11, 'open-source': 12, 'toolkit': 13, 'algorithms': 14, \n 'brain.': 15, 'deep': 16, 'enable': 17, 'human': 18, 'learn': 19, \n 'learning': 20, 'like': 21, 'that': 22, 'the': 23, 'to': 24, 'train': 25, 'us': 26\n}\n"
},
{
"code": null,
"e": 8051,
"s": 7710,
"text": "import gensim\nfrom gensim import corpora\nfrom pprint import pprint\nfrom gensim.utils import simple_preprocess\nfrom smart_open import smart_open\nimport os\ndict_STF = corpora.Dictionary(\n simple_preprocess(line, deacc =True) for line in open(‘doc.txt’, encoding=’utf-8’)\n)\ndict_STF = corpora.Dictionary(text_tokens)\nprint(dict_STF.token2id)"
},
{
"code": null,
"e": 8410,
"s": 8051,
"text": "Now let’s create dictionary from multiple files, i.e. more than one text file saved in the same directory. For this example, we have created three different text files namely first.txt, second.txt and third.txtcontaining the three lines from text file (doc.txt), we used for previous example. All these three text files are saved under a directory named ABC."
},
{
"code": null,
"e": 8628,
"s": 8410,
"text": "In order to implement this, we need to define a class with a method that can iterate through all the three text files (First, Second, and Third.txt) in the directory (ABC) and yield the processed list of words tokens."
},
{
"code": null,
"e": 8719,
"s": 8628,
"text": "Let’s define the class named Read_files having a method named __iteration__() as follows −"
},
{
"code": null,
"e": 9016,
"s": 8719,
"text": "class Read_files(object):\n def __init__(self, directoryname):\n elf.directoryname = directoryname\n def __iter__(self):\n for fname in os.listdir(self.directoryname):\n for line in open(os.path.join(self.directoryname, fname), encoding='latin'):\n yield simple_preprocess(line)"
},
{
"code": null,
"e": 9080,
"s": 9016,
"text": "Next, we need to provide the path of the directory as follows −"
},
{
"code": null,
"e": 9094,
"s": 9080,
"text": "path = \"ABC\"\n"
},
{
"code": null,
"e": 9171,
"s": 9094,
"text": "#provide the path as per your computer system where you saved the directory."
},
{
"code": null,
"e": 9321,
"s": 9171,
"text": "Next steps are similar as we did in previous examples. Next line of codes will make Gensim directory by using the directory having three text files −"
},
{
"code": null,
"e": 9370,
"s": 9321,
"text": "dict_MUL = corpora.Dictionary(Read_files(path))\n"
},
{
"code": null,
"e": 9458,
"s": 9370,
"text": "Dictionary(27 unique tokens: ['CNTK', 'Computational', 'Network', 'Toolkit', 'as']...)\n"
},
{
"code": null,
"e": 9526,
"s": 9458,
"text": "Now we can also see the word to unique integer mapping as follows −"
},
{
"code": null,
"e": 9551,
"s": 9526,
"text": "print(dict_MUL.token2id)"
},
{
"code": null,
"e": 9942,
"s": 9551,
"text": "{\n 'CNTK': 0, 'Computational': 1, 'Network': 2, 'Toolkit': 3, 'as': 4, \n 'formerly': 5, 'known': 6, 'a': 7, 'commercial-grade': 8, 'easy-to-use': 9, \n 'free': 10, 'is': 11, 'open-source': 12, 'toolkit': 13, 'algorithms': 14, \n 'brain.': 15, 'deep': 16, 'enable': 17, 'human': 18, 'learn': 19, \n 'learning': 20, 'like': 21, 'that': 22, 'the': 23, 'to': 24, 'train': 25, 'us': 26\n}\n"
},
{
"code": null,
"e": 10076,
"s": 9942,
"text": "Gensim support their own native save() method to save dictionary to the disk and load() method to load back dictionary from the disk."
},
{
"code": null,
"e": 10152,
"s": 10076,
"text": "For example, we can save the dictionary with the help of following script −"
},
{
"code": null,
"e": 10193,
"s": 10152,
"text": "Gensim.corpora.dictionary.save(filename)"
},
{
"code": null,
"e": 10250,
"s": 10193,
"text": "#provide the path where you want to save the dictionary."
},
{
"code": null,
"e": 10353,
"s": 10250,
"text": "Similarly, we can load the saved dictionary by using the load() method. Following script can do this −"
},
{
"code": null,
"e": 10394,
"s": 10353,
"text": "Gensim.corpora.dictionary.load(filename)"
},
{
"code": null,
"e": 10449,
"s": 10394,
"text": "#provide the path where you have saved the dictionary."
},
{
"code": null,
"e": 10456,
"s": 10449,
"text": " Print"
},
{
"code": null,
"e": 10467,
"s": 10456,
"text": " Add Notes"
}
] |
Count Distinct Subsequences
|
05 Jul, 2022
Given a string, find the count of distinct subsequences of it.
Examples:
Input : str = "gfg"
Output : 7
The seven distinct subsequences are "", "g", "f",
"gf", "fg", "gg" and "gfg"
Input : str = "ggg"
Output : 4
The four distinct subsequences are "", "g", "gg"
and "ggg"
The problem of counting distinct subsequences is easy if all characters of input string are distinct. The count is equal to nC0 + nC1 + nC2 + ... nCn = 2n.How to count distinct subsequences when there can be repetition in input string? A Simple Solution to count distinct subsequences in a string with duplicates is to generate all subsequences. For every subsequence, store it in a hash table if it doesn’t exist already. The time complexity of this solution is exponential and it requires exponential extra space.
Method 1(Naive Approach): Using a set (without Dynamic Programming)
Approach: Generate all the possible subsequences of a given string. The subsequences of a string can be generated in the following manner:
Include a particular element(say ith) in the output array and recursively call the function for the rest of the input string. This results in the subsequences of a string having ith character. Exclude a particular element(say ith) and recursively call the function for the rest of the input string. This contains all the subsequences which don’t have the ith character.Once we have generated a subsequence, in the base case of the function we insert that generated subsequence in an unordered set. An unordered Set is a Data structure, that stores distinct elements in an unordered manner. This way we insert all the generated subsequences in the set and print the size of the set as our answer because at last, the set will contain only distinct subsequences.
Include a particular element(say ith) in the output array and recursively call the function for the rest of the input string. This results in the subsequences of a string having ith character.
Exclude a particular element(say ith) and recursively call the function for the rest of the input string. This contains all the subsequences which don’t have the ith character.Once we have generated a subsequence, in the base case of the function we insert that generated subsequence in an unordered set. An unordered Set is a Data structure, that stores distinct elements in an unordered manner. This way we insert all the generated subsequences in the set and print the size of the set as our answer because at last, the set will contain only distinct subsequences.
Implementation:
C++
Python3
Javascript
// C++ program to print distinct// subsequences of a given string#include <bits/stdc++.h>using namespace std; // Create an empty set to store the subsequencesunordered_set<string> sn; // Function for generating the subsequencesvoid subsequences(char s[], char op[], int i, int j){ // Base Case if (s[i] == '\0') { op[j] = '\0'; // Insert each generated // subsequence into the set sn.insert(op); return; } // Recursive Case else { // When a particular character is taken op[j] = s[i]; subsequences(s, op, i + 1, j + 1); // When a particular character isn't taken subsequences(s, op, i + 1, j); return; }} // Driver Codeint main(){ char str[] = "ggg"; int m = sizeof(str) / sizeof(char); int n = pow(2, m) + 1; // Output array for storing // the generating subsequences // in each call char op[m+1]; //extra one for having \0 at the end // Function Call subsequences(str, op, 0, 0); // Output will be the number // of elements in the set cout << sn.size(); sn.clear(); return 0; // This code is contributed by Kishan Mishra}
# Python3 program to print# distinct subsequences of# a given stringimport math # Create an empty set# to store the subsequencessn = []global mm = 0 # Function for generating# the subsequences def subsequences(s, op, i, j): # Base Case if(i == m): op[j] = None temp = "".join([i for i in op if i]) # Insert each generated # subsequence into the set sn.append(temp) return # Recursive Case else: # When a particular # character is taken op[j] = s[i] subsequences(s, op, i + 1, j + 1) # When a particular # character isn't taken subsequences(s, op, i + 1, j) return # Driver Codestr = "ggg"m = len(str)n = int(math.pow(2, m) + 1) # Output array for storing# the generating subsequences# in each callop = [None for i in range(n)] # Function Callsubsequences(str, op, 0, 0) # Output will be the number# of elements in the setprint(len(set(sn))) # This code is contributed by avanitrachhadiya2155
<script>// Javascript program to print distinct// subsequences of a given string // Create an empty set to store the subsequenceslet sn = new Set();let m = 0; // Function for generating the subsequencesfunction subsequences(s, op, i, j){ // Base Case if (i == m) { op[j] = '\0'; // Insert each generated // subsequence into the set sn.add(op.join("")); return; } // Recursive Case else { // When a particular character is taken op[j] = s[i]; subsequences(s, op, i + 1, j + 1); // When a particular character isn't taken subsequences(s, op, i + 1, j); return; }} // Driver Codelet str= "ggg";m = str.length;let n = Math.pow(2, m) + 1; // Output array for storing// the generating subsequences// in each calllet op=new Array(n); // Function Callsubsequences(str, op, 0, 0); // Output will be the number// of elements in the setdocument.write(sn.size); // This code is contributed by patel2127</script>
4
Time Complexity: O(2^n) Auxiliary Space: O(n) where n is the length of the string.
Method 2(Efficient Approach): Using Dynamic Programming
An Efficient Solution doesn’t require the generation of subsequences.
Let countSub(n) be count of subsequences of
first n characters in input string. We can
recursively write it as below.
countSub(n) = 2*Count(n-1) - Repetition
If current character, i.e., str[n-1] of str has
not appeared before, then
Repetition = 0
Else:
Repetition = Count(m)
Here m is index of previous occurrence of
current character. We basically remove all
counts ending with previous occurrence of
current character.
How does this work? If there are no repetitions, then count becomes double of count for n-1 because we get count(n-1) more subsequences by adding current character at the end of all subsequences possible with n-1 length. If there are repetitions, then we find a count of all distinct subsequences ending with the previous occurrence. This count can be obtained by recursively calling for an index of the previous occurrence. Since the above recurrence has overlapping subproblems, we can solve it using Dynamic Programming.
Below is the implementation of the above idea.
C++
Java
Python3
C#
Javascript
// C++ program to count number of distinct// subsequences of a given string.#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 256; // Returns count of distinct subsequences of str.int countSub(string str){ // Create an array to store index // of last vector<int> last(MAX_CHAR, -1); // Length of input string int n = str.length(); // dp[i] is going to store count of distinct // subsequences of length i. int dp[n + 1]; // Empty substring has only one subsequence dp[0] = 1; // Traverse through all lengths from 1 to n. for (int i = 1; i <= n; i++) { // Number of subsequences with substring // str[0..i-1] dp[i] = 2 * dp[i - 1]; // If current character has appeared // before, then remove all subsequences // ending with previous occurrence. if (last[str[i - 1]] != -1) dp[i] = dp[i] - dp[last[str[i - 1]]]; // Mark occurrence of current character last[str[i - 1]] = (i - 1); } return dp[n];} // Driver codeint main(){ cout << countSub("gfg"); return 0;}
// Java program to count number of distinct// subsequences of a given string.import java.util.ArrayList;import java.util.Arrays;public class Count_Subsequences { static final int MAX_CHAR = 256; // Returns count of distinct subsequences of str. static int countSub(String str) { // Create an array to store index // of last int[] last = new int[MAX_CHAR]; Arrays.fill(last, -1); // Length of input string int n = str.length(); // dp[i] is going to store count of distinct // subsequences of length i. int[] dp = new int[n + 1]; // Empty substring has only one subsequence dp[0] = 1; // Traverse through all lengths from 1 to n. for (int i = 1; i <= n; i++) { // Number of subsequences with substring // str[0..i-1] dp[i] = 2 * dp[i - 1]; // If current character has appeared // before, then remove all subsequences // ending with previous occurrence. if (last[(int)str.charAt(i - 1)] != -1) dp[i] = dp[i] - dp[last[(int)str.charAt(i - 1)]]; // Mark occurrence of current character last[(int)str.charAt(i - 1)] = (i - 1); } return dp[n]; } // Driver code public static void main(String args[]) { System.out.println(countSub("gfg")); }}// This code is contributed by Sumit Ghosh
# Python3 program to count number of# distinct subsequences of a given string MAX_CHAR = 256 def countSub(ss): # create an array to store index of last last = [-1 for i in range(MAX_CHAR + 1)] # length of input string n = len(ss) # dp[i] is going to store count of # discount subsequence of length of i dp = [-2 for i in range(n + 1)] # empty substring has only # one subsequence dp[0] = 1 # Traverse through all lengths # from 1 to n for i in range(1, n + 1): # number of subsequence with # substring str[0...i-1] dp[i] = 2 * dp[i - 1] # if current character has appeared # before, then remove all subsequences # ending with previous occurrence. if last[ord(ss[i - 1])] != -1: dp[i] = dp[i] - dp[last[ord(ss[i - 1])]] last[ord(ss[i - 1])] = i - 1 return dp[n] # Driver codeprint(countSub("gfg")) # This code is contributed# by mohit kumar 29
// C# program to count number of distinct// subsequences of a given string.using System; public class Count_Subsequences { static readonly int MAX_CHAR = 256; // Returns count of distinct subsequences of str. static int countSub(String str) { // Create an array to store index // of last int[] last = new int[MAX_CHAR]; for (int i = 0; i < MAX_CHAR; i++) last[i] = -1; // Length of input string int n = str.Length; // dp[i] is going to store count of // distinct subsequences of length i. int[] dp = new int[n + 1]; // Empty substring has only one subsequence dp[0] = 1; // Traverse through all lengths from 1 to n. for (int i = 1; i <= n; i++) { // Number of subsequences with substring // str[0..i-1] dp[i] = 2 * dp[i - 1]; // If current character has appeared // before, then remove all subsequences // ending with previous occurrence. if (last[(int)str[i - 1]] != -1) dp[i] = dp[i] - dp[last[(int)str[i - 1]]]; // Mark occurrence of current character last[(int)str[i - 1]] = (i - 1); } return dp[n]; } // Driver code public static void Main(String[] args) { Console.WriteLine(countSub("gfg")); }} // This code is contributed 29AjayKumar
<script> // Javascript program to count number of// distinct subsequences of a given string.let MAX_CHAR = 256; // Returns count of distinct subsequences// of str.function countSub(str){ // Create an array to store index // of last let last = new Array(MAX_CHAR); last.fill(-1); // Length of input string let n = str.length; // dp[i] is going to store count of distinct // subsequences of length i. let dp = new Array(n + 1); // Empty substring has only one subsequence dp[0] = 1; // Traverse through all lengths from 1 to n. for(let i = 1; i <= n; i++) { // Number of subsequences with substring // str[0..i-1] dp[i] = 2 * dp[i - 1]; // If current character has appeared // before, then remove all subsequences // ending with previous occurrence. if (last[str[i - 1].charCodeAt()] != -1) dp[i] = dp[i] - dp[last[str[i - 1].charCodeAt()]]; // Mark occurrence of current character last[str[i - 1].charCodeAt()] = (i - 1); } return dp[n];} // Driver codedocument.write(countSub("gfg")); // This code is contributed by mukesh07 </script>
7
Time Complexity: O(n) Auxiliary Space: O(n)
Method 3: Without extra space
Let’s say we have 2 variables : `allCount` which adds up total distinct subsequence count and `levelCount` which stores the count of subsequences ending at index i. To find repetitions we will store the most recent levelCount for each character. Finally we will see how we can determine `allCount` using the `levelCount` variable.
Here is a representation of above statement:
Say s = “abab”
Let’s initialize all string characters in a map with -1 . The value in this map represents how many distinct subsequences ended at the last occurrence of this character.
map = {a:-1,b:-1}
Also initially we have
levelCount=0;
allCount = 0;
Now iterating through each character
1st iteration ‘a’ Distinct Subsequences ending with ‘a’ are : “a” . So we make levelCount = 1, also allCount is 1 now.map will be updated like map[`current_char`]=levelCount.levelCount = 1; allCount = 1; map = {a:1,b:-1}
Distinct Subsequences ending with ‘a’ are : “a” . So we make levelCount = 1, also allCount is 1 now.map will be updated like map[`current_char`]=levelCount.
levelCount = 1; allCount = 1; map = {a:1,b:-1}
2nd iteration ‘b’Distinct Subsequences ending with ‘b’ are “ab”,”b”. So the levelCount = 2. Also total subsequences we found till now are 3. allCount = 3.Here we can notice that levelCount can be determined from last value of allCount variable by adding 1 to itlevelCount = allCount+1 ( levelCount= 1+1=2)In case, if this is a distinct character then current allCount can also be determined easily asallCount = allCount + levelCount; ( allCount= 1+ 2 = 3)We also update the map with the current character’s levelCount. map{a:1,b:2}
Distinct Subsequences ending with ‘b’ are “ab”,”b”. So the levelCount = 2.
Also total subsequences we found till now are 3. allCount = 3.
Here we can notice that levelCount can be determined from last value of allCount variable by adding 1 to it
levelCount = allCount+1 ( levelCount= 1+1=2)
In case, if this is a distinct character then current allCount can also be determined easily as
allCount = allCount + levelCount; ( allCount= 1+ 2 = 3)
We also update the map with the current character’s levelCount. map{a:1,b:2}
3rd iteration ‘a’ Now we have a repetition. Distinct Subsequences ending with ‘a’ are now “aa”,”ba”,”aba”,”a”. So our levelCount is now 4: which is determined as previously stated allCount+1 = 3+1 = 4.if this was a distinct character allcount would have been 7 (allCount = allCount+levelCount = 3+4) but we will have remove the repetition, which is map.get(`a`) which is 1 , so now allCount is 7-1 = 6Here note that we have essentially remove the results of our 1st iteration which was duplicate subsequence “a”. This simply means that we can form the same subsequences ending with our new founded `a` that old `a` would have formed, so we subtract the older subsequences.map is now updated with new levelCount of a to {a:4,b:2}In case of repetition out allCount calculation changes asallCount = allCount + levelCount – map.get(currentCharacter);allCount = 3+4-1 = 6
Now we have a repetition.
Distinct Subsequences ending with ‘a’ are now “aa”,”ba”,”aba”,”a”. So our levelCount is now 4: which is determined as previously stated allCount+1 = 3+1 = 4.
if this was a distinct character allcount would have been 7 (allCount = allCount+levelCount = 3+4) but we will have remove the repetition, which is map.get(`a`) which is 1 , so now allCount is 7-1 = 6
Here note that we have essentially remove the results of our 1st iteration which was duplicate subsequence “a”. This simply means that we can form the same subsequences ending with our new founded `a` that old `a` would have formed, so we subtract the older subsequences.
map is now updated with new levelCount of a to {a:4,b:2}
In case of repetition out allCount calculation changes as
allCount = allCount + levelCount – map.get(currentCharacter);
allCount = 3+4-1 = 6
4th iteration ‘b’Again a repetition. Subsequences ending with ‘b’ are now “abb”,”bb”,”aab”,”bab”,”abab”,”ab” ,”b” which count is same as levelCount = allCount+1 = 6+1 = 7 .allCount will be = allCount+levelCount – map.get(‘b’) = 6+7-2 = 11Total number of distinct subsequences is allCount.If empty String is also included then our answer is allCount+1.Below is the implementation of the above approach.
Again a repetition.
Subsequences ending with ‘b’ are now “abb”,”bb”,”aab”,”bab”,”abab”,”ab” ,”b” which count is same as levelCount = allCount+1 = 6+1 = 7 .
allCount will be = allCount+levelCount – map.get(‘b’) = 6+7-2 = 11
Total number of distinct subsequences is allCount.
If empty String is also included then our answer is allCount+1.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Returns count of distinct// subsequences of str.int countSub(string s){ map<char, int> Map; // Iterate from 0 to s.length() for(int i = 0; i < s.length(); i++) { Map[s[i]] = -1; } int allCount = 0; int levelCount = 0; // Iterate from 0 to s.length() for(int i = 0; i < s.length(); i++) { char c = s[i]; // Check if i equal to 0 if (i == 0) { allCount = 1; Map = 1; levelCount = 1; continue; } // Replace levelCount with // allCount + 1 levelCount = allCount + 1; // If map is less than 0 if (Map < 0) { allCount = allCount + levelCount; } else { allCount = allCount + levelCount - Map; } Map = levelCount; } // Return answer return allCount;} // Driver codeint main(){ string list[] = { "abab", "gfg" }; for(string s : list) { int cnt = countSub(s); int withEmptyString = cnt + 1; cout << "With empty string count for " << s << " is " << withEmptyString << endl; cout << "Without empty string count for " << s << " is " << cnt << endl; } return 0;} // This code is contributed by divyeshrabadiya07
// Java Program for above approachimport java.io.*;import java.util.*;class SubsequenceCount{ // Returns count of distinct // subsequences of str. public static int countSub(String s) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); // Iterate from 0 to s.length() for(int i = 0; i < s.length(); i++) { map.put(s.charAt(i), -1); } int allCount = 0; int levelCount = 0; // Iterate from 0 to s.length() for(int i=0;i<s.length();i++) { char c = s.charAt(i); // Check if i equal to 0 if(i==0) { allCount = 1; map.put(c,1); levelCount = 1; continue; } // Replace levelCount with // allCount + 1 levelCount = allCount + 1; // If map is less than 0 if(map.get(c)<0) { allCount = allCount + levelCount; } else { allCount = allCount + levelCount - map.get(c); } map.put(c,levelCount); } // Return answer return allCount; } // Driver Code public static void main(String[] args) { List<String> list = Arrays.asList("abab","gfg"); for(String s : list) { int cnt = countSub(s); int withEmptyString = cnt+1; System.out.println("With empty string count for " + s +" is " + withEmptyString); System.out.println("Without empty string count for " + s + " is " + cnt); } }}//Code is contributed by abhisht7
# Python3 program for above approach # Returns count of distinct # subsequences of str.def countSub(s): Map = {} # Iterate from 0 to length of s for i in range(len(s)): Map[s[i]] = -1 allCount = 0 levelCount = 0 # Iterate from 0 to length of s for i in range(len(s)): c = s[i] # Check if i equal to 0 if (i == 0): allCount = 1 Map = 1 levelCount = 1 continue # Replace levelCount with # allCount + 1 levelCount = allCount + 1 # If map is less than 0 if (Map < 0): allCount = allCount + levelCount else: allCount = allCount + levelCount - Map Map = levelCount # Return answer return allCount # Driver CodeList = [ "abab", "gfg" ] for s in List: cnt = countSub(s) withEmptyString = cnt + 1 print("With empty string count for", s, "is", withEmptyString) print("Without empty string count for", s, "is", cnt) # This code is contributed by rag2127
// C# Program for above approachusing System;using System.Collections.Generic; class GFG{ // Returns count of distinct// subsequences of str.public static int countSub(String s){ Dictionary<char, int> map = new Dictionary<char, int>(); // Iterate from 0 to s.length() for(int i = 0; i < s.Length; i++) { if (!map.ContainsKey(s[i])) { map.Add(s[i], -1); } } int allCount = 0; int levelCount = 0; // Iterate from 0 to s.length() for(int i = 0; i < s.Length; i++) { char c = s[i]; // Check if i equal to 0 if (i == 0) { allCount = 1; if (!map.ContainsKey(c)) { map.Add(c, 1); } else { map = 1; } levelCount = 1; continue; } // Replace levelCount with // allCount + 1 levelCount = allCount + 1; // If map is less than 0 if (map.ContainsKey(c)) { if (map < 0) { allCount = (allCount + levelCount); } else { allCount = (allCount + levelCount - map); } } if (!map.ContainsKey(c)) { map.Add(c, levelCount); } else { map = levelCount; } } // Return answer return allCount; } // Driver Codestatic void Main(){ List<string> list = new List<string>(); list.Add("abab"); list.Add("gfg"); foreach(string s in list) { int cnt = countSub(s); int withEmptyString = cnt + 1; Console.WriteLine("With empty string count for " + s + " is " + withEmptyString); Console.WriteLine("Without empty string count for " + s + " is " + cnt); }}} // This code is contributed by divyesh072019
<script>// Javascript Program for above approach // Returns count of distinct // subsequences of str. function countSub(s) { let map = new Map(); // Iterate from 0 to s.length() for(let i = 0; i < s.length; i++) { map.set(s[i], -1); } let allCount = 0; let levelCount = 0; // Iterate from 0 to s.length() for(let i=0;i<s.length;i++) { let c = s[i]; // Check if i equal to 0 if(i==0) { allCount = 1; map.set(c,1); levelCount = 1; continue; } // Replace levelCount with // allCount + 1 levelCount = allCount + 1; // If map is less than 0 if(map.get(c)<0) { allCount = allCount + levelCount; } else { allCount = allCount + levelCount - map.get(c); } map.set(c,levelCount); } // Return answer return allCount; } // Driver Code let list=["abab","gfg"]; for(let i=0;i<list.length;i++) { let cnt = countSub(list[i]); let withEmptyString = cnt+1; document.write("With empty string count for " + list[i] +" is " + withEmptyString+"<br>"); document.write("Without empty string count for " + list[i] + " is " + cnt+"<br>"); } // This code is contributed by unknown2108</script>
With empty string count for abab is 12
Without empty string count for abab is 11
With empty string count for gfg is 7
Without empty string count for gfg is 6
Time Complexity: O(n)Space Complexity: O(1)
s_pandey06
mohit kumar 29
29AjayKumar
mishrakishan1
abhishtmishra
avanitrachhadiya2155
divyeshrabadiya07
divyesh072019
rag2127
mukesh07
unknown2108
patel2127
yash_760
as5853535
sumitgumber28
simranarora5sos
arorakashish0911
hardikkoriintern
subsequence
Dynamic Programming
Strings
Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in an undirected graph
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Bellman–Ford Algorithm | DP-23
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 116,
"s": 52,
"text": "Given a string, find the count of distinct subsequences of it. "
},
{
"code": null,
"e": 127,
"s": 116,
"text": "Examples: "
},
{
"code": null,
"e": 329,
"s": 127,
"text": "Input : str = \"gfg\"\nOutput : 7\nThe seven distinct subsequences are \"\", \"g\", \"f\",\n\"gf\", \"fg\", \"gg\" and \"gfg\" \n\nInput : str = \"ggg\"\nOutput : 4\nThe four distinct subsequences are \"\", \"g\", \"gg\"\nand \"ggg\""
},
{
"code": null,
"e": 845,
"s": 329,
"text": "The problem of counting distinct subsequences is easy if all characters of input string are distinct. The count is equal to nC0 + nC1 + nC2 + ... nCn = 2n.How to count distinct subsequences when there can be repetition in input string? A Simple Solution to count distinct subsequences in a string with duplicates is to generate all subsequences. For every subsequence, store it in a hash table if it doesn’t exist already. The time complexity of this solution is exponential and it requires exponential extra space."
},
{
"code": null,
"e": 913,
"s": 845,
"text": "Method 1(Naive Approach): Using a set (without Dynamic Programming)"
},
{
"code": null,
"e": 1053,
"s": 913,
"text": "Approach: Generate all the possible subsequences of a given string. The subsequences of a string can be generated in the following manner: "
},
{
"code": null,
"e": 1815,
"s": 1053,
"text": "Include a particular element(say ith) in the output array and recursively call the function for the rest of the input string. This results in the subsequences of a string having ith character. Exclude a particular element(say ith) and recursively call the function for the rest of the input string. This contains all the subsequences which don’t have the ith character.Once we have generated a subsequence, in the base case of the function we insert that generated subsequence in an unordered set. An unordered Set is a Data structure, that stores distinct elements in an unordered manner. This way we insert all the generated subsequences in the set and print the size of the set as our answer because at last, the set will contain only distinct subsequences. "
},
{
"code": null,
"e": 2009,
"s": 1815,
"text": "Include a particular element(say ith) in the output array and recursively call the function for the rest of the input string. This results in the subsequences of a string having ith character. "
},
{
"code": null,
"e": 2578,
"s": 2009,
"text": "Exclude a particular element(say ith) and recursively call the function for the rest of the input string. This contains all the subsequences which don’t have the ith character.Once we have generated a subsequence, in the base case of the function we insert that generated subsequence in an unordered set. An unordered Set is a Data structure, that stores distinct elements in an unordered manner. This way we insert all the generated subsequences in the set and print the size of the set as our answer because at last, the set will contain only distinct subsequences. "
},
{
"code": null,
"e": 2594,
"s": 2578,
"text": "Implementation:"
},
{
"code": null,
"e": 2598,
"s": 2594,
"text": "C++"
},
{
"code": null,
"e": 2606,
"s": 2598,
"text": "Python3"
},
{
"code": null,
"e": 2617,
"s": 2606,
"text": "Javascript"
},
{
"code": "// C++ program to print distinct// subsequences of a given string#include <bits/stdc++.h>using namespace std; // Create an empty set to store the subsequencesunordered_set<string> sn; // Function for generating the subsequencesvoid subsequences(char s[], char op[], int i, int j){ // Base Case if (s[i] == '\\0') { op[j] = '\\0'; // Insert each generated // subsequence into the set sn.insert(op); return; } // Recursive Case else { // When a particular character is taken op[j] = s[i]; subsequences(s, op, i + 1, j + 1); // When a particular character isn't taken subsequences(s, op, i + 1, j); return; }} // Driver Codeint main(){ char str[] = \"ggg\"; int m = sizeof(str) / sizeof(char); int n = pow(2, m) + 1; // Output array for storing // the generating subsequences // in each call char op[m+1]; //extra one for having \\0 at the end // Function Call subsequences(str, op, 0, 0); // Output will be the number // of elements in the set cout << sn.size(); sn.clear(); return 0; // This code is contributed by Kishan Mishra}",
"e": 3789,
"s": 2617,
"text": null
},
{
"code": "# Python3 program to print# distinct subsequences of# a given stringimport math # Create an empty set# to store the subsequencessn = []global mm = 0 # Function for generating# the subsequences def subsequences(s, op, i, j): # Base Case if(i == m): op[j] = None temp = \"\".join([i for i in op if i]) # Insert each generated # subsequence into the set sn.append(temp) return # Recursive Case else: # When a particular # character is taken op[j] = s[i] subsequences(s, op, i + 1, j + 1) # When a particular # character isn't taken subsequences(s, op, i + 1, j) return # Driver Codestr = \"ggg\"m = len(str)n = int(math.pow(2, m) + 1) # Output array for storing# the generating subsequences# in each callop = [None for i in range(n)] # Function Callsubsequences(str, op, 0, 0) # Output will be the number# of elements in the setprint(len(set(sn))) # This code is contributed by avanitrachhadiya2155",
"e": 4839,
"s": 3789,
"text": null
},
{
"code": "<script>// Javascript program to print distinct// subsequences of a given string // Create an empty set to store the subsequenceslet sn = new Set();let m = 0; // Function for generating the subsequencesfunction subsequences(s, op, i, j){ // Base Case if (i == m) { op[j] = '\\0'; // Insert each generated // subsequence into the set sn.add(op.join(\"\")); return; } // Recursive Case else { // When a particular character is taken op[j] = s[i]; subsequences(s, op, i + 1, j + 1); // When a particular character isn't taken subsequences(s, op, i + 1, j); return; }} // Driver Codelet str= \"ggg\";m = str.length;let n = Math.pow(2, m) + 1; // Output array for storing// the generating subsequences// in each calllet op=new Array(n); // Function Callsubsequences(str, op, 0, 0); // Output will be the number// of elements in the setdocument.write(sn.size); // This code is contributed by patel2127</script>",
"e": 5849,
"s": 4839,
"text": null
},
{
"code": null,
"e": 5851,
"s": 5849,
"text": "4"
},
{
"code": null,
"e": 5934,
"s": 5851,
"text": "Time Complexity: O(2^n) Auxiliary Space: O(n) where n is the length of the string."
},
{
"code": null,
"e": 5990,
"s": 5934,
"text": "Method 2(Efficient Approach): Using Dynamic Programming"
},
{
"code": null,
"e": 6063,
"s": 5990,
"text": "An Efficient Solution doesn’t require the generation of subsequences. "
},
{
"code": null,
"e": 6510,
"s": 6063,
"text": "Let countSub(n) be count of subsequences of \nfirst n characters in input string. We can\nrecursively write it as below. \n\ncountSub(n) = 2*Count(n-1) - Repetition\n\nIf current character, i.e., str[n-1] of str has\nnot appeared before, then \n Repetition = 0\n\nElse:\n Repetition = Count(m)\n Here m is index of previous occurrence of\n current character. We basically remove all\n counts ending with previous occurrence of\n current character."
},
{
"code": null,
"e": 7035,
"s": 6510,
"text": "How does this work? If there are no repetitions, then count becomes double of count for n-1 because we get count(n-1) more subsequences by adding current character at the end of all subsequences possible with n-1 length. If there are repetitions, then we find a count of all distinct subsequences ending with the previous occurrence. This count can be obtained by recursively calling for an index of the previous occurrence. Since the above recurrence has overlapping subproblems, we can solve it using Dynamic Programming. "
},
{
"code": null,
"e": 7084,
"s": 7035,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 7088,
"s": 7084,
"text": "C++"
},
{
"code": null,
"e": 7093,
"s": 7088,
"text": "Java"
},
{
"code": null,
"e": 7101,
"s": 7093,
"text": "Python3"
},
{
"code": null,
"e": 7104,
"s": 7101,
"text": "C#"
},
{
"code": null,
"e": 7115,
"s": 7104,
"text": "Javascript"
},
{
"code": "// C++ program to count number of distinct// subsequences of a given string.#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 256; // Returns count of distinct subsequences of str.int countSub(string str){ // Create an array to store index // of last vector<int> last(MAX_CHAR, -1); // Length of input string int n = str.length(); // dp[i] is going to store count of distinct // subsequences of length i. int dp[n + 1]; // Empty substring has only one subsequence dp[0] = 1; // Traverse through all lengths from 1 to n. for (int i = 1; i <= n; i++) { // Number of subsequences with substring // str[0..i-1] dp[i] = 2 * dp[i - 1]; // If current character has appeared // before, then remove all subsequences // ending with previous occurrence. if (last[str[i - 1]] != -1) dp[i] = dp[i] - dp[last[str[i - 1]]]; // Mark occurrence of current character last[str[i - 1]] = (i - 1); } return dp[n];} // Driver codeint main(){ cout << countSub(\"gfg\"); return 0;}",
"e": 8215,
"s": 7115,
"text": null
},
{
"code": "// Java program to count number of distinct// subsequences of a given string.import java.util.ArrayList;import java.util.Arrays;public class Count_Subsequences { static final int MAX_CHAR = 256; // Returns count of distinct subsequences of str. static int countSub(String str) { // Create an array to store index // of last int[] last = new int[MAX_CHAR]; Arrays.fill(last, -1); // Length of input string int n = str.length(); // dp[i] is going to store count of distinct // subsequences of length i. int[] dp = new int[n + 1]; // Empty substring has only one subsequence dp[0] = 1; // Traverse through all lengths from 1 to n. for (int i = 1; i <= n; i++) { // Number of subsequences with substring // str[0..i-1] dp[i] = 2 * dp[i - 1]; // If current character has appeared // before, then remove all subsequences // ending with previous occurrence. if (last[(int)str.charAt(i - 1)] != -1) dp[i] = dp[i] - dp[last[(int)str.charAt(i - 1)]]; // Mark occurrence of current character last[(int)str.charAt(i - 1)] = (i - 1); } return dp[n]; } // Driver code public static void main(String args[]) { System.out.println(countSub(\"gfg\")); }}// This code is contributed by Sumit Ghosh",
"e": 9655,
"s": 8215,
"text": null
},
{
"code": "# Python3 program to count number of# distinct subsequences of a given string MAX_CHAR = 256 def countSub(ss): # create an array to store index of last last = [-1 for i in range(MAX_CHAR + 1)] # length of input string n = len(ss) # dp[i] is going to store count of # discount subsequence of length of i dp = [-2 for i in range(n + 1)] # empty substring has only # one subsequence dp[0] = 1 # Traverse through all lengths # from 1 to n for i in range(1, n + 1): # number of subsequence with # substring str[0...i-1] dp[i] = 2 * dp[i - 1] # if current character has appeared # before, then remove all subsequences # ending with previous occurrence. if last[ord(ss[i - 1])] != -1: dp[i] = dp[i] - dp[last[ord(ss[i - 1])]] last[ord(ss[i - 1])] = i - 1 return dp[n] # Driver codeprint(countSub(\"gfg\")) # This code is contributed# by mohit kumar 29",
"e": 10648,
"s": 9655,
"text": null
},
{
"code": "// C# program to count number of distinct// subsequences of a given string.using System; public class Count_Subsequences { static readonly int MAX_CHAR = 256; // Returns count of distinct subsequences of str. static int countSub(String str) { // Create an array to store index // of last int[] last = new int[MAX_CHAR]; for (int i = 0; i < MAX_CHAR; i++) last[i] = -1; // Length of input string int n = str.Length; // dp[i] is going to store count of // distinct subsequences of length i. int[] dp = new int[n + 1]; // Empty substring has only one subsequence dp[0] = 1; // Traverse through all lengths from 1 to n. for (int i = 1; i <= n; i++) { // Number of subsequences with substring // str[0..i-1] dp[i] = 2 * dp[i - 1]; // If current character has appeared // before, then remove all subsequences // ending with previous occurrence. if (last[(int)str[i - 1]] != -1) dp[i] = dp[i] - dp[last[(int)str[i - 1]]]; // Mark occurrence of current character last[(int)str[i - 1]] = (i - 1); } return dp[n]; } // Driver code public static void Main(String[] args) { Console.WriteLine(countSub(\"gfg\")); }} // This code is contributed 29AjayKumar",
"e": 12063,
"s": 10648,
"text": null
},
{
"code": "<script> // Javascript program to count number of// distinct subsequences of a given string.let MAX_CHAR = 256; // Returns count of distinct subsequences// of str.function countSub(str){ // Create an array to store index // of last let last = new Array(MAX_CHAR); last.fill(-1); // Length of input string let n = str.length; // dp[i] is going to store count of distinct // subsequences of length i. let dp = new Array(n + 1); // Empty substring has only one subsequence dp[0] = 1; // Traverse through all lengths from 1 to n. for(let i = 1; i <= n; i++) { // Number of subsequences with substring // str[0..i-1] dp[i] = 2 * dp[i - 1]; // If current character has appeared // before, then remove all subsequences // ending with previous occurrence. if (last[str[i - 1].charCodeAt()] != -1) dp[i] = dp[i] - dp[last[str[i - 1].charCodeAt()]]; // Mark occurrence of current character last[str[i - 1].charCodeAt()] = (i - 1); } return dp[n];} // Driver codedocument.write(countSub(\"gfg\")); // This code is contributed by mukesh07 </script>",
"e": 13240,
"s": 12063,
"text": null
},
{
"code": null,
"e": 13242,
"s": 13240,
"text": "7"
},
{
"code": null,
"e": 13287,
"s": 13242,
"text": "Time Complexity: O(n) Auxiliary Space: O(n) "
},
{
"code": null,
"e": 13317,
"s": 13287,
"text": "Method 3: Without extra space"
},
{
"code": null,
"e": 13648,
"s": 13317,
"text": "Let’s say we have 2 variables : `allCount` which adds up total distinct subsequence count and `levelCount` which stores the count of subsequences ending at index i. To find repetitions we will store the most recent levelCount for each character. Finally we will see how we can determine `allCount` using the `levelCount` variable."
},
{
"code": null,
"e": 13694,
"s": 13648,
"text": "Here is a representation of above statement: "
},
{
"code": null,
"e": 13709,
"s": 13694,
"text": "Say s = “abab”"
},
{
"code": null,
"e": 13880,
"s": 13709,
"text": "Let’s initialize all string characters in a map with -1 . The value in this map represents how many distinct subsequences ended at the last occurrence of this character. "
},
{
"code": null,
"e": 13898,
"s": 13880,
"text": "map = {a:-1,b:-1}"
},
{
"code": null,
"e": 13921,
"s": 13898,
"text": "Also initially we have"
},
{
"code": null,
"e": 13935,
"s": 13921,
"text": "levelCount=0;"
},
{
"code": null,
"e": 13949,
"s": 13935,
"text": "allCount = 0;"
},
{
"code": null,
"e": 13986,
"s": 13949,
"text": "Now iterating through each character"
},
{
"code": null,
"e": 14210,
"s": 13986,
"text": "1st iteration ‘a’ Distinct Subsequences ending with ‘a’ are : “a” . So we make levelCount = 1, also allCount is 1 now.map will be updated like map[`current_char`]=levelCount.levelCount = 1; allCount = 1; map = {a:1,b:-1} "
},
{
"code": null,
"e": 14368,
"s": 14210,
"text": "Distinct Subsequences ending with ‘a’ are : “a” . So we make levelCount = 1, also allCount is 1 now.map will be updated like map[`current_char`]=levelCount."
},
{
"code": null,
"e": 14417,
"s": 14368,
"text": "levelCount = 1; allCount = 1; map = {a:1,b:-1} "
},
{
"code": null,
"e": 14949,
"s": 14417,
"text": "2nd iteration ‘b’Distinct Subsequences ending with ‘b’ are “ab”,”b”. So the levelCount = 2. Also total subsequences we found till now are 3. allCount = 3.Here we can notice that levelCount can be determined from last value of allCount variable by adding 1 to itlevelCount = allCount+1 ( levelCount= 1+1=2)In case, if this is a distinct character then current allCount can also be determined easily asallCount = allCount + levelCount; ( allCount= 1+ 2 = 3)We also update the map with the current character’s levelCount. map{a:1,b:2}"
},
{
"code": null,
"e": 15025,
"s": 14949,
"text": "Distinct Subsequences ending with ‘b’ are “ab”,”b”. So the levelCount = 2. "
},
{
"code": null,
"e": 15088,
"s": 15025,
"text": "Also total subsequences we found till now are 3. allCount = 3."
},
{
"code": null,
"e": 15196,
"s": 15088,
"text": "Here we can notice that levelCount can be determined from last value of allCount variable by adding 1 to it"
},
{
"code": null,
"e": 15241,
"s": 15196,
"text": "levelCount = allCount+1 ( levelCount= 1+1=2)"
},
{
"code": null,
"e": 15337,
"s": 15241,
"text": "In case, if this is a distinct character then current allCount can also be determined easily as"
},
{
"code": null,
"e": 15393,
"s": 15337,
"text": "allCount = allCount + levelCount; ( allCount= 1+ 2 = 3)"
},
{
"code": null,
"e": 15470,
"s": 15393,
"text": "We also update the map with the current character’s levelCount. map{a:1,b:2}"
},
{
"code": null,
"e": 16341,
"s": 15470,
"text": "3rd iteration ‘a’ Now we have a repetition. Distinct Subsequences ending with ‘a’ are now “aa”,”ba”,”aba”,”a”. So our levelCount is now 4: which is determined as previously stated allCount+1 = 3+1 = 4.if this was a distinct character allcount would have been 7 (allCount = allCount+levelCount = 3+4) but we will have remove the repetition, which is map.get(`a`) which is 1 , so now allCount is 7-1 = 6Here note that we have essentially remove the results of our 1st iteration which was duplicate subsequence “a”. This simply means that we can form the same subsequences ending with our new founded `a` that old `a` would have formed, so we subtract the older subsequences.map is now updated with new levelCount of a to {a:4,b:2}In case of repetition out allCount calculation changes asallCount = allCount + levelCount – map.get(currentCharacter);allCount = 3+4-1 = 6"
},
{
"code": null,
"e": 16368,
"s": 16341,
"text": "Now we have a repetition. "
},
{
"code": null,
"e": 16527,
"s": 16368,
"text": "Distinct Subsequences ending with ‘a’ are now “aa”,”ba”,”aba”,”a”. So our levelCount is now 4: which is determined as previously stated allCount+1 = 3+1 = 4."
},
{
"code": null,
"e": 16730,
"s": 16527,
"text": "if this was a distinct character allcount would have been 7 (allCount = allCount+levelCount = 3+4) but we will have remove the repetition, which is map.get(`a`) which is 1 , so now allCount is 7-1 = 6"
},
{
"code": null,
"e": 17002,
"s": 16730,
"text": "Here note that we have essentially remove the results of our 1st iteration which was duplicate subsequence “a”. This simply means that we can form the same subsequences ending with our new founded `a` that old `a` would have formed, so we subtract the older subsequences."
},
{
"code": null,
"e": 17059,
"s": 17002,
"text": "map is now updated with new levelCount of a to {a:4,b:2}"
},
{
"code": null,
"e": 17117,
"s": 17059,
"text": "In case of repetition out allCount calculation changes as"
},
{
"code": null,
"e": 17179,
"s": 17117,
"text": "allCount = allCount + levelCount – map.get(currentCharacter);"
},
{
"code": null,
"e": 17200,
"s": 17179,
"text": "allCount = 3+4-1 = 6"
},
{
"code": null,
"e": 17604,
"s": 17200,
"text": "4th iteration ‘b’Again a repetition. Subsequences ending with ‘b’ are now “abb”,”bb”,”aab”,”bab”,”abab”,”ab” ,”b” which count is same as levelCount = allCount+1 = 6+1 = 7 .allCount will be = allCount+levelCount – map.get(‘b’) = 6+7-2 = 11Total number of distinct subsequences is allCount.If empty String is also included then our answer is allCount+1.Below is the implementation of the above approach. "
},
{
"code": null,
"e": 17625,
"s": 17604,
"text": "Again a repetition. "
},
{
"code": null,
"e": 17761,
"s": 17625,
"text": "Subsequences ending with ‘b’ are now “abb”,”bb”,”aab”,”bab”,”abab”,”ab” ,”b” which count is same as levelCount = allCount+1 = 6+1 = 7 ."
},
{
"code": null,
"e": 17829,
"s": 17761,
"text": "allCount will be = allCount+levelCount – map.get(‘b’) = 6+7-2 = 11"
},
{
"code": null,
"e": 17880,
"s": 17829,
"text": "Total number of distinct subsequences is allCount."
},
{
"code": null,
"e": 17944,
"s": 17880,
"text": "If empty String is also included then our answer is allCount+1."
},
{
"code": null,
"e": 17996,
"s": 17944,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 18000,
"s": 17996,
"text": "C++"
},
{
"code": null,
"e": 18005,
"s": 18000,
"text": "Java"
},
{
"code": null,
"e": 18013,
"s": 18005,
"text": "Python3"
},
{
"code": null,
"e": 18016,
"s": 18013,
"text": "C#"
},
{
"code": null,
"e": 18027,
"s": 18016,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Returns count of distinct// subsequences of str.int countSub(string s){ map<char, int> Map; // Iterate from 0 to s.length() for(int i = 0; i < s.length(); i++) { Map[s[i]] = -1; } int allCount = 0; int levelCount = 0; // Iterate from 0 to s.length() for(int i = 0; i < s.length(); i++) { char c = s[i]; // Check if i equal to 0 if (i == 0) { allCount = 1; Map = 1; levelCount = 1; continue; } // Replace levelCount with // allCount + 1 levelCount = allCount + 1; // If map is less than 0 if (Map < 0) { allCount = allCount + levelCount; } else { allCount = allCount + levelCount - Map; } Map = levelCount; } // Return answer return allCount;} // Driver codeint main(){ string list[] = { \"abab\", \"gfg\" }; for(string s : list) { int cnt = countSub(s); int withEmptyString = cnt + 1; cout << \"With empty string count for \" << s << \" is \" << withEmptyString << endl; cout << \"Without empty string count for \" << s << \" is \" << cnt << endl; } return 0;} // This code is contributed by divyeshrabadiya07",
"e": 19489,
"s": 18027,
"text": null
},
{
"code": "// Java Program for above approachimport java.io.*;import java.util.*;class SubsequenceCount{ // Returns count of distinct // subsequences of str. public static int countSub(String s) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); // Iterate from 0 to s.length() for(int i = 0; i < s.length(); i++) { map.put(s.charAt(i), -1); } int allCount = 0; int levelCount = 0; // Iterate from 0 to s.length() for(int i=0;i<s.length();i++) { char c = s.charAt(i); // Check if i equal to 0 if(i==0) { allCount = 1; map.put(c,1); levelCount = 1; continue; } // Replace levelCount with // allCount + 1 levelCount = allCount + 1; // If map is less than 0 if(map.get(c)<0) { allCount = allCount + levelCount; } else { allCount = allCount + levelCount - map.get(c); } map.put(c,levelCount); } // Return answer return allCount; } // Driver Code public static void main(String[] args) { List<String> list = Arrays.asList(\"abab\",\"gfg\"); for(String s : list) { int cnt = countSub(s); int withEmptyString = cnt+1; System.out.println(\"With empty string count for \" + s +\" is \" + withEmptyString); System.out.println(\"Without empty string count for \" + s + \" is \" + cnt); } }}//Code is contributed by abhisht7",
"e": 21052,
"s": 19489,
"text": null
},
{
"code": "# Python3 program for above approach # Returns count of distinct # subsequences of str.def countSub(s): Map = {} # Iterate from 0 to length of s for i in range(len(s)): Map[s[i]] = -1 allCount = 0 levelCount = 0 # Iterate from 0 to length of s for i in range(len(s)): c = s[i] # Check if i equal to 0 if (i == 0): allCount = 1 Map = 1 levelCount = 1 continue # Replace levelCount with # allCount + 1 levelCount = allCount + 1 # If map is less than 0 if (Map < 0): allCount = allCount + levelCount else: allCount = allCount + levelCount - Map Map = levelCount # Return answer return allCount # Driver CodeList = [ \"abab\", \"gfg\" ] for s in List: cnt = countSub(s) withEmptyString = cnt + 1 print(\"With empty string count for\", s, \"is\", withEmptyString) print(\"Without empty string count for\", s, \"is\", cnt) # This code is contributed by rag2127",
"e": 22111,
"s": 21052,
"text": null
},
{
"code": "// C# Program for above approachusing System;using System.Collections.Generic; class GFG{ // Returns count of distinct// subsequences of str.public static int countSub(String s){ Dictionary<char, int> map = new Dictionary<char, int>(); // Iterate from 0 to s.length() for(int i = 0; i < s.Length; i++) { if (!map.ContainsKey(s[i])) { map.Add(s[i], -1); } } int allCount = 0; int levelCount = 0; // Iterate from 0 to s.length() for(int i = 0; i < s.Length; i++) { char c = s[i]; // Check if i equal to 0 if (i == 0) { allCount = 1; if (!map.ContainsKey(c)) { map.Add(c, 1); } else { map = 1; } levelCount = 1; continue; } // Replace levelCount with // allCount + 1 levelCount = allCount + 1; // If map is less than 0 if (map.ContainsKey(c)) { if (map < 0) { allCount = (allCount + levelCount); } else { allCount = (allCount + levelCount - map); } } if (!map.ContainsKey(c)) { map.Add(c, levelCount); } else { map = levelCount; } } // Return answer return allCount; } // Driver Codestatic void Main(){ List<string> list = new List<string>(); list.Add(\"abab\"); list.Add(\"gfg\"); foreach(string s in list) { int cnt = countSub(s); int withEmptyString = cnt + 1; Console.WriteLine(\"With empty string count for \" + s + \" is \" + withEmptyString); Console.WriteLine(\"Without empty string count for \" + s + \" is \" + cnt); }}} // This code is contributed by divyesh072019",
"e": 24200,
"s": 22111,
"text": null
},
{
"code": "<script>// Javascript Program for above approach // Returns count of distinct // subsequences of str. function countSub(s) { let map = new Map(); // Iterate from 0 to s.length() for(let i = 0; i < s.length; i++) { map.set(s[i], -1); } let allCount = 0; let levelCount = 0; // Iterate from 0 to s.length() for(let i=0;i<s.length;i++) { let c = s[i]; // Check if i equal to 0 if(i==0) { allCount = 1; map.set(c,1); levelCount = 1; continue; } // Replace levelCount with // allCount + 1 levelCount = allCount + 1; // If map is less than 0 if(map.get(c)<0) { allCount = allCount + levelCount; } else { allCount = allCount + levelCount - map.get(c); } map.set(c,levelCount); } // Return answer return allCount; } // Driver Code let list=[\"abab\",\"gfg\"]; for(let i=0;i<list.length;i++) { let cnt = countSub(list[i]); let withEmptyString = cnt+1; document.write(\"With empty string count for \" + list[i] +\" is \" + withEmptyString+\"<br>\"); document.write(\"Without empty string count for \" + list[i] + \" is \" + cnt+\"<br>\"); } // This code is contributed by unknown2108</script>",
"e": 25629,
"s": 24200,
"text": null
},
{
"code": null,
"e": 25787,
"s": 25629,
"text": "With empty string count for abab is 12\nWithout empty string count for abab is 11\nWith empty string count for gfg is 7\nWithout empty string count for gfg is 6"
},
{
"code": null,
"e": 25831,
"s": 25787,
"text": "Time Complexity: O(n)Space Complexity: O(1)"
},
{
"code": null,
"e": 25842,
"s": 25831,
"text": "s_pandey06"
},
{
"code": null,
"e": 25857,
"s": 25842,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 25869,
"s": 25857,
"text": "29AjayKumar"
},
{
"code": null,
"e": 25883,
"s": 25869,
"text": "mishrakishan1"
},
{
"code": null,
"e": 25897,
"s": 25883,
"text": "abhishtmishra"
},
{
"code": null,
"e": 25918,
"s": 25897,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 25936,
"s": 25918,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 25950,
"s": 25936,
"text": "divyesh072019"
},
{
"code": null,
"e": 25958,
"s": 25950,
"text": "rag2127"
},
{
"code": null,
"e": 25967,
"s": 25958,
"text": "mukesh07"
},
{
"code": null,
"e": 25979,
"s": 25967,
"text": "unknown2108"
},
{
"code": null,
"e": 25989,
"s": 25979,
"text": "patel2127"
},
{
"code": null,
"e": 25998,
"s": 25989,
"text": "yash_760"
},
{
"code": null,
"e": 26008,
"s": 25998,
"text": "as5853535"
},
{
"code": null,
"e": 26022,
"s": 26008,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26038,
"s": 26022,
"text": "simranarora5sos"
},
{
"code": null,
"e": 26055,
"s": 26038,
"text": "arorakashish0911"
},
{
"code": null,
"e": 26072,
"s": 26055,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 26084,
"s": 26072,
"text": "subsequence"
},
{
"code": null,
"e": 26104,
"s": 26084,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 26112,
"s": 26104,
"text": "Strings"
},
{
"code": null,
"e": 26120,
"s": 26112,
"text": "Strings"
},
{
"code": null,
"e": 26140,
"s": 26120,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 26238,
"s": 26140,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26306,
"s": 26238,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 26339,
"s": 26306,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 26374,
"s": 26339,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 26405,
"s": 26374,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 26473,
"s": 26405,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 26519,
"s": 26473,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 26544,
"s": 26519,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 26604,
"s": 26544,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 26619,
"s": 26604,
"text": "C++ Data Types"
}
] |
iText - Adding a Paragraph
|
In this chapter, we will see how to create a PDF document and add a paragraph to it using the iText library.
You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter, to its constructor. Then, to add a paragraph to the document, you need to instantiate the Paragraph class and add this object to the document using the add() method.
Following are the steps to create a PDF document with a paragraph in it.
The PdfWriter class represents the Doc Writer for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created.
Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below.
// Creating a PdfWriter
String dest = "C:/itextExamples/addingParagraph.pdf";
PdfWriter writer = new PdfWriter(dest);
When the object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified.
The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor.
Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below.
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class.
The Document class of the package com.itextpdf.layout is the root element. While creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument.
Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps as shown below.
// Creating a Document
Document document = new Document(pdfDoc);
The Paragraph class represents a self-contained block of textual and graphical information. It belongs to the package com.itextpdf.layout.element.
Instantiate the Paragraph class by passing the text content as a string to its constructor, as shown below.
String para = "Welcome to Tutorialspoint.";
// Creating an Area Break
Paragraph para = new Paragraph (para);
Add the Paragraph object created in the previous step using the add() method of the Document class, as shown below.
// Adding area break to the PDF
document.add(para);
Close the document using the close() method of the Document class, as shown below.
// Closing the document
document.close();
The following Java program demonstrates how to create a PDF document and add a paragraph to it using the iText library. It creates a PDF document with the name addingParagraph.pdf, adds a paragraph to it, and saves it in the path C:/itextExamples/.
Save this code in a file with the name AddingParagraph.java.
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
public class AddingParagraph {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/addingParagraph.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
String para1 = "Tutorials Point originated from the idea that there exists
a class of readers who respond better to online content and prefer to learn
new skills at their own pace from the comforts of their drawing rooms.";
String para2 = "The journey commenced with a single tutorial on HTML in 2006
and elated by the response it generated, we worked our way to adding fresh
tutorials to our repository which now proudly flaunts a wealth of tutorials
and allied articles on topics ranging from programming languages to web designing
to academics and much more.";
// Creating Paragraphs
Paragraph paragraph1 = new Paragraph(para1);
Paragraph paragraph2 = new Paragraph(para2);
// Adding paragraphs to document
document.add(paragraph1);
document.add(paragraph2);
// Closing the document
document.close();
System.out.println("Paragraph added");
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac AddingParagraph.java
java AddingParagraph
Upon execution, the above program creates a PDF document, displaying the following message.
Paragraph added
If you verify the specified path, you can find the created PDF document, as shown below.
|
[
{
"code": null,
"e": 2611,
"s": 2502,
"text": "In this chapter, we will see how to create a PDF document and add a paragraph to it using the iText library."
},
{
"code": null,
"e": 2937,
"s": 2611,
"text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter, to its constructor. Then, to add a paragraph to the document, you need to instantiate the Paragraph class and add this object to the document using the add() method."
},
{
"code": null,
"e": 3010,
"s": 2937,
"text": "Following are the steps to create a PDF document with a paragraph in it."
},
{
"code": null,
"e": 3240,
"s": 3010,
"text": "The PdfWriter class represents the Doc Writer for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created."
},
{
"code": null,
"e": 3389,
"s": 3240,
"text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below."
},
{
"code": null,
"e": 3511,
"s": 3389,
"text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/addingParagraph.pdf\"; \nPdfWriter writer = new PdfWriter(dest); \n"
},
{
"code": null,
"e": 3652,
"s": 3511,
"text": "When the object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified."
},
{
"code": null,
"e": 3904,
"s": 3652,
"text": "The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor."
},
{
"code": null,
"e": 4020,
"s": 3904,
"text": "Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below."
},
{
"code": null,
"e": 4096,
"s": 4020,
"text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer); \n"
},
{
"code": null,
"e": 4267,
"s": 4096,
"text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class."
},
{
"code": null,
"e": 4462,
"s": 4267,
"text": "The Document class of the package com.itextpdf.layout is the root element. While creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument."
},
{
"code": null,
"e": 4586,
"s": 4462,
"text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps as shown below."
},
{
"code": null,
"e": 4656,
"s": 4586,
"text": "// Creating a Document \nDocument document = new Document(pdfDoc); \n"
},
{
"code": null,
"e": 4803,
"s": 4656,
"text": "The Paragraph class represents a self-contained block of textual and graphical information. It belongs to the package com.itextpdf.layout.element."
},
{
"code": null,
"e": 4911,
"s": 4803,
"text": "Instantiate the Paragraph class by passing the text content as a string to its constructor, as shown below."
},
{
"code": null,
"e": 5027,
"s": 4911,
"text": "String para = \"Welcome to Tutorialspoint.\"; \n// Creating an Area Break \nParagraph para = new Paragraph (para); \n"
},
{
"code": null,
"e": 5143,
"s": 5027,
"text": "Add the Paragraph object created in the previous step using the add() method of the Document class, as shown below."
},
{
"code": null,
"e": 5198,
"s": 5143,
"text": "// Adding area break to the PDF \ndocument.add(para); \n"
},
{
"code": null,
"e": 5281,
"s": 5198,
"text": "Close the document using the close() method of the Document class, as shown below."
},
{
"code": null,
"e": 5325,
"s": 5281,
"text": "// Closing the document \ndocument.close();\n"
},
{
"code": null,
"e": 5574,
"s": 5325,
"text": "The following Java program demonstrates how to create a PDF document and add a paragraph to it using the iText library. It creates a PDF document with the name addingParagraph.pdf, adds a paragraph to it, and saves it in the path C:/itextExamples/."
},
{
"code": null,
"e": 5635,
"s": 5574,
"text": "Save this code in a file with the name AddingParagraph.java."
},
{
"code": null,
"e": 7367,
"s": 5635,
"text": "import com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfWriter; \nimport com.itextpdf.layout.Document; \nimport com.itextpdf.layout.element.Paragraph; \n\npublic class AddingParagraph { \n public static void main(String args[]) throws Exception {\n // Creating a PdfWriter \n String dest = \"C:/itextExamples/addingParagraph.pdf\"; \n PdfWriter writer = new PdfWriter(dest); \n \n // Creating a PdfDocument \n PdfDocument pdf = new PdfDocument(writer); \n \n // Creating a Document \n Document document = new Document(pdf); \n String para1 = \"Tutorials Point originated from the idea that there exists \n a class of readers who respond better to online content and prefer to learn \n new skills at their own pace from the comforts of their drawing rooms.\"; \n \n String para2 = \"The journey commenced with a single tutorial on HTML in 2006 \n and elated by the response it generated, we worked our way to adding fresh \n tutorials to our repository which now proudly flaunts a wealth of tutorials \n and allied articles on topics ranging from programming languages to web designing \n to academics and much more.\"; \n \n // Creating Paragraphs \n Paragraph paragraph1 = new Paragraph(para1); \n Paragraph paragraph2 = new Paragraph(para2); \n \n // Adding paragraphs to document \n document.add(paragraph1); \n document.add(paragraph2); \n \n // Closing the document \n document.close(); \n System.out.println(\"Paragraph added\"); \n } \n} "
},
{
"code": null,
"e": 7462,
"s": 7367,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 7512,
"s": 7462,
"text": "javac AddingParagraph.java \njava AddingParagraph\n"
},
{
"code": null,
"e": 7604,
"s": 7512,
"text": "Upon execution, the above program creates a PDF document, displaying the following message."
},
{
"code": null,
"e": 7621,
"s": 7604,
"text": "Paragraph added\n"
}
] |
GATE | GATE-CS-2006 | Question 60
|
17 Sep, 2021
Consider the following C code segment.
for (i = 0, i<n; i++){ for (j=0; j<n; j++) { if (i%2) { x += (4*j + 5*i); y += (7 + 4*j); } }}
Which one of the following is false?(A) The code contains loop invariant computation(B) There is scope of common sub-expression elimination in this code(C) There is scope of strength reduction in this code(D) There is scope of dead code elimination in this codeAnswer: (D)Explanation: Question asks about false statement
4*j is common subexpression elimination so B is true.
5*i can be moved out of inner loop so can be i%2.
Means, A is true as we have loop invariant computation.
Next, 4*j as well as 5*i can be replaced with a = - 4;
before j loop then a = a + 4; where 4*j is computed,
likewise for 5*i. C is true as there is scope of strength
reduction.
By choice elimination, we have D.
GATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE | - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0033:31 / 38:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mNG-F-8t3a4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 1996 | Question 38
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 67,
"s": 28,
"text": "Consider the following C code segment."
},
{
"code": "for (i = 0, i<n; i++){ for (j=0; j<n; j++) { if (i%2) { x += (4*j + 5*i); y += (7 + 4*j); } }}",
"e": 214,
"s": 67,
"text": null
},
{
"code": null,
"e": 535,
"s": 214,
"text": "Which one of the following is false?(A) The code contains loop invariant computation(B) There is scope of common sub-expression elimination in this code(C) There is scope of strength reduction in this code(D) There is scope of dead code elimination in this codeAnswer: (D)Explanation: Question asks about false statement"
},
{
"code": null,
"e": 913,
"s": 535,
"text": "\n4*j is common subexpression elimination so B is true.\n\n5*i can be moved out of inner loop so can be i%2. \nMeans, A is true as we have loop invariant computation.\n\nNext, 4*j as well as 5*i can be replaced with a = - 4;\nbefore j loop then a = a + 4; where 4*j is computed,\nlikewise for 5*i. C is true as there is scope of strength \nreduction. \n\nBy choice elimination, we have D."
},
{
"code": null,
"e": 1945,
"s": 913,
"text": "GATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE | - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0033:31 / 38:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=mNG-F-8t3a4\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 1958,
"s": 1945,
"text": "GATE-CS-2006"
},
{
"code": null,
"e": 1976,
"s": 1958,
"text": "GATE-GATE-CS-2006"
},
{
"code": null,
"e": 1981,
"s": 1976,
"text": "GATE"
},
{
"code": null,
"e": 2079,
"s": 1981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2121,
"s": 2079,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 2183,
"s": 2121,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 2217,
"s": 2183,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 2259,
"s": 2217,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 2301,
"s": 2259,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 2335,
"s": 2301,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 2377,
"s": 2335,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
},
{
"code": null,
"e": 2411,
"s": 2377,
"text": "GATE | GATE CS 2011 | Question 49"
},
{
"code": null,
"e": 2445,
"s": 2411,
"text": "GATE | GATE-CS-2004 | Question 31"
}
] |
Pacman command in Arch Linux
|
21 Dec, 2021
Pacman is a package manager for the arch Linux and arch-based Linux distributions. If you have used Debian-based OS like ubuntu, then the Pacman is similar to the apt command of Debian-based operating systems. Pacman contains the compressed files as a package format and maintains a text-based package database. Pacman keeps the system up to date by synchronizing package lists with the master server. Pacman can install the packages from the official repositories or your own build packages.
In this article, we are going to see how to use Pacman to manage the software in arch-based systems. Now let’s see how to use Pacman.
When we install any new operating system on our machine, the first task we do is to install the software packages on the system. Now, to install the packages on Arch Linux, use the command Pacman with -S option and mention the package name. The -S option tells the Pacman to synchronize and to continue. Here is one example
sudo pacman -S cmatrix
We can mention the many package names after the -S option, separated by space.
sudo pacman -S package1 package2 package3
Then Pacman will show the download and install size of the package and ask for to proceed, then simply press the Y key. Pacman categorizes the installed packages into two categories.
Implicitly Installed: The package that was installed using the -S or -U option.
Dependencies: The package is installed because it is required by another package.
Now let’s see how to remove the installed package.
When we don’t need the package anymore, then we should remove the package from the system. To remove the package with all its dependencies which are not required by other packages, use the following command:
sudo pacman -Rs <package_name>
To remove the package without removing its dependency use the following command:
sudo pacman -R <package_name>
To remove the dependencies which are not required anymore, use the following command:
pacman -Qdtq | pacman -Rs -
In arch Linux, we can upgrade the full system by only one command using the Pacman. Use the following command to update the system:
sudo pacman -Suy
Let’s understand the meaning, S tell the pacman to synchronize the local database with the main database. u tells the pacman to upgrade the packages and y update the local catch on the system. Basically, this command synchronizes the local pacman database with the main repository database and then updates the system.
Now let’s see how we can search the package into the database of pacman. To search query in the name and description of the package in the database use the following command:
sudo pacman -Ss <query1> <query2>
To search into already installed packages on the system, use the following command:
sudo pacman -Qs query1> <query2>
To search the query into the local database use the following command:
sudo pacman -F query1> <query2>
When pacman downloads the packages it stores the packages into the /var/cache/pacman/pkg/ and while uninstalling the package pacman does not delete these files. Pacman uses these files to downgrade the package or install the package. But it can take a lot of space to store these packages. So to delete the stored packages, use the following command:
sudo pacman -Sc
To remove all stored packages and catch, use the following command:
sudp pacman -Scc
By using pacman we can install packages other than the main repository of Arch Linux. Use the following command to install the packages
For local:
sudo pacman -U path_to_file.pkg.tar.xz
For remote package:
sudo pacman -U http://www.example.com/repo/example.pkg.tar.xz
Sometimes installing the packages with pacman we face some errors. Following are the mainly occurred errors with pacman:
Conflicting file error: This error occurs due to some conflict packages present in the repository. To solve this error we can manually rename the file or force the overwrite function. We can use the following command to overwrite the function:
pacman -S --overwrite glob package
Invalid package: This error can occur due to the partial installation of the packages. We can solve this error by deleting .part files in /var/cache/pacman/pkg/.
Locking database: This error can occur when pacman is interrupted while updating the database. To solve this error, delete the file /var/lib/pacman/db.lock and update the database. Use the following command to delete the file:
rm /var/lib/pacman/db.lock
kk773572498
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 522,
"s": 28,
"text": "Pacman is a package manager for the arch Linux and arch-based Linux distributions. If you have used Debian-based OS like ubuntu, then the Pacman is similar to the apt command of Debian-based operating systems. Pacman contains the compressed files as a package format and maintains a text-based package database. Pacman keeps the system up to date by synchronizing package lists with the master server. Pacman can install the packages from the official repositories or your own build packages."
},
{
"code": null,
"e": 656,
"s": 522,
"text": "In this article, we are going to see how to use Pacman to manage the software in arch-based systems. Now let’s see how to use Pacman."
},
{
"code": null,
"e": 981,
"s": 656,
"text": "When we install any new operating system on our machine, the first task we do is to install the software packages on the system. Now, to install the packages on Arch Linux, use the command Pacman with -S option and mention the package name. The -S option tells the Pacman to synchronize and to continue. Here is one example "
},
{
"code": null,
"e": 1004,
"s": 981,
"text": "sudo pacman -S cmatrix"
},
{
"code": null,
"e": 1083,
"s": 1004,
"text": "We can mention the many package names after the -S option, separated by space."
},
{
"code": null,
"e": 1125,
"s": 1083,
"text": "sudo pacman -S package1 package2 package3"
},
{
"code": null,
"e": 1308,
"s": 1125,
"text": "Then Pacman will show the download and install size of the package and ask for to proceed, then simply press the Y key. Pacman categorizes the installed packages into two categories."
},
{
"code": null,
"e": 1388,
"s": 1308,
"text": "Implicitly Installed: The package that was installed using the -S or -U option."
},
{
"code": null,
"e": 1470,
"s": 1388,
"text": "Dependencies: The package is installed because it is required by another package."
},
{
"code": null,
"e": 1521,
"s": 1470,
"text": "Now let’s see how to remove the installed package."
},
{
"code": null,
"e": 1729,
"s": 1521,
"text": "When we don’t need the package anymore, then we should remove the package from the system. To remove the package with all its dependencies which are not required by other packages, use the following command:"
},
{
"code": null,
"e": 1760,
"s": 1729,
"text": "sudo pacman -Rs <package_name>"
},
{
"code": null,
"e": 1841,
"s": 1760,
"text": "To remove the package without removing its dependency use the following command:"
},
{
"code": null,
"e": 1871,
"s": 1841,
"text": "sudo pacman -R <package_name>"
},
{
"code": null,
"e": 1957,
"s": 1871,
"text": "To remove the dependencies which are not required anymore, use the following command:"
},
{
"code": null,
"e": 1986,
"s": 1957,
"text": "pacman -Qdtq | pacman -Rs -"
},
{
"code": null,
"e": 2118,
"s": 1986,
"text": "In arch Linux, we can upgrade the full system by only one command using the Pacman. Use the following command to update the system:"
},
{
"code": null,
"e": 2135,
"s": 2118,
"text": "sudo pacman -Suy"
},
{
"code": null,
"e": 2454,
"s": 2135,
"text": "Let’s understand the meaning, S tell the pacman to synchronize the local database with the main database. u tells the pacman to upgrade the packages and y update the local catch on the system. Basically, this command synchronizes the local pacman database with the main repository database and then updates the system."
},
{
"code": null,
"e": 2630,
"s": 2454,
"text": "Now let’s see how we can search the package into the database of pacman. To search query in the name and description of the package in the database use the following command:"
},
{
"code": null,
"e": 2667,
"s": 2630,
"text": "sudo pacman -Ss <query1> <query2>"
},
{
"code": null,
"e": 2751,
"s": 2667,
"text": "To search into already installed packages on the system, use the following command:"
},
{
"code": null,
"e": 2785,
"s": 2751,
"text": "sudo pacman -Qs query1> <query2>"
},
{
"code": null,
"e": 2856,
"s": 2785,
"text": "To search the query into the local database use the following command:"
},
{
"code": null,
"e": 2889,
"s": 2856,
"text": "sudo pacman -F query1> <query2>"
},
{
"code": null,
"e": 3240,
"s": 2889,
"text": "When pacman downloads the packages it stores the packages into the /var/cache/pacman/pkg/ and while uninstalling the package pacman does not delete these files. Pacman uses these files to downgrade the package or install the package. But it can take a lot of space to store these packages. So to delete the stored packages, use the following command:"
},
{
"code": null,
"e": 3256,
"s": 3240,
"text": "sudo pacman -Sc"
},
{
"code": null,
"e": 3324,
"s": 3256,
"text": "To remove all stored packages and catch, use the following command:"
},
{
"code": null,
"e": 3341,
"s": 3324,
"text": "sudp pacman -Scc"
},
{
"code": null,
"e": 3477,
"s": 3341,
"text": "By using pacman we can install packages other than the main repository of Arch Linux. Use the following command to install the packages"
},
{
"code": null,
"e": 3488,
"s": 3477,
"text": "For local:"
},
{
"code": null,
"e": 3527,
"s": 3488,
"text": "sudo pacman -U path_to_file.pkg.tar.xz"
},
{
"code": null,
"e": 3547,
"s": 3527,
"text": "For remote package:"
},
{
"code": null,
"e": 3609,
"s": 3547,
"text": "sudo pacman -U http://www.example.com/repo/example.pkg.tar.xz"
},
{
"code": null,
"e": 3730,
"s": 3609,
"text": "Sometimes installing the packages with pacman we face some errors. Following are the mainly occurred errors with pacman:"
},
{
"code": null,
"e": 3974,
"s": 3730,
"text": "Conflicting file error: This error occurs due to some conflict packages present in the repository. To solve this error we can manually rename the file or force the overwrite function. We can use the following command to overwrite the function:"
},
{
"code": null,
"e": 4009,
"s": 3974,
"text": "pacman -S --overwrite glob package"
},
{
"code": null,
"e": 4171,
"s": 4009,
"text": "Invalid package: This error can occur due to the partial installation of the packages. We can solve this error by deleting .part files in /var/cache/pacman/pkg/."
},
{
"code": null,
"e": 4398,
"s": 4171,
"text": "Locking database: This error can occur when pacman is interrupted while updating the database. To solve this error, delete the file /var/lib/pacman/db.lock and update the database. Use the following command to delete the file:"
},
{
"code": null,
"e": 4425,
"s": 4398,
"text": "rm /var/lib/pacman/db.lock"
},
{
"code": null,
"e": 4437,
"s": 4425,
"text": "kk773572498"
},
{
"code": null,
"e": 4448,
"s": 4437,
"text": "Linux-Unix"
},
{
"code": null,
"e": 4546,
"s": 4448,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4572,
"s": 4546,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 4607,
"s": 4572,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 4644,
"s": 4607,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 4673,
"s": 4644,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 4710,
"s": 4673,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 4747,
"s": 4710,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 4781,
"s": 4747,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 4821,
"s": 4781,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 4860,
"s": 4821,
"text": "Introduction to Linux Operating System"
}
] |
Python | Reading .ini Configuration Files
|
20 Jun, 2019
This article aims to read configuration files written in the common .ini configuration file format. The configparser module can be used to read configuration files.
Code #1 : Configuration File
abc.ini ; Sample configuration file[installation]library = %(prefix)s/libinclude = %(prefix)s/includebin = %(prefix)s/binprefix = /usr/local # Setting related to debug configuration[debug]pid-file = /tmp/spam.pidshow_warnings = Falselog_errors = true[server]nworkers: 32port: 8080root = /www/rootsignature:
Code #2 : Reading the file and extracting values.
from configparser import ConfigParser configur = ConfigParser()print (configur.read('config.ini')) print ("Sections : ", configur.sections())print ("Installation Library : ", configur.get('installation','library'))print ("Log Errors debugged ? : ", configur.getboolean('debug','log_errors'))print ("Port Server : ", configur.getint('server','port'))print ("Worker Server : ", configur.getint('server','nworkers'))
Output :
['config.ini']
Sections : ['installation', 'debug', 'server']
Installation Library : '/usr/local/lib'
Log Errors debugged ? : True
Port Server : 8080
Worker Server : 32
One can also modify the configuration and write it back to a file using the cfg.write() method.
Code #3 :
configur.set('server','port','9000')configur.set('debug','log_errors','False') import sysconfigur.write(sys.stdout)
Output :
[installation]
library = %(prefix)s/lib
include = %(prefix)s/include
bin = %(prefix)s/bin
prefix = /usr/local
[debug]
log_errors = False
show_warnings = False
[server]
port = 9000
nworkers = 32
pid-file = /tmp/spam.pid
root = /www/root
Configuration files are well suited to specify configuration data to your program. Within each config file, values are grouped into different sections (e.g., “installation”, “debug” and “server”).
Each section then has a specific value for various variables in that section. For the same purpose, there are some prominent differences between a config file and using a Python source file.
First, the syntax is much more permissive and “sloppy.”
Names used in a config file are also assumed to be case-insensitive as shown in the code below –
configur.get('installation','PREFIX') configur.get('installation','prefix')
Output :
'/usr/local'
'/usr/local'
When parsing values, methods such as getboolean() look for any reasonable value. For example, these are all equivalent.
log_errors = true
log_errors = TRUE
log_errors = Yes
log_errors = 1
The most noteworthy contrast between a config record and Python code is that, in contrast to scripts, configuration files are not executed in a top-down way. Rather, the file is read completely. On the off chance that variable substitutions are made, they are done later after the fact. For instance, it doesn’t make a difference that the prefix variable is allocated after different variables that happen to utilize it.
[installation]
library = %(prefix)s/lib
include = %(prefix)s/include
bin = %(prefix)s/bin
prefix = /usr/local
Multiple configuration files can be read together and their results can be merged into a single configuration using ConfigParser, which makes it so special to use.
Example – A user made their own configuration file that looks as.
; ~/.config.ini
[installation]
prefix = /Users/beazley/test
[debug]
log_errors = False
This file can be merged with the previous configuration by reading it separately
Code #4 :
import os # Previously read configurationprint (configur.get('installation', 'prefix')) # Merge in user-specific configurationprint (configur.read(os.path.expanduser('~/.config.ini')))print (configur.get('installation', 'prefix'))print (configur.get('installation', 'library')) print (configur.getboolean('debug', 'log_errors'))
Output :
'/usr/local'
['/Users/HP/.config.ini']
'/Users/HP/test'
'/Users/HP/test/lib'
False
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jun, 2019"
},
{
"code": null,
"e": 193,
"s": 28,
"text": "This article aims to read configuration files written in the common .ini configuration file format. The configparser module can be used to read configuration files."
},
{
"code": null,
"e": 222,
"s": 193,
"text": "Code #1 : Configuration File"
},
{
"code": "abc.ini ; Sample configuration file[installation]library = %(prefix)s/libinclude = %(prefix)s/includebin = %(prefix)s/binprefix = /usr/local # Setting related to debug configuration[debug]pid-file = /tmp/spam.pidshow_warnings = Falselog_errors = true[server]nworkers: 32port: 8080root = /www/rootsignature:",
"e": 531,
"s": 222,
"text": null
},
{
"code": null,
"e": 581,
"s": 531,
"text": "Code #2 : Reading the file and extracting values."
},
{
"code": "from configparser import ConfigParser configur = ConfigParser()print (configur.read('config.ini')) print (\"Sections : \", configur.sections())print (\"Installation Library : \", configur.get('installation','library'))print (\"Log Errors debugged ? : \", configur.getboolean('debug','log_errors'))print (\"Port Server : \", configur.getint('server','port'))print (\"Worker Server : \", configur.getint('server','nworkers')) ",
"e": 999,
"s": 581,
"text": null
},
{
"code": null,
"e": 1008,
"s": 999,
"text": "Output :"
},
{
"code": null,
"e": 1178,
"s": 1008,
"text": "['config.ini']\nSections : ['installation', 'debug', 'server']\nInstallation Library : '/usr/local/lib'\nLog Errors debugged ? : True\nPort Server : 8080\nWorker Server : 32\n"
},
{
"code": null,
"e": 1274,
"s": 1178,
"text": "One can also modify the configuration and write it back to a file using the cfg.write() method."
},
{
"code": null,
"e": 1284,
"s": 1274,
"text": "Code #3 :"
},
{
"code": "configur.set('server','port','9000')configur.set('debug','log_errors','False') import sysconfigur.write(sys.stdout)",
"e": 1401,
"s": 1284,
"text": null
},
{
"code": null,
"e": 1410,
"s": 1401,
"text": "Output :"
},
{
"code": null,
"e": 1649,
"s": 1410,
"text": "[installation]\nlibrary = %(prefix)s/lib\ninclude = %(prefix)s/include\nbin = %(prefix)s/bin\nprefix = /usr/local\n\n[debug]\nlog_errors = False\nshow_warnings = False\n\n[server]\nport = 9000\nnworkers = 32\npid-file = /tmp/spam.pid\nroot = /www/root\n"
},
{
"code": null,
"e": 1846,
"s": 1649,
"text": "Configuration files are well suited to specify configuration data to your program. Within each config file, values are grouped into different sections (e.g., “installation”, “debug” and “server”)."
},
{
"code": null,
"e": 2037,
"s": 1846,
"text": "Each section then has a specific value for various variables in that section. For the same purpose, there are some prominent differences between a config file and using a Python source file."
},
{
"code": null,
"e": 2093,
"s": 2037,
"text": "First, the syntax is much more permissive and “sloppy.”"
},
{
"code": null,
"e": 2190,
"s": 2093,
"text": "Names used in a config file are also assumed to be case-insensitive as shown in the code below –"
},
{
"code": "configur.get('installation','PREFIX') configur.get('installation','prefix')",
"e": 2267,
"s": 2190,
"text": null
},
{
"code": null,
"e": 2276,
"s": 2267,
"text": "Output :"
},
{
"code": null,
"e": 2302,
"s": 2276,
"text": "'/usr/local'\n'/usr/local'"
},
{
"code": null,
"e": 2422,
"s": 2302,
"text": "When parsing values, methods such as getboolean() look for any reasonable value. For example, these are all equivalent."
},
{
"code": null,
"e": 2490,
"s": 2422,
"text": "log_errors = true\nlog_errors = TRUE\nlog_errors = Yes\nlog_errors = 1"
},
{
"code": null,
"e": 2911,
"s": 2490,
"text": "The most noteworthy contrast between a config record and Python code is that, in contrast to scripts, configuration files are not executed in a top-down way. Rather, the file is read completely. On the off chance that variable substitutions are made, they are done later after the fact. For instance, it doesn’t make a difference that the prefix variable is allocated after different variables that happen to utilize it."
},
{
"code": null,
"e": 3021,
"s": 2911,
"text": "[installation]\nlibrary = %(prefix)s/lib\ninclude = %(prefix)s/include\nbin = %(prefix)s/bin\nprefix = /usr/local"
},
{
"code": null,
"e": 3185,
"s": 3021,
"text": "Multiple configuration files can be read together and their results can be merged into a single configuration using ConfigParser, which makes it so special to use."
},
{
"code": null,
"e": 3251,
"s": 3185,
"text": "Example – A user made their own configuration file that looks as."
},
{
"code": null,
"e": 3338,
"s": 3251,
"text": "; ~/.config.ini\n[installation]\nprefix = /Users/beazley/test\n[debug]\nlog_errors = False"
},
{
"code": null,
"e": 3419,
"s": 3338,
"text": "This file can be merged with the previous configuration by reading it separately"
},
{
"code": null,
"e": 3429,
"s": 3419,
"text": "Code #4 :"
},
{
"code": "import os # Previously read configurationprint (configur.get('installation', 'prefix')) # Merge in user-specific configurationprint (configur.read(os.path.expanduser('~/.config.ini')))print (configur.get('installation', 'prefix'))print (configur.get('installation', 'library')) print (configur.getboolean('debug', 'log_errors'))",
"e": 3761,
"s": 3429,
"text": null
},
{
"code": null,
"e": 3770,
"s": 3761,
"text": "Output :"
},
{
"code": null,
"e": 3855,
"s": 3770,
"text": "'/usr/local' \n['/Users/HP/.config.ini']\n'/Users/HP/test'\n'/Users/HP/test/lib'\nFalse\n"
},
{
"code": null,
"e": 3870,
"s": 3855,
"text": "python-utility"
},
{
"code": null,
"e": 3877,
"s": 3870,
"text": "Python"
},
{
"code": null,
"e": 3975,
"s": 3877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4007,
"s": 3975,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4034,
"s": 4007,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4065,
"s": 4034,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4088,
"s": 4065,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4109,
"s": 4088,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4165,
"s": 4109,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4207,
"s": 4165,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4249,
"s": 4207,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4288,
"s": 4249,
"text": "Python | Get unique values from a list"
}
] |
PHP | ord() Function
|
20 Mar, 2018
The ord() function is a inbuilt function in PHP that returns the ASCII value of the first character of a string. This function takes a character string as a parameter and returns the ASCII value of the first character of this string.
Syntax:
int ord($string)
Parameter: This function accepts a single parameter $string. This is a mandatory parameter from which we get an ASCII value.
Return value: This function returns an integer value which represents the ASCII value of the first character in the string passed to this function as a parameter.
Examples:
Input : Geeksforgeeks
Output : 71
Explanation: The ASCII value of G is 71
Input : twinkle
Output : 116
Explanation: The ASCII value of t is 116
Below programs illustrate the ord() function in PHP:
Program 1:
<?php// PHP program to illustrate the ord() function // ASCII value of 't' is printed.echo ord("twinkle");?>
Output:
116
Program 2:
<?php// PHP program to illustrate the ord() function // ASCII value of 'G' is printedecho ord("Geeksforgeeks");?>
Output:
71
Reference:http://php.net/manual/en/function.ord.php
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Mar, 2018"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "The ord() function is a inbuilt function in PHP that returns the ASCII value of the first character of a string. This function takes a character string as a parameter and returns the ASCII value of the first character of this string."
},
{
"code": null,
"e": 270,
"s": 262,
"text": "Syntax:"
},
{
"code": null,
"e": 287,
"s": 270,
"text": "int ord($string)"
},
{
"code": null,
"e": 412,
"s": 287,
"text": "Parameter: This function accepts a single parameter $string. This is a mandatory parameter from which we get an ASCII value."
},
{
"code": null,
"e": 575,
"s": 412,
"text": "Return value: This function returns an integer value which represents the ASCII value of the first character in the string passed to this function as a parameter."
},
{
"code": null,
"e": 585,
"s": 575,
"text": "Examples:"
},
{
"code": null,
"e": 731,
"s": 585,
"text": "Input : Geeksforgeeks\nOutput : 71\nExplanation: The ASCII value of G is 71\n\nInput : twinkle\nOutput : 116\nExplanation: The ASCII value of t is 116\n"
},
{
"code": null,
"e": 784,
"s": 731,
"text": "Below programs illustrate the ord() function in PHP:"
},
{
"code": null,
"e": 795,
"s": 784,
"text": "Program 1:"
},
{
"code": "<?php// PHP program to illustrate the ord() function // ASCII value of 't' is printed.echo ord(\"twinkle\");?>",
"e": 905,
"s": 795,
"text": null
},
{
"code": null,
"e": 913,
"s": 905,
"text": "Output:"
},
{
"code": null,
"e": 918,
"s": 913,
"text": "116\n"
},
{
"code": null,
"e": 929,
"s": 918,
"text": "Program 2:"
},
{
"code": "<?php// PHP program to illustrate the ord() function // ASCII value of 'G' is printedecho ord(\"Geeksforgeeks\");?>",
"e": 1044,
"s": 929,
"text": null
},
{
"code": null,
"e": 1052,
"s": 1044,
"text": "Output:"
},
{
"code": null,
"e": 1055,
"s": 1052,
"text": "71"
},
{
"code": null,
"e": 1107,
"s": 1055,
"text": "Reference:http://php.net/manual/en/function.ord.php"
},
{
"code": null,
"e": 1118,
"s": 1107,
"text": "PHP-string"
},
{
"code": null,
"e": 1122,
"s": 1118,
"text": "PHP"
},
{
"code": null,
"e": 1139,
"s": 1122,
"text": "Web Technologies"
},
{
"code": null,
"e": 1143,
"s": 1139,
"text": "PHP"
}
] |
Differences between TreeMap, HashMap and LinkedHashMap in Java
|
02 Aug, 2021
Prerequisite : HashMap and TreeMap in Java
TreeMap, HashMap and LinkedHashMap: What’s Similar?
All offer a key->value map and a way to iterate through the keys. The most important distinction between these classes is the time guarantees and the ordering of the keys.
All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map interface, and represents mapping from unique key to values.
Key Points
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys, though, the ordering of the keys is essentially arbitrary. It is implemented by an array of linked lists. Syntax:
HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys, though, the ordering of the keys is essentially arbitrary. It is implemented by an array of linked lists. Syntax:
public class HashMap extends AbstractMap
implements Map,Cloneable, Serializable
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
2. LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by their insertion order. It is implemented by doubly-linked buckets. Syntax:
public class LinkedHashMap extends HashMap
implements Map
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
3.TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through the keys in sorted order, you can. This means that keys must implement the Comparable interface. TreeMap is implemented by a Red-Black Tree. Syntax:
public class TreeMap extends AbstractMap implements
NavigableMap, Cloneable, Serializable
A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order(Sorted using the natural order of its key).
4. Hashtable: “Hashtable” is the generic name for hash-based maps. Syntax:
public class Hashtable extends Dictionary implements
Map, Cloneable, Serializable
A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
It is a legacy class.
HashMap
LinkedHashMap
TreeMap
// Java program to print ordering// of all elements using HashMapimport java.util.*;import java.lang.*;import java.io.*;class Main{ // This function prints ordering of all elements static void insertAndPrint(AbstractMap<Integer, String> map) { int[] array= {1, -1, 0, 2,-2}; for (int x: array) { map.put(x, Integer.toString(x)); } for (int k: map.keySet()) { System.out.print(k + ", "); } } // Driver method to test above method public static void main (String[] args) { HashMap<Integer, String> map = new HashMap<Integer, String>(); insertAndPrint(map); }}
// Java program to print ordering// of all elements using LinkedHashMapimport java.util.*;import java.lang.*;import java.io.*; class Main{ // This function prints ordering of all elements static void insertAndPrint(AbstractMap<Integer, String> map) { int[] array= {1, -1, 0, 2,-2}; for (int x: array) { map.put(x, Integer.toString(x)); } for (int k: map.keySet()) { System.out.print(k + ", "); } } // Driver method to test above method public static void main (String[] args) { LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>(); insertAndPrint(map); }}
// Java program to print ordering of// all elements using TreeMap import java.util.*;import java.lang.*;import java.io.*; class Main{ // This function prints ordering of all elements static void insertAndPrint(AbstractMap<Integer, String> map) { int[] array= {1, -1, 0, 2,-2}; for (int x: array) { map.put(x, Integer.toString(x)); } for (int k: map.keySet()) { System.out.print(k + ", "); } } // Driver method to test above method public static void main (String[] args) { TreeMap<Integer, String> map = new TreeMap<Integer, String>(); insertAndPrint(map); }}
Output of HashMap:
-1, 0, 1, -2, 2,
// ordering of the keys is essentially arbitrary (any ordering)
Output of LinkedHashMap:
1, -1, 0, 2, -2,
// Keys are ordered by their insertion order
Output of TreeMap:
-2, -1, 0, 1, 2,
// Keys are in sorted order
Comparison Table
Real Life Applications
Suppose you were creating a mapping of names to Person objects. You might want to periodically output the people in alphabetical order by name. A TreeMap lets you do this.A TreeMap also offers a way to, given a name, output the next 10 people. This could be useful for a “More”function in many applications.A LinkedHashMap is useful whenever you need the ordering of keys to match the ordering of insertion. This might be useful in a caching situation, when you want to delete the oldest item.Generally, unless there is a reason not to, you would use HashMap. That is, if you need to get the keys back in insertion order, then use LinkedHashMap. If you need to get the keys back in their true/natural order, then use TreeMap. Otherwise, HashMap is probably best. It is typically faster and requires less overhead.
Suppose you were creating a mapping of names to Person objects. You might want to periodically output the people in alphabetical order by name. A TreeMap lets you do this.
A TreeMap also offers a way to, given a name, output the next 10 people. This could be useful for a “More”function in many applications.
A LinkedHashMap is useful whenever you need the ordering of keys to match the ordering of insertion. This might be useful in a caching situation, when you want to delete the oldest item.
Generally, unless there is a reason not to, you would use HashMap. That is, if you need to get the keys back in insertion order, then use LinkedHashMap. If you need to get the keys back in their true/natural order, then use TreeMap. Otherwise, HashMap is probably best. It is typically faster and requires less overhead.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
siddharth chandran.e
Java-HashMap
Java-LinkedHashMap
Java-Map-Programs
java-TreeMap
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Aug, 2021"
},
{
"code": null,
"e": 98,
"s": 54,
"text": "Prerequisite : HashMap and TreeMap in Java "
},
{
"code": null,
"e": 151,
"s": 98,
"text": "TreeMap, HashMap and LinkedHashMap: What’s Similar? "
},
{
"code": null,
"e": 323,
"s": 151,
"text": "All offer a key->value map and a way to iterate through the keys. The most important distinction between these classes is the time guarantees and the ordering of the keys."
},
{
"code": null,
"e": 463,
"s": 323,
"text": "All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map interface, and represents mapping from unique key to values. "
},
{
"code": null,
"e": 475,
"s": 463,
"text": "Key Points "
},
{
"code": null,
"e": 675,
"s": 475,
"text": "HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys, though, the ordering of the keys is essentially arbitrary. It is implemented by an array of linked lists. Syntax: "
},
{
"code": null,
"e": 875,
"s": 675,
"text": "HashMap: HashMap offers 0(1) lookup and insertion. If you iterate through the keys, though, the ordering of the keys is essentially arbitrary. It is implemented by an array of linked lists. Syntax: "
},
{
"code": null,
"e": 956,
"s": 875,
"text": "public class HashMap extends AbstractMap \nimplements Map,Cloneable, Serializable"
},
{
"code": null,
"e": 1002,
"s": 958,
"text": "A HashMap contains values based on the key."
},
{
"code": null,
"e": 1036,
"s": 1002,
"text": "It contains only unique elements."
},
{
"code": null,
"e": 1087,
"s": 1036,
"text": "It may have one null key and multiple null values."
},
{
"code": null,
"e": 1110,
"s": 1087,
"text": "It maintains no order."
},
{
"code": null,
"e": 1273,
"s": 1110,
"text": "2. LinkedHashMap: LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by their insertion order. It is implemented by doubly-linked buckets. Syntax: "
},
{
"code": null,
"e": 1332,
"s": 1273,
"text": "public class LinkedHashMap extends HashMap \nimplements Map"
},
{
"code": null,
"e": 1384,
"s": 1334,
"text": "A LinkedHashMap contains values based on the key."
},
{
"code": null,
"e": 1418,
"s": 1384,
"text": "It contains only unique elements."
},
{
"code": null,
"e": 1469,
"s": 1418,
"text": "It may have one null key and multiple null values."
},
{
"code": null,
"e": 1526,
"s": 1469,
"text": "It is same as HashMap instead maintains insertion order."
},
{
"code": null,
"e": 1786,
"s": 1526,
"text": "3.TreeMap: TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through the keys in sorted order, you can. This means that keys must implement the Comparable interface. TreeMap is implemented by a Red-Black Tree. Syntax: "
},
{
"code": null,
"e": 1876,
"s": 1786,
"text": "public class TreeMap extends AbstractMap implements\nNavigableMap, Cloneable, Serializable"
},
{
"code": null,
"e": 1994,
"s": 1878,
"text": "A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class."
},
{
"code": null,
"e": 2028,
"s": 1994,
"text": "It contains only unique elements."
},
{
"code": null,
"e": 2087,
"s": 2028,
"text": "It cannot have null key but can have multiple null values."
},
{
"code": null,
"e": 2187,
"s": 2087,
"text": "It is same as HashMap instead maintains ascending order(Sorted using the natural order of its key)."
},
{
"code": null,
"e": 2263,
"s": 2187,
"text": "4. Hashtable: “Hashtable” is the generic name for hash-based maps. Syntax: "
},
{
"code": null,
"e": 2345,
"s": 2263,
"text": "public class Hashtable extends Dictionary implements\nMap, Cloneable, Serializable"
},
{
"code": null,
"e": 2529,
"s": 2347,
"text": "A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key."
},
{
"code": null,
"e": 2563,
"s": 2529,
"text": "It contains only unique elements."
},
{
"code": null,
"e": 2607,
"s": 2563,
"text": "It may have not have any null key or value."
},
{
"code": null,
"e": 2627,
"s": 2607,
"text": "It is synchronized."
},
{
"code": null,
"e": 2649,
"s": 2627,
"text": "It is a legacy class."
},
{
"code": null,
"e": 2659,
"s": 2651,
"text": "HashMap"
},
{
"code": null,
"e": 2673,
"s": 2659,
"text": "LinkedHashMap"
},
{
"code": null,
"e": 2681,
"s": 2673,
"text": "TreeMap"
},
{
"code": "// Java program to print ordering// of all elements using HashMapimport java.util.*;import java.lang.*;import java.io.*;class Main{ // This function prints ordering of all elements static void insertAndPrint(AbstractMap<Integer, String> map) { int[] array= {1, -1, 0, 2,-2}; for (int x: array) { map.put(x, Integer.toString(x)); } for (int k: map.keySet()) { System.out.print(k + \", \"); } } // Driver method to test above method public static void main (String[] args) { HashMap<Integer, String> map = new HashMap<Integer, String>(); insertAndPrint(map); }}",
"e": 3349,
"s": 2681,
"text": null
},
{
"code": "// Java program to print ordering// of all elements using LinkedHashMapimport java.util.*;import java.lang.*;import java.io.*; class Main{ // This function prints ordering of all elements static void insertAndPrint(AbstractMap<Integer, String> map) { int[] array= {1, -1, 0, 2,-2}; for (int x: array) { map.put(x, Integer.toString(x)); } for (int k: map.keySet()) { System.out.print(k + \", \"); } } // Driver method to test above method public static void main (String[] args) { LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>(); insertAndPrint(map); }}",
"e": 4040,
"s": 3349,
"text": null
},
{
"code": "// Java program to print ordering of// all elements using TreeMap import java.util.*;import java.lang.*;import java.io.*; class Main{ // This function prints ordering of all elements static void insertAndPrint(AbstractMap<Integer, String> map) { int[] array= {1, -1, 0, 2,-2}; for (int x: array) { map.put(x, Integer.toString(x)); } for (int k: map.keySet()) { System.out.print(k + \", \"); } } // Driver method to test above method public static void main (String[] args) { TreeMap<Integer, String> map = new TreeMap<Integer, String>(); insertAndPrint(map); }}",
"e": 4710,
"s": 4040,
"text": null
},
{
"code": null,
"e": 4731,
"s": 4710,
"text": "Output of HashMap: "
},
{
"code": null,
"e": 4817,
"s": 4731,
"text": "-1, 0, 1, -2, 2, \n// ordering of the keys is essentially arbitrary (any ordering)"
},
{
"code": null,
"e": 4844,
"s": 4817,
"text": "Output of LinkedHashMap: "
},
{
"code": null,
"e": 4912,
"s": 4844,
"text": " 1, -1, 0, 2, -2, \n// Keys are ordered by their insertion order"
},
{
"code": null,
"e": 4933,
"s": 4912,
"text": "Output of TreeMap: "
},
{
"code": null,
"e": 4982,
"s": 4933,
"text": " -2, -1, 0, 1, 2, \n// Keys are in sorted order"
},
{
"code": null,
"e": 5000,
"s": 4982,
"text": "Comparison Table "
},
{
"code": null,
"e": 5025,
"s": 5002,
"text": "Real Life Applications"
},
{
"code": null,
"e": 5839,
"s": 5025,
"text": "Suppose you were creating a mapping of names to Person objects. You might want to periodically output the people in alphabetical order by name. A TreeMap lets you do this.A TreeMap also offers a way to, given a name, output the next 10 people. This could be useful for a “More”function in many applications.A LinkedHashMap is useful whenever you need the ordering of keys to match the ordering of insertion. This might be useful in a caching situation, when you want to delete the oldest item.Generally, unless there is a reason not to, you would use HashMap. That is, if you need to get the keys back in insertion order, then use LinkedHashMap. If you need to get the keys back in their true/natural order, then use TreeMap. Otherwise, HashMap is probably best. It is typically faster and requires less overhead."
},
{
"code": null,
"e": 6011,
"s": 5839,
"text": "Suppose you were creating a mapping of names to Person objects. You might want to periodically output the people in alphabetical order by name. A TreeMap lets you do this."
},
{
"code": null,
"e": 6148,
"s": 6011,
"text": "A TreeMap also offers a way to, given a name, output the next 10 people. This could be useful for a “More”function in many applications."
},
{
"code": null,
"e": 6335,
"s": 6148,
"text": "A LinkedHashMap is useful whenever you need the ordering of keys to match the ordering of insertion. This might be useful in a caching situation, when you want to delete the oldest item."
},
{
"code": null,
"e": 6656,
"s": 6335,
"text": "Generally, unless there is a reason not to, you would use HashMap. That is, if you need to get the keys back in insertion order, then use LinkedHashMap. If you need to get the keys back in their true/natural order, then use TreeMap. Otherwise, HashMap is probably best. It is typically faster and requires less overhead."
},
{
"code": null,
"e": 7083,
"s": 6656,
"text": "This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 7104,
"s": 7083,
"text": "siddharth chandran.e"
},
{
"code": null,
"e": 7117,
"s": 7104,
"text": "Java-HashMap"
},
{
"code": null,
"e": 7136,
"s": 7117,
"text": "Java-LinkedHashMap"
},
{
"code": null,
"e": 7154,
"s": 7136,
"text": "Java-Map-Programs"
},
{
"code": null,
"e": 7167,
"s": 7154,
"text": "java-TreeMap"
},
{
"code": null,
"e": 7186,
"s": 7167,
"text": "Difference Between"
},
{
"code": null,
"e": 7191,
"s": 7186,
"text": "Java"
},
{
"code": null,
"e": 7196,
"s": 7191,
"text": "Java"
},
{
"code": null,
"e": 7294,
"s": 7196,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7334,
"s": 7294,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 7365,
"s": 7334,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 7426,
"s": 7365,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7494,
"s": 7426,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 7531,
"s": 7494,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 7546,
"s": 7531,
"text": "Arrays in Java"
},
{
"code": null,
"e": 7582,
"s": 7546,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 7626,
"s": 7582,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 7651,
"s": 7626,
"text": "Reverse a string in Java"
}
] |
Loops in JavaScript
|
22 Jun, 2022
Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below:
Iterative Method
The iterative method to do this is to write the document.write() statement 10 times.
JavaScript
<script type = "text/javascript">document.write("Hello World\n");document.write("Hello World\n");document.write("Hello World\n");document.write("Hello World\n");document.write("Hello World\n");document.write("Hello World\n");document.write("Hello World\n");document.write("Hello World\n");document.write("Hello World\n");document.write("Hello World\n");</script>
Using Loops
In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below:
JavaScript
<script type = "text/javascript">var i; for (i = 0; i < 10; i++){ document.write("Hello World!\n");}</script>
Many things may seem confusing to you in the above program at this point of time but do not worry you will be able to understand everything about loops in JavaScript by the end of this tutorial. You can observe that in the above program using loops we have used the document.write statement only once but still, the output of the program will be the same as that of the iterative program where we have used the document.write statement 10 times. In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.
An operation is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.
Counter not Reached: If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeats it.
Counter reached: If the condition has been reached, the next instruction “falls through” to the next sequential instruction or branches outside the loop.
There are mainly two types of loops:
Entry Controlled loops: In these types of loops, the test condition is tested before entering the loop body. For Loops and While Loops are entry-controlled loops.Exit Controlled loops: In these types of loops the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. The do-while loop is exit controlled loop.
Entry Controlled loops: In these types of loops, the test condition is tested before entering the loop body. For Loops and While Loops are entry-controlled loops.
Exit Controlled loops: In these types of loops the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. The do-while loop is exit controlled loop.
JavaScript mainly provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time. Let us learn about each one of these in detail.
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax :
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax :
while (boolean condition)
{
loop statements...
}
Flowchart: While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the Entry control loopOnce the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.When the condition becomes false, the loop terminates which marks the end of its life cycle.for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Syntax:
Flowchart: While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the Entry control loopOnce the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.When the condition becomes false, the loop terminates which marks the end of its life cycle.
While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the Entry control loop
Once the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Syntax:
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
Flowchart: Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.Increment/ Decrement: It is used for updating the variable for the next iteration.Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.do-while: do-while loop is similar to the while loop with the only difference that it checks for the condition after executing the statements, and therefore is an example of an Exit Control Loop. Syntax:
Flowchart: Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.Increment/ Decrement: It is used for updating the variable for the next iteration.Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.
Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.Increment/ Decrement: It is used for updating the variable for the next iteration.Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.
Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.
Increment/ Decrement: It is used for updating the variable for the next iteration.
Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.
do-while: do-while loop is similar to the while loop with the only difference that it checks for the condition after executing the statements, and therefore is an example of an Exit Control Loop. Syntax:
do
{
statements..
}
while (condition);
Flowchart: The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.After the execution of the statements, and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.When the condition becomes false, the loop terminates which marks the end of its life cycle.It is important to note that the do-while loop will execute its statements at least once before any condition is checked, and therefore is an example of the exit control loop.
Flowchart: The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.After the execution of the statements, and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.When the condition becomes false, the loop terminates which marks the end of its life cycle.It is important to note that the do-while loop will execute its statements at least once before any condition is checked, and therefore is an example of the exit control loop.
The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.After the execution of the statements, and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.When the condition becomes false, the loop terminates which marks the end of its life cycle.It is important to note that the do-while loop will execute its statements at least once before any condition is checked, and therefore is an example of the exit control loop.
The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.
After the execution of the statements, and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
It is important to note that the do-while loop will execute its statements at least once before any condition is checked, and therefore is an example of the exit control loop.
Infinite loop
One of the most common mistakes while implementing any sort of looping is that it may not ever exit, that is the loop runs for infinite times. This happens when the condition fails for some reason. Examples:
JavaScript
<script type = "text/javaScript">// JavaScript program to illustrate infinite loop // infinite loop because condition is not apt // condition should have been i>0. for (var i = 5; i != 0; i -= 2) { document.write(i); } var x = 5; // infinite loop because update statement // is not provided. while (x == 5) { document.write("In the loop"); } </script>
sagartomar9927
technophpfij
farzams101
javascript-basics
JavaScript-Misc
Loops & Control Structure
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 323,
"s": 52,
"text": "Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below:"
},
{
"code": null,
"e": 340,
"s": 323,
"text": "Iterative Method"
},
{
"code": null,
"e": 426,
"s": 340,
"text": "The iterative method to do this is to write the document.write() statement 10 times. "
},
{
"code": null,
"e": 437,
"s": 426,
"text": "JavaScript"
},
{
"code": "<script type = \"text/javascript\">document.write(\"Hello World\\n\");document.write(\"Hello World\\n\");document.write(\"Hello World\\n\");document.write(\"Hello World\\n\");document.write(\"Hello World\\n\");document.write(\"Hello World\\n\");document.write(\"Hello World\\n\");document.write(\"Hello World\\n\");document.write(\"Hello World\\n\");document.write(\"Hello World\\n\");</script>",
"e": 800,
"s": 437,
"text": null
},
{
"code": null,
"e": 812,
"s": 800,
"text": "Using Loops"
},
{
"code": null,
"e": 921,
"s": 812,
"text": "In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below: "
},
{
"code": null,
"e": 932,
"s": 921,
"text": "JavaScript"
},
{
"code": "<script type = \"text/javascript\">var i; for (i = 0; i < 10; i++){ document.write(\"Hello World!\\n\");}</script>",
"e": 1045,
"s": 932,
"text": null
},
{
"code": null,
"e": 1608,
"s": 1045,
"text": "Many things may seem confusing to you in the above program at this point of time but do not worry you will be able to understand everything about loops in JavaScript by the end of this tutorial. You can observe that in the above program using loops we have used the document.write statement only once but still, the output of the program will be the same as that of the iterative program where we have used the document.write statement 10 times. In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached."
},
{
"code": null,
"e": 1773,
"s": 1608,
"text": "An operation is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number."
},
{
"code": null,
"e": 1947,
"s": 1773,
"text": "Counter not Reached: If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeats it."
},
{
"code": null,
"e": 2101,
"s": 1947,
"text": "Counter reached: If the condition has been reached, the next instruction “falls through” to the next sequential instruction or branches outside the loop."
},
{
"code": null,
"e": 2138,
"s": 2101,
"text": "There are mainly two types of loops:"
},
{
"code": null,
"e": 2575,
"s": 2138,
"text": "Entry Controlled loops: In these types of loops, the test condition is tested before entering the loop body. For Loops and While Loops are entry-controlled loops.Exit Controlled loops: In these types of loops the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. The do-while loop is exit controlled loop."
},
{
"code": null,
"e": 2738,
"s": 2575,
"text": "Entry Controlled loops: In these types of loops, the test condition is tested before entering the loop body. For Loops and While Loops are entry-controlled loops."
},
{
"code": null,
"e": 3013,
"s": 2738,
"text": "Exit Controlled loops: In these types of loops the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. The do-while loop is exit controlled loop."
},
{
"code": null,
"e": 3237,
"s": 3013,
"text": "JavaScript mainly provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time. Let us learn about each one of these in detail."
},
{
"code": null,
"e": 3440,
"s": 3237,
"text": "while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax :"
},
{
"code": null,
"e": 3643,
"s": 3440,
"text": "while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax :"
},
{
"code": null,
"e": 3695,
"s": 3643,
"text": "while (boolean condition)\n{\n loop statements...\n}"
},
{
"code": null,
"e": 4487,
"s": 3695,
"text": "Flowchart: While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the Entry control loopOnce the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.When the condition becomes false, the loop terminates which marks the end of its life cycle.for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Syntax:"
},
{
"code": null,
"e": 5021,
"s": 4487,
"text": "Flowchart: While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the Entry control loopOnce the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.When the condition becomes false, the loop terminates which marks the end of its life cycle."
},
{
"code": null,
"e": 5258,
"s": 5021,
"text": "While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the Entry control loop"
},
{
"code": null,
"e": 5453,
"s": 5258,
"text": "Once the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration."
},
{
"code": null,
"e": 5546,
"s": 5453,
"text": "When the condition becomes false, the loop terminates which marks the end of its life cycle."
},
{
"code": null,
"e": 5805,
"s": 5546,
"text": "for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Syntax:"
},
{
"code": null,
"e": 5928,
"s": 5805,
"text": "for (initialization condition; testing condition; \n increment/decrement)\n{\n statement(s)\n}"
},
{
"code": null,
"e": 6845,
"s": 5928,
"text": "Flowchart: Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.Increment/ Decrement: It is used for updating the variable for the next iteration.Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.do-while: do-while loop is similar to the while loop with the only difference that it checks for the condition after executing the statements, and therefore is an example of an Exit Control Loop. Syntax:"
},
{
"code": null,
"e": 7559,
"s": 6845,
"text": "Flowchart: Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.Increment/ Decrement: It is used for updating the variable for the next iteration.Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle."
},
{
"code": null,
"e": 8262,
"s": 7559,
"text": "Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.Increment/ Decrement: It is used for updating the variable for the next iteration.Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle."
},
{
"code": null,
"e": 8455,
"s": 8262,
"text": "Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only."
},
{
"code": null,
"e": 8668,
"s": 8455,
"text": "Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements."
},
{
"code": null,
"e": 8779,
"s": 8668,
"text": "Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed."
},
{
"code": null,
"e": 8862,
"s": 8779,
"text": "Increment/ Decrement: It is used for updating the variable for the next iteration."
},
{
"code": null,
"e": 8969,
"s": 8862,
"text": "Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle."
},
{
"code": null,
"e": 9173,
"s": 8969,
"text": "do-while: do-while loop is similar to the while loop with the only difference that it checks for the condition after executing the statements, and therefore is an example of an Exit Control Loop. Syntax:"
},
{
"code": null,
"e": 9216,
"s": 9173,
"text": "do\n{\n statements..\n}\nwhile (condition);"
},
{
"code": null,
"e": 9811,
"s": 9216,
"text": "Flowchart: The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.After the execution of the statements, and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.When the condition becomes false, the loop terminates which marks the end of its life cycle.It is important to note that the do-while loop will execute its statements at least once before any condition is checked, and therefore is an example of the exit control loop."
},
{
"code": null,
"e": 10406,
"s": 9811,
"text": "Flowchart: The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.After the execution of the statements, and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.When the condition becomes false, the loop terminates which marks the end of its life cycle.It is important to note that the do-while loop will execute its statements at least once before any condition is checked, and therefore is an example of the exit control loop."
},
{
"code": null,
"e": 10990,
"s": 10406,
"text": "The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.After the execution of the statements, and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.When the condition becomes false, the loop terminates which marks the end of its life cycle.It is important to note that the do-while loop will execute its statements at least once before any condition is checked, and therefore is an example of the exit control loop."
},
{
"code": null,
"e": 11113,
"s": 10990,
"text": "The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time."
},
{
"code": null,
"e": 11308,
"s": 11113,
"text": "After the execution of the statements, and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts."
},
{
"code": null,
"e": 11401,
"s": 11308,
"text": "When the condition becomes false, the loop terminates which marks the end of its life cycle."
},
{
"code": null,
"e": 11577,
"s": 11401,
"text": "It is important to note that the do-while loop will execute its statements at least once before any condition is checked, and therefore is an example of the exit control loop."
},
{
"code": null,
"e": 11591,
"s": 11577,
"text": "Infinite loop"
},
{
"code": null,
"e": 11800,
"s": 11591,
"text": "One of the most common mistakes while implementing any sort of looping is that it may not ever exit, that is the loop runs for infinite times. This happens when the condition fails for some reason. Examples: "
},
{
"code": null,
"e": 11811,
"s": 11800,
"text": "JavaScript"
},
{
"code": "<script type = \"text/javaScript\">// JavaScript program to illustrate infinite loop // infinite loop because condition is not apt // condition should have been i>0. for (var i = 5; i != 0; i -= 2) { document.write(i); } var x = 5; // infinite loop because update statement // is not provided. while (x == 5) { document.write(\"In the loop\"); } </script>",
"e": 12217,
"s": 11811,
"text": null
},
{
"code": null,
"e": 12232,
"s": 12217,
"text": "sagartomar9927"
},
{
"code": null,
"e": 12245,
"s": 12232,
"text": "technophpfij"
},
{
"code": null,
"e": 12256,
"s": 12245,
"text": "farzams101"
},
{
"code": null,
"e": 12274,
"s": 12256,
"text": "javascript-basics"
},
{
"code": null,
"e": 12290,
"s": 12274,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 12316,
"s": 12290,
"text": "Loops & Control Structure"
},
{
"code": null,
"e": 12327,
"s": 12316,
"text": "JavaScript"
}
] |
Output of Java program | Set 18 (Overriding)
|
03 Jun, 2017
Prerequisite – Overriding in Java
1) What is the output of the following program?
class Derived { protected final void getDetails() { System.out.println("Derived class"); }} public class Test extends Derived{ protected final void getDetails() { System.out.println("Test class"); } public static void main(String[] args) { Derived obj = new Derived(); obj.getDetails(); }}
a) Derived classb) Test classc) Runtime errord) Compilation error
Ans. (d)Explanation: Final and static methods cannot be overridden. For more details Check: Can we Overload or Override static methods in java ?
2) What is the output of the following program?
class Derived { public void getDetails(String temp) { System.out.println("Derived class " + temp); }} public class Test extends Derived{ public int getDetails(String temp) { System.out.println("Test class " + temp); return 0; } public static void main(String[] args) { Test obj = new Test(); obj.getDetails("GFG"); }}
a) Derived class GFGb) Test class GFGc) Compilation errord) Runtime error
Ans. (c)Explanation: The overriding method must have same signature, which includes, the argument list and the return type. For details, See : Overriding in Java
3) What is the output of the following program?
class Derived { public void getDetails() { System.out.println("Derived class"); }} public class Test extends Derived{ protected void getDetails() { System.out.println("Test class"); } public static void main(String[] args) { Derived obj = new Test(); // line xyz obj.getDetails(); }}
a) Test classb) Compilation error due to line xyzc) Derived classd) Compilation error due to access modifier
Ans: (d)Explanation: The overriding method can not have more restrictive access modifier.
4) What is the output of the following program?
import java.io.IOException; class Derived { public void getDetails() throws IOException //line 23 { System.out.println("Derived class"); }} public class Test extends Derived{ public void getDetails() throws Exception //line 24 { System.out.println("Test class"); } public static void main(String[] args) throws IOException //line 25 { Derived obj = new Test(); obj.getDetails(); }}
a) Compilation error due to line 23b) Compilation error due to line 24c) Compilation error due to line 25d) All the above
Ans. (b)Explanation: The exception thrown by the overriding method should not be new or more broader checked exception. In the code above, Exception is more broader class of checked exception than IOException, so this results in compilation error.
5) What is the output of the following program?
class Derived { public void getDetails() { System.out.printf("Derived class "); }} public class Test extends Derived{ public void getDetails() { System.out.printf("Test class "); super.getDetails(); } public static void main(String[] args) { Derived obj = new Test(); obj.getDetails(); }}
a) Test class Derived classb) Derived class Test classc) Compilation errord) Runtime error
Ans. (a)Explanation: super keyword is used to invoke the overridden method from a child class explicitly.
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jun, 2017"
},
{
"code": null,
"e": 86,
"s": 52,
"text": "Prerequisite – Overriding in Java"
},
{
"code": null,
"e": 134,
"s": 86,
"text": "1) What is the output of the following program?"
},
{
"code": "class Derived { protected final void getDetails() { System.out.println(\"Derived class\"); }} public class Test extends Derived{ protected final void getDetails() { System.out.println(\"Test class\"); } public static void main(String[] args) { Derived obj = new Derived(); obj.getDetails(); }}",
"e": 480,
"s": 134,
"text": null
},
{
"code": null,
"e": 546,
"s": 480,
"text": "a) Derived classb) Test classc) Runtime errord) Compilation error"
},
{
"code": null,
"e": 691,
"s": 546,
"text": "Ans. (d)Explanation: Final and static methods cannot be overridden. For more details Check: Can we Overload or Override static methods in java ?"
},
{
"code": null,
"e": 739,
"s": 691,
"text": "2) What is the output of the following program?"
},
{
"code": "class Derived { public void getDetails(String temp) { System.out.println(\"Derived class \" + temp); }} public class Test extends Derived{ public int getDetails(String temp) { System.out.println(\"Test class \" + temp); return 0; } public static void main(String[] args) { Test obj = new Test(); obj.getDetails(\"GFG\"); }}",
"e": 1120,
"s": 739,
"text": null
},
{
"code": null,
"e": 1194,
"s": 1120,
"text": "a) Derived class GFGb) Test class GFGc) Compilation errord) Runtime error"
},
{
"code": null,
"e": 1356,
"s": 1194,
"text": "Ans. (c)Explanation: The overriding method must have same signature, which includes, the argument list and the return type. For details, See : Overriding in Java"
},
{
"code": null,
"e": 1404,
"s": 1356,
"text": "3) What is the output of the following program?"
},
{
"code": "class Derived { public void getDetails() { System.out.println(\"Derived class\"); }} public class Test extends Derived{ protected void getDetails() { System.out.println(\"Test class\"); } public static void main(String[] args) { Derived obj = new Test(); // line xyz obj.getDetails(); }}",
"e": 1745,
"s": 1404,
"text": null
},
{
"code": null,
"e": 1854,
"s": 1745,
"text": "a) Test classb) Compilation error due to line xyzc) Derived classd) Compilation error due to access modifier"
},
{
"code": null,
"e": 1944,
"s": 1854,
"text": "Ans: (d)Explanation: The overriding method can not have more restrictive access modifier."
},
{
"code": null,
"e": 1992,
"s": 1944,
"text": "4) What is the output of the following program?"
},
{
"code": "import java.io.IOException; class Derived { public void getDetails() throws IOException //line 23 { System.out.println(\"Derived class\"); }} public class Test extends Derived{ public void getDetails() throws Exception //line 24 { System.out.println(\"Test class\"); } public static void main(String[] args) throws IOException //line 25 { Derived obj = new Test(); obj.getDetails(); }}",
"e": 2431,
"s": 1992,
"text": null
},
{
"code": null,
"e": 2553,
"s": 2431,
"text": "a) Compilation error due to line 23b) Compilation error due to line 24c) Compilation error due to line 25d) All the above"
},
{
"code": null,
"e": 2801,
"s": 2553,
"text": "Ans. (b)Explanation: The exception thrown by the overriding method should not be new or more broader checked exception. In the code above, Exception is more broader class of checked exception than IOException, so this results in compilation error."
},
{
"code": null,
"e": 2849,
"s": 2801,
"text": "5) What is the output of the following program?"
},
{
"code": "class Derived { public void getDetails() { System.out.printf(\"Derived class \"); }} public class Test extends Derived{ public void getDetails() { System.out.printf(\"Test class \"); super.getDetails(); } public static void main(String[] args) { Derived obj = new Test(); obj.getDetails(); }}",
"e": 3201,
"s": 2849,
"text": null
},
{
"code": null,
"e": 3292,
"s": 3201,
"text": "a) Test class Derived classb) Derived class Test classc) Compilation errord) Runtime error"
},
{
"code": null,
"e": 3398,
"s": 3292,
"text": "Ans. (a)Explanation: super keyword is used to invoke the overridden method from a child class explicitly."
},
{
"code": null,
"e": 3698,
"s": 3398,
"text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3823,
"s": 3698,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3835,
"s": 3823,
"text": "Java-Output"
},
{
"code": null,
"e": 3850,
"s": 3835,
"text": "Program Output"
}
] |
How to create Voronoi regions with Geospatial data in Python | by Abdishakur | Towards Data Science
|
Assume you are planning to walk to a station to pick up a scooter. There are numerous stations available in nearby. Which one should you go to pick up your scooter and ride?
The closest station, right!
But, how do you know the closest station from your place?
Enter Voronoi diagrams.
A Voronoi diagram is a collection of polygons with all the points on a plane that is closest to the single object.
In other words, each polygon division correlates with a single object and contains all points which are closest to this single object.
Applications of Voronoi diagrams are many and often include determining which feature is closest to any given point. For example, to determine which school is nearest at a given point in a neighbourhood. Or which cell tower is closest to my cell phone to make a phone call.
The famous John Snow’s cholera outbreak mapping in 1854 that killed 500 people in five days is said to have plotted water pumps data on a chart and effectively constructing a Voronoi diagram for inner Neighbourhoods in London.
We Can not list out all possible use case for Voronoi diagrams here. Still, its applications are far-reaching including Anthropology and Archeology, Statistics and Data Analysis, to Marketing and Meteorology. Here is a long list of some of its applications.
In this tutorial, we create a Voronoi diagram using preschools dataset. The dataset contains all preschools in Uppsala county, Sweden. To create Voronoi diagrams, we are going to use several libraries, including Geopandas and Geovoronoi.
Let us import the libraries and read the data first.
import numpy as npimport geopandas as gpdimport contextily as ctximport matplotlib.pyplot as pltfrom shapely.ops import cascaded_unionfrom geovoronoi.plotting import subplot_for_map, plot_voronoi_polys_with_points_in_areafrom geovoronoi import voronoi_regions_from_coords, points_to_coordsgdf = gpd.read_file("data/preschools.shp")gdf.head()
As shown here in the first few rows of the data, we have a geometry column with Points and some other attributes like the county, post address, etc..
We can plot the points data. Just to give some context, we also read the boundary of the county and plot the points on top of it.
boundary = gpd.read_file(“data/uppsala.shp”)fig, ax = plt.subplots(figsize=(12, 10))boundary.plot(ax=ax, color=”gray”)gdf.plot(ax=ax, markersize=3.5, color=”black”)ax.axis(“off”)plt.axis(‘equal’)plt.show()
The output is a map showing all preschools (black dots) in Uppsala county, Sweden.
Before we calculate the Voronoi regions, we need to make sure two things. First, we need to check the projection of the data and then convert it to Web Mercator projection (epsg=339599.
boundary = boundary.to_crs(epsg=3395)gdf_proj = gdf.to_crs(boundary.crs)
Second, we need to prepare the data to a format that Geovoronoi library can use. Here, we convert the boundary geometry into a union of the polygon. We also convert the Geopandas GeoSeries of Point objects to NumPy array of coordinates.
boundary_shape = cascaded_union(boundary.geometry)coords = points_to_coords(gdf_proj.geometry)
Calculate Voronoi Regions
Now, that we have prepared the data, we can calculate Voronoi regions simply using Geovoronoi’s method voronoi_regions_from_coords().
# Calculate Voronoi Regionspoly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords(coords, boundary_shape)
The output holds the shapes, the points and identification link between the two.
Plot Voronoi Diagram
To plot Voronoi Diagrams, we also use the functionality of Geovoronoi — plot_voronoi_polys_with_points_in_area(). Here, we provide all the output from the above Voronoi calculations and the boundary shape.
fig, ax = subplot_for_map()plot_voronoi_polys_with_points_in_area(ax, boundary_shape, poly_shapes, pts, poly_to_pt_assignments)ax.set_title('Voronoi regions of Schools in Uppsala')plt.tight_layout()plt.show()
The output is a Voronoi diagram which delineates school points into regions that are closest to each location.
The above map is small, but the good thing is that we can tweak it using the familiar Matplotlib interface. Let us first see the parameters and documentation for the plot_voronoi_polys_with_points_in_area() function.
plot_voronoi_polys_with_points_in_area( ax, area_shape, poly_shapes, points, poly_to_pt_assignments=None, area_color='white', area_edgecolor='black', voronoi_and_points_cmap='tab20', voronoi_color=None, voronoi_edgecolor=None, points_color=None, points_markersize=5, points_marker='o', voronoi_labels=None, voronoi_label_fontsize=10, voronoi_label_color=None, point_labels=None, point_label_fontsize=7, point_label_color=None, plot_area_opts=None, plot_voronoi_opts=None, plot_points_opts=None,)Docstring:All-in-one function to plot Voronoi region polygons `poly_shapes` and the respective points `points` inside ageographic area `area_shape` on a matplotlib Axes object `ax`. By default, the regions will be blue and the pointsblack. Optionally pass `poly_to_pt_assignments` to show Voronoi regions and their respective points with the samecolor (which is randomly drawn from color map `voronoi_and_points_cmap`). Labels for Voronoi regions can be passedas `voronoi_labels`. Labels for points can be passed as `point_labels`. Use style options to customize the plot.Pass additional (matplotlib) parameters to the individual plotting steps as `plot_area_opts`, `plot_voronoi_opts` or`plot_points_opts` respectively.
As you can see, there are a lot of parameters we can use to format the visualization. The documentation is also very clear and helpful.
We can increase the figure size and marker size of the points. We can also change the colour using Matplotlib Colormap. This is just one way, and there are other ways you can tweak which I leave it to you.
fig, ax = plt.subplots(figsize=(14,12))plot_voronoi_polys_with_points_in_area(ax, boundary_shape, poly_shapes, pts, poly_to_pt_assignments, voronoi_and_points_cmap=’tab20c’, points_markersize=20)ax.set_title(‘Upssalla Preschools — Voronoi Regions’)ax.axis(“off”)plt.tight_layout()plt.show()
The output map is much better now compared to the previous with the defaults.
Voronoi Diagrams are useful and are used widely in many Geographic applications. In this tutorial, we have covered how to create Voronoi diagrams using Python.
The code and the data for this article are available in this Github repository.
|
[
{
"code": null,
"e": 346,
"s": 172,
"text": "Assume you are planning to walk to a station to pick up a scooter. There are numerous stations available in nearby. Which one should you go to pick up your scooter and ride?"
},
{
"code": null,
"e": 374,
"s": 346,
"text": "The closest station, right!"
},
{
"code": null,
"e": 432,
"s": 374,
"text": "But, how do you know the closest station from your place?"
},
{
"code": null,
"e": 456,
"s": 432,
"text": "Enter Voronoi diagrams."
},
{
"code": null,
"e": 571,
"s": 456,
"text": "A Voronoi diagram is a collection of polygons with all the points on a plane that is closest to the single object."
},
{
"code": null,
"e": 706,
"s": 571,
"text": "In other words, each polygon division correlates with a single object and contains all points which are closest to this single object."
},
{
"code": null,
"e": 980,
"s": 706,
"text": "Applications of Voronoi diagrams are many and often include determining which feature is closest to any given point. For example, to determine which school is nearest at a given point in a neighbourhood. Or which cell tower is closest to my cell phone to make a phone call."
},
{
"code": null,
"e": 1207,
"s": 980,
"text": "The famous John Snow’s cholera outbreak mapping in 1854 that killed 500 people in five days is said to have plotted water pumps data on a chart and effectively constructing a Voronoi diagram for inner Neighbourhoods in London."
},
{
"code": null,
"e": 1465,
"s": 1207,
"text": "We Can not list out all possible use case for Voronoi diagrams here. Still, its applications are far-reaching including Anthropology and Archeology, Statistics and Data Analysis, to Marketing and Meteorology. Here is a long list of some of its applications."
},
{
"code": null,
"e": 1703,
"s": 1465,
"text": "In this tutorial, we create a Voronoi diagram using preschools dataset. The dataset contains all preschools in Uppsala county, Sweden. To create Voronoi diagrams, we are going to use several libraries, including Geopandas and Geovoronoi."
},
{
"code": null,
"e": 1756,
"s": 1703,
"text": "Let us import the libraries and read the data first."
},
{
"code": null,
"e": 2098,
"s": 1756,
"text": "import numpy as npimport geopandas as gpdimport contextily as ctximport matplotlib.pyplot as pltfrom shapely.ops import cascaded_unionfrom geovoronoi.plotting import subplot_for_map, plot_voronoi_polys_with_points_in_areafrom geovoronoi import voronoi_regions_from_coords, points_to_coordsgdf = gpd.read_file(\"data/preschools.shp\")gdf.head()"
},
{
"code": null,
"e": 2248,
"s": 2098,
"text": "As shown here in the first few rows of the data, we have a geometry column with Points and some other attributes like the county, post address, etc.."
},
{
"code": null,
"e": 2378,
"s": 2248,
"text": "We can plot the points data. Just to give some context, we also read the boundary of the county and plot the points on top of it."
},
{
"code": null,
"e": 2584,
"s": 2378,
"text": "boundary = gpd.read_file(“data/uppsala.shp”)fig, ax = plt.subplots(figsize=(12, 10))boundary.plot(ax=ax, color=”gray”)gdf.plot(ax=ax, markersize=3.5, color=”black”)ax.axis(“off”)plt.axis(‘equal’)plt.show()"
},
{
"code": null,
"e": 2667,
"s": 2584,
"text": "The output is a map showing all preschools (black dots) in Uppsala county, Sweden."
},
{
"code": null,
"e": 2853,
"s": 2667,
"text": "Before we calculate the Voronoi regions, we need to make sure two things. First, we need to check the projection of the data and then convert it to Web Mercator projection (epsg=339599."
},
{
"code": null,
"e": 2926,
"s": 2853,
"text": "boundary = boundary.to_crs(epsg=3395)gdf_proj = gdf.to_crs(boundary.crs)"
},
{
"code": null,
"e": 3163,
"s": 2926,
"text": "Second, we need to prepare the data to a format that Geovoronoi library can use. Here, we convert the boundary geometry into a union of the polygon. We also convert the Geopandas GeoSeries of Point objects to NumPy array of coordinates."
},
{
"code": null,
"e": 3258,
"s": 3163,
"text": "boundary_shape = cascaded_union(boundary.geometry)coords = points_to_coords(gdf_proj.geometry)"
},
{
"code": null,
"e": 3284,
"s": 3258,
"text": "Calculate Voronoi Regions"
},
{
"code": null,
"e": 3418,
"s": 3284,
"text": "Now, that we have prepared the data, we can calculate Voronoi regions simply using Geovoronoi’s method voronoi_regions_from_coords()."
},
{
"code": null,
"e": 3540,
"s": 3418,
"text": "# Calculate Voronoi Regionspoly_shapes, pts, poly_to_pt_assignments = voronoi_regions_from_coords(coords, boundary_shape)"
},
{
"code": null,
"e": 3621,
"s": 3540,
"text": "The output holds the shapes, the points and identification link between the two."
},
{
"code": null,
"e": 3642,
"s": 3621,
"text": "Plot Voronoi Diagram"
},
{
"code": null,
"e": 3848,
"s": 3642,
"text": "To plot Voronoi Diagrams, we also use the functionality of Geovoronoi — plot_voronoi_polys_with_points_in_area(). Here, we provide all the output from the above Voronoi calculations and the boundary shape."
},
{
"code": null,
"e": 4057,
"s": 3848,
"text": "fig, ax = subplot_for_map()plot_voronoi_polys_with_points_in_area(ax, boundary_shape, poly_shapes, pts, poly_to_pt_assignments)ax.set_title('Voronoi regions of Schools in Uppsala')plt.tight_layout()plt.show()"
},
{
"code": null,
"e": 4168,
"s": 4057,
"text": "The output is a Voronoi diagram which delineates school points into regions that are closest to each location."
},
{
"code": null,
"e": 4385,
"s": 4168,
"text": "The above map is small, but the good thing is that we can tweak it using the familiar Matplotlib interface. Let us first see the parameters and documentation for the plot_voronoi_polys_with_points_in_area() function."
},
{
"code": null,
"e": 5667,
"s": 4385,
"text": "plot_voronoi_polys_with_points_in_area( ax, area_shape, poly_shapes, points, poly_to_pt_assignments=None, area_color='white', area_edgecolor='black', voronoi_and_points_cmap='tab20', voronoi_color=None, voronoi_edgecolor=None, points_color=None, points_markersize=5, points_marker='o', voronoi_labels=None, voronoi_label_fontsize=10, voronoi_label_color=None, point_labels=None, point_label_fontsize=7, point_label_color=None, plot_area_opts=None, plot_voronoi_opts=None, plot_points_opts=None,)Docstring:All-in-one function to plot Voronoi region polygons `poly_shapes` and the respective points `points` inside ageographic area `area_shape` on a matplotlib Axes object `ax`. By default, the regions will be blue and the pointsblack. Optionally pass `poly_to_pt_assignments` to show Voronoi regions and their respective points with the samecolor (which is randomly drawn from color map `voronoi_and_points_cmap`). Labels for Voronoi regions can be passedas `voronoi_labels`. Labels for points can be passed as `point_labels`. Use style options to customize the plot.Pass additional (matplotlib) parameters to the individual plotting steps as `plot_area_opts`, `plot_voronoi_opts` or`plot_points_opts` respectively."
},
{
"code": null,
"e": 5803,
"s": 5667,
"text": "As you can see, there are a lot of parameters we can use to format the visualization. The documentation is also very clear and helpful."
},
{
"code": null,
"e": 6009,
"s": 5803,
"text": "We can increase the figure size and marker size of the points. We can also change the colour using Matplotlib Colormap. This is just one way, and there are other ways you can tweak which I leave it to you."
},
{
"code": null,
"e": 6300,
"s": 6009,
"text": "fig, ax = plt.subplots(figsize=(14,12))plot_voronoi_polys_with_points_in_area(ax, boundary_shape, poly_shapes, pts, poly_to_pt_assignments, voronoi_and_points_cmap=’tab20c’, points_markersize=20)ax.set_title(‘Upssalla Preschools — Voronoi Regions’)ax.axis(“off”)plt.tight_layout()plt.show()"
},
{
"code": null,
"e": 6378,
"s": 6300,
"text": "The output map is much better now compared to the previous with the defaults."
},
{
"code": null,
"e": 6538,
"s": 6378,
"text": "Voronoi Diagrams are useful and are used widely in many Geographic applications. In this tutorial, we have covered how to create Voronoi diagrams using Python."
}
] |
Rational UI Design with Streamlit | by Alan Jones | Towards Data Science
|
When Tim Berners-Lee first invented the web, pages were just text. When the first graphical browsers like Mosaic came along web pages got pictures, too.
Later they became apps with server-side programs supplying the data to construct the web pages. This often entailed writing code in the within the HTML in PHP, or Java or Visual Basic, which the server executed in order to construct the page.
The result was often a real dog’s dinner — the code scattered throughout the HTML wasn’t clear because it was fragmented and, on top of that, it also obscured the page layout.
Those who thought deeply about these things suggested that we should separate the logic of an app from the way it was presented. One idea was the Model, View, Controller method (MVC). Here the Model was the app logic, typically some data and program code on a server; the View was how the web page should look, HTML and CSS in the browser; and the Controller was the code that connected the Model to the View, getting user input from the web page, supplying it to the Model and getting results back to display in the View.
And if that sounds complicated... well, what can I say - yes, it is a bit complicated.
Complicated because while the idea of MVC is simple enough, the technologies and techniques required mean that a whole bunch of skills are needed. For the View, HTML and CSS; for the Model, a language like Python, Java or C# (and probably some SQL, too); and for the Controller, probably Javascript, a knowledge of HTTP and, these days, Ajax, too.
Maybe you’ve never heard of MVC but many web app frameworks were (indeed, are) based on the idea.
So Streamlit is going backwards by mixing the code and the layout in a single entity. But, while that is true, it is also attempting to make life easier because all of those technologies I mentioned above are no longer necessary — all you need is Python and the Streamlit library.
So, how do we get the benefit of the simple Pythonic approach without getting mired in the complications of mixing app logic and page design?
The solution is to keep the MVC approach in mind and separate the program logic from the way it is presented.
Both Python and Streamlit can help us.
We can modularise the app using Python classes and functions, separating the View from the Model, and we can structure the View using Streamlit functions. (Streamlit has a nice recent addition: you can use the with statement with containers objects like st.container or st.columns and this allows you to show the structure of the page.)
The Controller part of MVC is taken care of by Streamlit and is incorporated into the View.
Let me show you what I mean.
Here is a simple template from which we can construct a MVC-style app in Streamlit.
############################################### A simple model/view template for Streamlit ###############################################import streamlit as st################ Model ################class Model: caption = "This is some text"################ View ################def view(model): st.write(model.caption)################ Start ################view(Model())
As you can see there are four sections: the imports, a class called Model, a function called view and the final line which calls the view function with an instantiation of Model as a parameter.
This is as simple as it can get. The Model class has a single attribute, caption, and the view function uses this to write to the screen.
For clarity, the last line is the equivalent of creating an object of type Model and passing it to the view function. Something like this:
m = Model()view(m)
Now let’s imagine we want to design a simple app that looks like the image at the top of this article. It’s what has become a classic illustration of how GDP per Capita relates to life expectancy and is based on the work of the late Hans Rosling from Gapminder (and if you don’t know about Gapminder or Hans Rosling, be sure to follow the link).
The layout of the app looks like this:
This is the basis of our View: a header, below which are two columns; the right hand column contains the chart that we want to display; the left hand column contains some text that describes the page and, below that, a slider that allows the user to select a year to be displayed on the chart.
Here is a sort of pseudo code of what the Streamlit View would look like
# Headerst.header(caption)# Two columns: # 1. Commentary and slider# 2. Main chartcommentaryCol, chartCol = st.columns(dimensions)with commentaryCol: # Show commentary text # Show year Sliderwith chartCol: # Display Main Chart
You can see, I hope that the code will mirror the layout diagram — we just need to fill in the detailed code.
Before we do that though we also need to consider what data the View requires. And that is four things: the caption for the header, the commentary text, the parameters that the slider will require and, finally, the chart to be displayed.This data will be provided by the Model.
Let’s start looking at the code.
The imports are as follows:
import streamlit as stimport pandas as pdimport plotly.express as px
We need Streamlit (of course), Pandas to hold the Gapminder data, and Plotly to draw the chart.
The model should come next in the program file but we are going to park that for now and look at how we develop the View.
The View is a function called view which contains all of the Streamlit code to create the web page. We pass a instance of the model to it and all of the data that Streamlit needs will come from there. So, for example, the header caption is held in the Model in an attribute called header, thus the Streamlit code to write the header will be st.header(model.header).
Here is the complete code which is a development of the pseudo code that we saw earlier.
################ View ################def view(model): st.set_page_config(layout = 'wide') # Header st.header(model.header) commentaryCol, spaceCol, chartCol=st.columns((2,1,6)) # Description with commentaryCol: st.write(model.description) # Year Slider year=st.slider(model.sliderCaption, model.yearStart, model.yearEnd, model.yearStart, model.yearStep) #Chart with chartCol: st.plotly_chart(model.chart(year), use_container_width = True)
Notice that I am using the with statement to show which UI element the following code is for. This is a nice touch that was included in a recent release of the Streamlit library and makes the code easier to read.
The first thing in the code is to set the page layout to wide. This is not essential but I think the end result looks better.
Next follows the main elements:
the header: this just displays model.header at the top of the page
a set of columns: there are three, the right-hand to hold the chart, the left-hand one to hold the description and the slider and one in between which just puts a bit of space between the other two.
the description goes in commentaryCol and just writes out model.description
the slider that we will use to select the year also goes in commentaryColbelow the description. The slider requires 5 parameters, a caption, start and end points, the initial value and a step. These are provided by the model attributes as shown in the code.
the chart goes in chartCol and is a call to st.plotly_chart. The actual chart to be displayed is returned from a method in model called chart. This method needs the year to be passed as a parameter.
The final code is the same as we saw earlier: it calls view with an instantiation of Model as a parameter.
################ Start ################view(Model())
In the Model we need to provide all of the data that the view requires. Much of that is done in the constructor method __init__. This method is called when an object is created from Model. The first thing to do is to load the Gapminder data into a Pandas Dataframe — the Gapminder data is included in the Plotly library and so we are using this; in a real app this data would likely be loaded from a database or from an API.
From the Gapminder data we set a number of attributes, a list of unique years (which we convert from their original Numpy types to plain old Python int which Streamlit seems to prefer).
We then set the start, end and step values that the slider will use.
Next comes the chart method which draws a Plotly scatter chart.
Lastly, we set attributes for the various string that the View will use.
################ Model ################class Model: def __init__(self): self.df = pd.DataFrame(px.data.gapminder()) self.ylist = [int(i) for i in self.df['year'].unique()] self.yearStart = self.ylist[0] self.yearEnd = self.ylist[-1] self.yearStep = self.ylist[1]-self.ylist[0] def chart(self,year): return px.scatter(self.df[self.df['year'] == year], x = 'lifeExp', y = 'gdpPercap', title = f'Year: {year}', color='continent',size='pop') header = 'Global Statistics from Gapminder' description =''' See how life expectancy changes over time and in relation to GDP. Move the slider to change the year to display. ''' sliderCaption='Select the year for the chart'
If you now put those sections of code together in the right order, you will have a complete Streamlit app.
We now have an app with a separate View and Model. If we wanted to change the way the app looked then there should be no need to touch the model code, at all, only the view function.
This makes updating and maintaining the code easier and also makes the code easier to read and understand. And if, for some reason, we decide that we want to get our data from elsewhere, it is only the Model code that needs to be changed not the view.
This is a fairly trivial example but I hope that you can see that this rational approach would scale up to more complex apps and make them easier to write and maintain.
I have one doubt about the example that I have given: should the values that the slider need be calculated in the View or, where I’ve put them. in the Model? The way I’ve done it makes for a cleaner View but there is an argument that those values are only calculated because of the way we use the slider, so it might be more appropriate to derive them there.
I’d be very happy to hear how you feel about this approach, so please feel free to comment below.
As ever thanks for reading and if you would like to know when I publish new articles, please consider signing up for an email alert here.
The code for this article is easily cut and pasted from here but is also available on my GitHub page. A demonstrator page is also available here — select Rational UI Design from the drop down menu.
If you are not a Medium subscriber, how about signing up so you can read as many articles as you like for $5 a month. Sign up here and I’ll earn a small commission.
|
[
{
"code": null,
"e": 325,
"s": 172,
"text": "When Tim Berners-Lee first invented the web, pages were just text. When the first graphical browsers like Mosaic came along web pages got pictures, too."
},
{
"code": null,
"e": 568,
"s": 325,
"text": "Later they became apps with server-side programs supplying the data to construct the web pages. This often entailed writing code in the within the HTML in PHP, or Java or Visual Basic, which the server executed in order to construct the page."
},
{
"code": null,
"e": 744,
"s": 568,
"text": "The result was often a real dog’s dinner — the code scattered throughout the HTML wasn’t clear because it was fragmented and, on top of that, it also obscured the page layout."
},
{
"code": null,
"e": 1267,
"s": 744,
"text": "Those who thought deeply about these things suggested that we should separate the logic of an app from the way it was presented. One idea was the Model, View, Controller method (MVC). Here the Model was the app logic, typically some data and program code on a server; the View was how the web page should look, HTML and CSS in the browser; and the Controller was the code that connected the Model to the View, getting user input from the web page, supplying it to the Model and getting results back to display in the View."
},
{
"code": null,
"e": 1354,
"s": 1267,
"text": "And if that sounds complicated... well, what can I say - yes, it is a bit complicated."
},
{
"code": null,
"e": 1702,
"s": 1354,
"text": "Complicated because while the idea of MVC is simple enough, the technologies and techniques required mean that a whole bunch of skills are needed. For the View, HTML and CSS; for the Model, a language like Python, Java or C# (and probably some SQL, too); and for the Controller, probably Javascript, a knowledge of HTTP and, these days, Ajax, too."
},
{
"code": null,
"e": 1800,
"s": 1702,
"text": "Maybe you’ve never heard of MVC but many web app frameworks were (indeed, are) based on the idea."
},
{
"code": null,
"e": 2081,
"s": 1800,
"text": "So Streamlit is going backwards by mixing the code and the layout in a single entity. But, while that is true, it is also attempting to make life easier because all of those technologies I mentioned above are no longer necessary — all you need is Python and the Streamlit library."
},
{
"code": null,
"e": 2223,
"s": 2081,
"text": "So, how do we get the benefit of the simple Pythonic approach without getting mired in the complications of mixing app logic and page design?"
},
{
"code": null,
"e": 2333,
"s": 2223,
"text": "The solution is to keep the MVC approach in mind and separate the program logic from the way it is presented."
},
{
"code": null,
"e": 2372,
"s": 2333,
"text": "Both Python and Streamlit can help us."
},
{
"code": null,
"e": 2709,
"s": 2372,
"text": "We can modularise the app using Python classes and functions, separating the View from the Model, and we can structure the View using Streamlit functions. (Streamlit has a nice recent addition: you can use the with statement with containers objects like st.container or st.columns and this allows you to show the structure of the page.)"
},
{
"code": null,
"e": 2801,
"s": 2709,
"text": "The Controller part of MVC is taken care of by Streamlit and is incorporated into the View."
},
{
"code": null,
"e": 2830,
"s": 2801,
"text": "Let me show you what I mean."
},
{
"code": null,
"e": 2914,
"s": 2830,
"text": "Here is a simple template from which we can construct a MVC-style app in Streamlit."
},
{
"code": null,
"e": 3292,
"s": 2914,
"text": "############################################### A simple model/view template for Streamlit ###############################################import streamlit as st################ Model ################class Model: caption = \"This is some text\"################ View ################def view(model): st.write(model.caption)################ Start ################view(Model())"
},
{
"code": null,
"e": 3486,
"s": 3292,
"text": "As you can see there are four sections: the imports, a class called Model, a function called view and the final line which calls the view function with an instantiation of Model as a parameter."
},
{
"code": null,
"e": 3624,
"s": 3486,
"text": "This is as simple as it can get. The Model class has a single attribute, caption, and the view function uses this to write to the screen."
},
{
"code": null,
"e": 3763,
"s": 3624,
"text": "For clarity, the last line is the equivalent of creating an object of type Model and passing it to the view function. Something like this:"
},
{
"code": null,
"e": 3782,
"s": 3763,
"text": "m = Model()view(m)"
},
{
"code": null,
"e": 4128,
"s": 3782,
"text": "Now let’s imagine we want to design a simple app that looks like the image at the top of this article. It’s what has become a classic illustration of how GDP per Capita relates to life expectancy and is based on the work of the late Hans Rosling from Gapminder (and if you don’t know about Gapminder or Hans Rosling, be sure to follow the link)."
},
{
"code": null,
"e": 4167,
"s": 4128,
"text": "The layout of the app looks like this:"
},
{
"code": null,
"e": 4461,
"s": 4167,
"text": "This is the basis of our View: a header, below which are two columns; the right hand column contains the chart that we want to display; the left hand column contains some text that describes the page and, below that, a slider that allows the user to select a year to be displayed on the chart."
},
{
"code": null,
"e": 4534,
"s": 4461,
"text": "Here is a sort of pseudo code of what the Streamlit View would look like"
},
{
"code": null,
"e": 4771,
"s": 4534,
"text": "# Headerst.header(caption)# Two columns: # 1. Commentary and slider# 2. Main chartcommentaryCol, chartCol = st.columns(dimensions)with commentaryCol: # Show commentary text # Show year Sliderwith chartCol: # Display Main Chart"
},
{
"code": null,
"e": 4881,
"s": 4771,
"text": "You can see, I hope that the code will mirror the layout diagram — we just need to fill in the detailed code."
},
{
"code": null,
"e": 5159,
"s": 4881,
"text": "Before we do that though we also need to consider what data the View requires. And that is four things: the caption for the header, the commentary text, the parameters that the slider will require and, finally, the chart to be displayed.This data will be provided by the Model."
},
{
"code": null,
"e": 5192,
"s": 5159,
"text": "Let’s start looking at the code."
},
{
"code": null,
"e": 5220,
"s": 5192,
"text": "The imports are as follows:"
},
{
"code": null,
"e": 5289,
"s": 5220,
"text": "import streamlit as stimport pandas as pdimport plotly.express as px"
},
{
"code": null,
"e": 5385,
"s": 5289,
"text": "We need Streamlit (of course), Pandas to hold the Gapminder data, and Plotly to draw the chart."
},
{
"code": null,
"e": 5507,
"s": 5385,
"text": "The model should come next in the program file but we are going to park that for now and look at how we develop the View."
},
{
"code": null,
"e": 5873,
"s": 5507,
"text": "The View is a function called view which contains all of the Streamlit code to create the web page. We pass a instance of the model to it and all of the data that Streamlit needs will come from there. So, for example, the header caption is held in the Model in an attribute called header, thus the Streamlit code to write the header will be st.header(model.header)."
},
{
"code": null,
"e": 5962,
"s": 5873,
"text": "Here is the complete code which is a development of the pseudo code that we saw earlier."
},
{
"code": null,
"e": 6457,
"s": 5962,
"text": "################ View ################def view(model): st.set_page_config(layout = 'wide') # Header st.header(model.header) commentaryCol, spaceCol, chartCol=st.columns((2,1,6)) # Description with commentaryCol: st.write(model.description) # Year Slider year=st.slider(model.sliderCaption, model.yearStart, model.yearEnd, model.yearStart, model.yearStep) #Chart with chartCol: st.plotly_chart(model.chart(year), use_container_width = True)"
},
{
"code": null,
"e": 6670,
"s": 6457,
"text": "Notice that I am using the with statement to show which UI element the following code is for. This is a nice touch that was included in a recent release of the Streamlit library and makes the code easier to read."
},
{
"code": null,
"e": 6796,
"s": 6670,
"text": "The first thing in the code is to set the page layout to wide. This is not essential but I think the end result looks better."
},
{
"code": null,
"e": 6828,
"s": 6796,
"text": "Next follows the main elements:"
},
{
"code": null,
"e": 6895,
"s": 6828,
"text": "the header: this just displays model.header at the top of the page"
},
{
"code": null,
"e": 7094,
"s": 6895,
"text": "a set of columns: there are three, the right-hand to hold the chart, the left-hand one to hold the description and the slider and one in between which just puts a bit of space between the other two."
},
{
"code": null,
"e": 7170,
"s": 7094,
"text": "the description goes in commentaryCol and just writes out model.description"
},
{
"code": null,
"e": 7428,
"s": 7170,
"text": "the slider that we will use to select the year also goes in commentaryColbelow the description. The slider requires 5 parameters, a caption, start and end points, the initial value and a step. These are provided by the model attributes as shown in the code."
},
{
"code": null,
"e": 7627,
"s": 7428,
"text": "the chart goes in chartCol and is a call to st.plotly_chart. The actual chart to be displayed is returned from a method in model called chart. This method needs the year to be passed as a parameter."
},
{
"code": null,
"e": 7734,
"s": 7627,
"text": "The final code is the same as we saw earlier: it calls view with an instantiation of Model as a parameter."
},
{
"code": null,
"e": 7788,
"s": 7734,
"text": "################ Start ################view(Model())"
},
{
"code": null,
"e": 8213,
"s": 7788,
"text": "In the Model we need to provide all of the data that the view requires. Much of that is done in the constructor method __init__. This method is called when an object is created from Model. The first thing to do is to load the Gapminder data into a Pandas Dataframe — the Gapminder data is included in the Plotly library and so we are using this; in a real app this data would likely be loaded from a database or from an API."
},
{
"code": null,
"e": 8399,
"s": 8213,
"text": "From the Gapminder data we set a number of attributes, a list of unique years (which we convert from their original Numpy types to plain old Python int which Streamlit seems to prefer)."
},
{
"code": null,
"e": 8468,
"s": 8399,
"text": "We then set the start, end and step values that the slider will use."
},
{
"code": null,
"e": 8532,
"s": 8468,
"text": "Next comes the chart method which draws a Plotly scatter chart."
},
{
"code": null,
"e": 8605,
"s": 8532,
"text": "Lastly, we set attributes for the various string that the View will use."
},
{
"code": null,
"e": 9350,
"s": 8605,
"text": "################ Model ################class Model: def __init__(self): self.df = pd.DataFrame(px.data.gapminder()) self.ylist = [int(i) for i in self.df['year'].unique()] self.yearStart = self.ylist[0] self.yearEnd = self.ylist[-1] self.yearStep = self.ylist[1]-self.ylist[0] def chart(self,year): return px.scatter(self.df[self.df['year'] == year], x = 'lifeExp', y = 'gdpPercap', title = f'Year: {year}', color='continent',size='pop') header = 'Global Statistics from Gapminder' description =''' See how life expectancy changes over time and in relation to GDP. Move the slider to change the year to display. ''' sliderCaption='Select the year for the chart'"
},
{
"code": null,
"e": 9457,
"s": 9350,
"text": "If you now put those sections of code together in the right order, you will have a complete Streamlit app."
},
{
"code": null,
"e": 9640,
"s": 9457,
"text": "We now have an app with a separate View and Model. If we wanted to change the way the app looked then there should be no need to touch the model code, at all, only the view function."
},
{
"code": null,
"e": 9892,
"s": 9640,
"text": "This makes updating and maintaining the code easier and also makes the code easier to read and understand. And if, for some reason, we decide that we want to get our data from elsewhere, it is only the Model code that needs to be changed not the view."
},
{
"code": null,
"e": 10061,
"s": 9892,
"text": "This is a fairly trivial example but I hope that you can see that this rational approach would scale up to more complex apps and make them easier to write and maintain."
},
{
"code": null,
"e": 10420,
"s": 10061,
"text": "I have one doubt about the example that I have given: should the values that the slider need be calculated in the View or, where I’ve put them. in the Model? The way I’ve done it makes for a cleaner View but there is an argument that those values are only calculated because of the way we use the slider, so it might be more appropriate to derive them there."
},
{
"code": null,
"e": 10518,
"s": 10420,
"text": "I’d be very happy to hear how you feel about this approach, so please feel free to comment below."
},
{
"code": null,
"e": 10656,
"s": 10518,
"text": "As ever thanks for reading and if you would like to know when I publish new articles, please consider signing up for an email alert here."
},
{
"code": null,
"e": 10854,
"s": 10656,
"text": "The code for this article is easily cut and pasted from here but is also available on my GitHub page. A demonstrator page is also available here — select Rational UI Design from the drop down menu."
}
] |
send() - Unix, Linux System Call
|
Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
ssize_t send(int s, const void *buf, size_t len, int flags);
ssize_t sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen);
ssize_t sendmsg(int s, const struct msghdr *msg, int flags);
The
send() call may be used only when the socket is in a
connected state (so that the intended recipient is known).
The only difference between
send() and
write() is the presence of
flags. With zero
flags parameter,
send() is equivalent to
write(). Also,
send(s,buf,len,flags) is equivalent to
sendto(s,buf,len,flags,NULL,0).
The parameter
s is the file descriptor of the sending socket.
If
sendto() is used on a connection-mode (SOCK_STREAM, SOCK_SEQPACKET) socket,
the parameters
to and
tolen are ignored (and the error EISCONN may be returned when they are
not NULL and 0), and the error ENOTCONN is returned when the socket was
not actually connected. Otherwise, the address of the target is given by
to with
tolen specifying its size.
For
sendmsg(), the address of the target is given by
msg.msg_name, with
msg.msg_namelen specifying its size.
For
send() and
sendto(), the message is found in
buf and has length
len. For
sendmsg(), the message is pointed to by the elements of the array
msg.msg_iov. The
sendmsg() call also allows sending ancillary data (also known as control information).
If the message is too long to pass atomically through the
underlying protocol, the error
EMSGSIZE is returned, and the message is not transmitted.
No indication of failure to deliver is implicit in a
send(). Locally detected errors are indicated by a return value of -1.
When the message does not fit into the send buffer of the socket,
send() normally blocks, unless the socket has been placed in non-blocking I/O
mode. In non-blocking mode it would return
EAGAIN in this case.
The
select(2)
call may be used to determine when it is possible to send more data.
The
flags parameter is the bitwise OR
of zero or more of the following flags.
Since Linux 2.6, this flag is also supported for UDP sockets, and informs
the kernel to package all of the data sent in calls with this flag set
into a single datagram which is only transmitted when a call is performed
that does not specify this flag.
(See also the
UDP_CORK socket option described in
udp(7).)
struct msghdr {
void *msg_name; /* optional address */
socklen_t msg_namelen; /* size of address */
struct iovec *msg_iov; /* scatter/gather array */
size_t msg_iovlen; /* # elements in msg_iov */
void *msg_control; /* ancillary data, see below */
socklen_t msg_controllen; /* ancillary data buffer len */
int msg_flags; /* flags on received message */
};
struct msghdr {
void *msg_name; /* optional address */
socklen_t msg_namelen; /* size of address */
struct iovec *msg_iov; /* scatter/gather array */
size_t msg_iovlen; /* # elements in msg_iov */
void *msg_control; /* ancillary data, see below */
socklen_t msg_controllen; /* ancillary data buffer len */
int msg_flags; /* flags on received message */
};
You may send control information using the
msg_control and
msg_controllen members. The maximum control buffer length the kernel can process is limited
per socket by the
net.core.optmem_max sysctl; see
socket(7).
POSIX.1-2001 only describes the
MSG_OOB and
MSG_EOR flags.
The
MSG_CONFIRM flag is a Linux extension.
According to POSIX.1-2001, the
msg_controllen field of the
msghdr structure should be typed as
socklen_t, but glibc currently (2.4) types it as
size_t.
fcntl (2)
fcntl (2)
getsockopt (2)
getsockopt (2)
recv (2)
recv (2)
select (2)
select (2)
sendfile (2)
sendfile (2)
shutdown (2)
shutdown (2)
socket (2)
socket (2)
write (2)
write (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2552,
"s": 2319,
"text": "\nssize_t send(int s, const void *buf, size_t len, int flags); \nssize_t sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); \nssize_t sendmsg(int s, const struct msghdr *msg, int flags); "
},
{
"code": null,
"e": 2880,
"s": 2552,
"text": "\nThe\nsend() call may be used only when the socket is in a\nconnected state (so that the intended recipient is known).\nThe only difference between\nsend() and\nwrite() is the presence of\nflags. With zero\nflags parameter,\nsend() is equivalent to\nwrite(). Also,\nsend(s,buf,len,flags) is equivalent to\nsendto(s,buf,len,flags,NULL,0). "
},
{
"code": null,
"e": 2944,
"s": 2880,
"text": "\nThe parameter\ns is the file descriptor of the sending socket.\n"
},
{
"code": null,
"e": 3407,
"s": 2944,
"text": "\nIf\nsendto() is used on a connection-mode (SOCK_STREAM, SOCK_SEQPACKET) socket,\nthe parameters\nto and\ntolen are ignored (and the error EISCONN may be returned when they are\nnot NULL and 0), and the error ENOTCONN is returned when the socket was\nnot actually connected. Otherwise, the address of the target is given by\nto with\ntolen specifying its size.\nFor\nsendmsg(), the address of the target is given by\nmsg.msg_name, with\nmsg.msg_namelen specifying its size.\n"
},
{
"code": null,
"e": 3656,
"s": 3407,
"text": "\nFor\nsend() and\nsendto(), the message is found in\nbuf and has length\nlen. For\nsendmsg(), the message is pointed to by the elements of the array\nmsg.msg_iov. The\nsendmsg() call also allows sending ancillary data (also known as control information).\n"
},
{
"code": null,
"e": 3805,
"s": 3656,
"text": "\nIf the message is too long to pass atomically through the\nunderlying protocol, the error\nEMSGSIZE is returned, and the message is not transmitted.\n"
},
{
"code": null,
"e": 3931,
"s": 3805,
"text": "\nNo indication of failure to deliver is implicit in a\nsend(). Locally detected errors are indicated by a return value of -1.\n"
},
{
"code": null,
"e": 4225,
"s": 3931,
"text": "\nWhen the message does not fit into the send buffer of the socket,\nsend() normally blocks, unless the socket has been placed in non-blocking I/O\nmode. In non-blocking mode it would return\nEAGAIN in this case.\nThe\nselect(2)\ncall may be used to determine when it is possible to send more data.\n"
},
{
"code": null,
"e": 4305,
"s": 4225,
"text": "\nThe\nflags parameter is the bitwise OR\nof zero or more of the following flags.\n"
},
{
"code": null,
"e": 4619,
"s": 4305,
"text": "\nSince Linux 2.6, this flag is also supported for UDP sockets, and informs\nthe kernel to package all of the data sent in calls with this flag set\ninto a single datagram which is only transmitted when a call is performed\nthat does not specify this flag. \n(See also the\nUDP_CORK socket option described in\nudp(7).)\n"
},
{
"code": null,
"e": 5074,
"s": 4619,
"text": "\nstruct msghdr {\n void *msg_name; /* optional address */\n socklen_t msg_namelen; /* size of address */\n struct iovec *msg_iov; /* scatter/gather array */\n size_t msg_iovlen; /* # elements in msg_iov */\n void *msg_control; /* ancillary data, see below */\n socklen_t msg_controllen; /* ancillary data buffer len */\n int msg_flags; /* flags on received message */\n};\n"
},
{
"code": null,
"e": 5529,
"s": 5074,
"text": "\nstruct msghdr {\n void *msg_name; /* optional address */\n socklen_t msg_namelen; /* size of address */\n struct iovec *msg_iov; /* scatter/gather array */\n size_t msg_iovlen; /* # elements in msg_iov */\n void *msg_control; /* ancillary data, see below */\n socklen_t msg_controllen; /* ancillary data buffer len */\n int msg_flags; /* flags on received message */\n};\n"
},
{
"code": null,
"e": 5743,
"s": 5529,
"text": "\nYou may send control information using the\nmsg_control and\nmsg_controllen members. The maximum control buffer length the kernel can process is limited\nper socket by the\nnet.core.optmem_max sysctl; see\nsocket(7).\n"
},
{
"code": null,
"e": 5847,
"s": 5743,
"text": "\nPOSIX.1-2001 only describes the\nMSG_OOB and\nMSG_EOR flags.\nThe\nMSG_CONFIRM flag is a Linux extension.\n"
},
{
"code": null,
"e": 6001,
"s": 5847,
"text": "\nAccording to POSIX.1-2001, the\nmsg_controllen field of the\nmsghdr structure should be typed as\nsocklen_t, but glibc currently (2.4) types it as\nsize_t. "
},
{
"code": null,
"e": 6011,
"s": 6001,
"text": "fcntl (2)"
},
{
"code": null,
"e": 6021,
"s": 6011,
"text": "fcntl (2)"
},
{
"code": null,
"e": 6036,
"s": 6021,
"text": "getsockopt (2)"
},
{
"code": null,
"e": 6051,
"s": 6036,
"text": "getsockopt (2)"
},
{
"code": null,
"e": 6060,
"s": 6051,
"text": "recv (2)"
},
{
"code": null,
"e": 6069,
"s": 6060,
"text": "recv (2)"
},
{
"code": null,
"e": 6080,
"s": 6069,
"text": "select (2)"
},
{
"code": null,
"e": 6091,
"s": 6080,
"text": "select (2)"
},
{
"code": null,
"e": 6104,
"s": 6091,
"text": "sendfile (2)"
},
{
"code": null,
"e": 6117,
"s": 6104,
"text": "sendfile (2)"
},
{
"code": null,
"e": 6130,
"s": 6117,
"text": "shutdown (2)"
},
{
"code": null,
"e": 6143,
"s": 6130,
"text": "shutdown (2)"
},
{
"code": null,
"e": 6154,
"s": 6143,
"text": "socket (2)"
},
{
"code": null,
"e": 6165,
"s": 6154,
"text": "socket (2)"
},
{
"code": null,
"e": 6175,
"s": 6165,
"text": "write (2)"
},
{
"code": null,
"e": 6185,
"s": 6175,
"text": "write (2)"
},
{
"code": null,
"e": 6202,
"s": 6185,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 6237,
"s": 6202,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 6265,
"s": 6237,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6299,
"s": 6265,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6316,
"s": 6299,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6349,
"s": 6316,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6360,
"s": 6349,
"text": " Pradeep D"
},
{
"code": null,
"e": 6395,
"s": 6360,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6411,
"s": 6395,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 6444,
"s": 6411,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6456,
"s": 6444,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 6488,
"s": 6456,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6496,
"s": 6488,
"text": " Uplatz"
},
{
"code": null,
"e": 6503,
"s": 6496,
"text": " Print"
},
{
"code": null,
"e": 6514,
"s": 6503,
"text": " Add Notes"
}
] |
VBScript Exit For statement
|
A Exit For Statement is used when we want to Exit the For Loop based on certain criteria. When Exit For is executed, the control jumps to next statement immediately after the For Loop.
The syntax for Exit For Statement in VBScript is −
Exit For
The below example uses Exit For. If the value of the Counter reaches 4, the For Loop is Exited and control jumps to the next statement immediately after the For Loop.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a : a = 10
For i = 0 to a Step 2 'i is the counter variable and it is incremented by 2
document.write("The value is i is : " & i)
document.write("<br></br>")
If i = 4 Then
i = i*10 'This is executed only if i = 4
document.write("The value is i is : " & i)
Exit For 'Exited when i = 4
End If
Next
</script>
</body>
</html>
When the above code is executed, it prints the following output in the console.
The value is i is : 0
The value is i is : 2
The value is i is : 4
The value is i is : 40
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2265,
"s": 2080,
"text": "A Exit For Statement is used when we want to Exit the For Loop based on certain criteria. When Exit For is executed, the control jumps to next statement immediately after the For Loop."
},
{
"code": null,
"e": 2316,
"s": 2265,
"text": "The syntax for Exit For Statement in VBScript is −"
},
{
"code": null,
"e": 2327,
"s": 2316,
"text": " Exit For\n"
},
{
"code": null,
"e": 2494,
"s": 2327,
"text": "The below example uses Exit For. If the value of the Counter reaches 4, the For Loop is Exited and control jumps to the next statement immediately after the For Loop."
},
{
"code": null,
"e": 3050,
"s": 2494,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim a : a = 10\n For i = 0 to a Step 2 'i is the counter variable and it is incremented by 2\n document.write(\"The value is i is : \" & i)\n document.write(\"<br></br>\")\n \n If i = 4 Then\n i = i*10 'This is executed only if i = 4\n document.write(\"The value is i is : \" & i)\n Exit For 'Exited when i = 4\n End If\t \n Next\n \n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3130,
"s": 3050,
"text": "When the above code is executed, it prints the following output in the console."
},
{
"code": null,
"e": 3224,
"s": 3130,
"text": "The value is i is : 0\n\nThe value is i is : 2\n\nThe value is i is : 4\n\nThe value is i is : 40 \n"
},
{
"code": null,
"e": 3257,
"s": 3224,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3274,
"s": 3257,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3281,
"s": 3274,
"text": " Print"
},
{
"code": null,
"e": 3292,
"s": 3281,
"text": " Add Notes"
}
] |
Socket programming In Python
|
In bidirectional communications channel, sockets are two end points. Sockets can communicate between process on the same machine or on different continents.
Sockets are implemented by the different types of channel-TCP, UDP.
For creating Socket, we need socket module and socket.socket () function.
my_socket = socket.socket (socket_family, socket_type, protocol=0)
Different methods in Server Socket
my_socket.bind()
This method is used for binding address (hostname, port number pair) to socket.
my_socket.listen()
This method is used for set up and start TCP listener.
my_socket.accept()
This method is used for accepting TCP client connection, waiting until connection arrives (blocking).
my_socket.connect()
This method actively initiates TCP server connection.
my_socket.recv()
This method receives TCP message
my_socket.send()
This method transmits TCP message
my_socket.recvfrom()
This method receives UDP message
my_socket.sendto()
This method transmits UDP message
my_socket.close()
This method closes socket
my_socket.gethostname()
This method returns the hostname.
import socket
my_socket = socket.socket() # Create a socket object
my_host = socket.gethostname()
my_port = 00000# Store a port for your service.
my_socket.bind((my_host, my_port))
my_socket.listen(5) # Now wait for client connection.
while True:
cl, myaddr = my_socket.accept() # Establish connection with client.
print ('Got connection from', myaddr)
cl.send('Thank you for connecting')
cl.close() # Close the connection
import socket # Import socket module
my_socket = socket.socket() # Create a socket object
my_host = socket.gethostname() # Get local machine name
my_port = 00000# Store a port for your service.
my_socket.connect((my_host, my_port))
print (my_socket.recv(1024))
my_socket.close
|
[
{
"code": null,
"e": 1219,
"s": 1062,
"text": "In bidirectional communications channel, sockets are two end points. Sockets can communicate between process on the same machine or on different continents."
},
{
"code": null,
"e": 1287,
"s": 1219,
"text": "Sockets are implemented by the different types of channel-TCP, UDP."
},
{
"code": null,
"e": 1361,
"s": 1287,
"text": "For creating Socket, we need socket module and socket.socket () function."
},
{
"code": null,
"e": 1429,
"s": 1361,
"text": "my_socket = socket.socket (socket_family, socket_type, protocol=0)\n"
},
{
"code": null,
"e": 1464,
"s": 1429,
"text": "Different methods in Server Socket"
},
{
"code": null,
"e": 1482,
"s": 1464,
"text": "my_socket.bind()\n"
},
{
"code": null,
"e": 1562,
"s": 1482,
"text": "This method is used for binding address (hostname, port number pair) to socket."
},
{
"code": null,
"e": 1582,
"s": 1562,
"text": "my_socket.listen()\n"
},
{
"code": null,
"e": 1637,
"s": 1582,
"text": "This method is used for set up and start TCP listener."
},
{
"code": null,
"e": 1657,
"s": 1637,
"text": "my_socket.accept()\n"
},
{
"code": null,
"e": 1759,
"s": 1657,
"text": "This method is used for accepting TCP client connection, waiting until connection arrives (blocking)."
},
{
"code": null,
"e": 1780,
"s": 1759,
"text": "my_socket.connect()\n"
},
{
"code": null,
"e": 1834,
"s": 1780,
"text": "This method actively initiates TCP server connection."
},
{
"code": null,
"e": 1852,
"s": 1834,
"text": "my_socket.recv()\n"
},
{
"code": null,
"e": 1885,
"s": 1852,
"text": "This method receives TCP message"
},
{
"code": null,
"e": 1903,
"s": 1885,
"text": "my_socket.send()\n"
},
{
"code": null,
"e": 1937,
"s": 1903,
"text": "This method transmits TCP message"
},
{
"code": null,
"e": 1959,
"s": 1937,
"text": "my_socket.recvfrom()\n"
},
{
"code": null,
"e": 1992,
"s": 1959,
"text": "This method receives UDP message"
},
{
"code": null,
"e": 2012,
"s": 1992,
"text": "my_socket.sendto()\n"
},
{
"code": null,
"e": 2046,
"s": 2012,
"text": "This method transmits UDP message"
},
{
"code": null,
"e": 2065,
"s": 2046,
"text": "my_socket.close()\n"
},
{
"code": null,
"e": 2091,
"s": 2065,
"text": "This method closes socket"
},
{
"code": null,
"e": 2116,
"s": 2091,
"text": "my_socket.gethostname()\n"
},
{
"code": null,
"e": 2150,
"s": 2116,
"text": "This method returns the hostname."
},
{
"code": null,
"e": 2603,
"s": 2150,
"text": "import socket\nmy_socket = socket.socket() # Create a socket object\nmy_host = socket.gethostname()\nmy_port = 00000# Store a port for your service.\nmy_socket.bind((my_host, my_port))\nmy_socket.listen(5) # Now wait for client connection.\nwhile True:\n cl, myaddr = my_socket.accept() # Establish connection with client.\n print ('Got connection from', myaddr)\n cl.send('Thank you for connecting')\n cl.close() # Close the connection"
},
{
"code": null,
"e": 2894,
"s": 2603,
"text": "import socket # Import socket module\nmy_socket = socket.socket() # Create a socket object\nmy_host = socket.gethostname() # Get local machine name\nmy_port = 00000# Store a port for your service.\nmy_socket.connect((my_host, my_port))\nprint (my_socket.recv(1024))\nmy_socket.close"
}
] |
Spring Boot - Rest Template
|
Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods. The code given below shows how to create Bean for Rest Template to auto wiring the Rest Template object.
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
Consuming the GET API by using RestTemplate - exchange() method
Assume this URL http://localhost:8080/products returns the following JSON and we are going to consume this API response by using Rest Template using the following code −
[
{
"id": "1",
"name": "Honey"
},
{
"id": "2",
"name": "Almond"
}
]
You will have to follow the given points to consume the API −
Autowired the Rest Template Object.
Use HttpHeaders to set the Request Headers.
Use HttpEntity to wrap the request object.
Provide the URL, HttpMethod, and Return type for Exchange() method.
@RestController
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/template/products")
public String getProductList() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity <String> entity = new HttpEntity<String>(headers);
return restTemplate.exchange("
http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody();
}
}
Consuming POST API by using RestTemplate - exchange() method
Assume this URL http://localhost:8080/products returns the response shown below, we are going to consume this API response by using the Rest Template.
The code given below is the Request body −
{
"id":"3",
"name":"Ginger"
}
The code given below is the Response body −
Product is created successfully
You will have to follow the points given below to consume the API −
Autowired the Rest Template Object.
Autowired the Rest Template Object.
Use the HttpHeaders to set the Request Headers.
Use the HttpHeaders to set the Request Headers.
Use the HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body.
Use the HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body.
Provide the URL, HttpMethod, and Return type for exchange() method.
Provide the URL, HttpMethod, and Return type for exchange() method.
@RestController
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/template/products", method = RequestMethod.POST)
public String createProducts(@RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products", HttpMethod.POST, entity, String.class).getBody();
}
}
Consuming PUT API by using RestTemplate - exchange() method
Assume this URL http://localhost:8080/products/3 returns the below response and we are going to consume this API response by using Rest Template.
The code given below is Request body −
{
"name":"Indian Ginger"
}
The code given below is the Response body −
Product is updated successfully
You will have to follow the points given below to consume the API −
Autowired the Rest Template Object.
Autowired the Rest Template Object.
Use HttpHeaders to set the Request Headers.
Use HttpHeaders to set the Request Headers.
Use HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body.
Use HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body.
Provide the URL, HttpMethod, and Return type for exchange() method.
Provide the URL, HttpMethod, and Return type for exchange() method.
@RestController
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/template/products/{id}", method = RequestMethod.PUT)
public String updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id, HttpMethod.PUT, entity, String.class).getBody();
}
}
Consuming DELETE API by using RestTemplate - exchange() method
Assume this URL http://localhost:8080/products/3 returns the response given below and we are going to consume this API response by using Rest Template.
This line of code shown below is the Response body −
Product is deleted successfully
You will have to follow the points shown below to consume the API −
Autowired the Rest Template Object.
Autowired the Rest Template Object.
Use HttpHeaders to set the Request Headers.
Use HttpHeaders to set the Request Headers.
Use HttpEntity to wrap the request object.
Use HttpEntity to wrap the request object.
Provide the URL, HttpMethod, and Return type for exchange() method.
Provide the URL, HttpMethod, and Return type for exchange() method.
@RestController
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/template/products/{id}", method = RequestMethod.DELETE)
public String deleteProduct(@PathVariable("id") String id) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id, HttpMethod.DELETE, entity, String.class).getBody();
}
}
The complete Rest Template Controller class file is given below −
package com.tutorialspoint.demo.controller;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/template/products")
public String getProductList() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
return restTemplate.exchange(
"http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody();
}
@RequestMapping(value = "/template/products", method = RequestMethod.POST)
public String createProducts(@RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products", HttpMethod.POST, entity, String.class).getBody();
}
@RequestMapping(value = "/template/products/{id}", method = RequestMethod.PUT)
public String updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id, HttpMethod.PUT, entity, String.class).getBody();
}
@RequestMapping(value = "/template/products/{id}", method = RequestMethod.DELETE)
public String deleteProduct(@PathVariable("id") String id) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id, HttpMethod.DELETE, entity, String.class).getBody();
}
}
The code for Spring Boot Application Class – DemoApplication.java is given below −
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
The code for Maven build – pom.xml is given below −
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The code for Gradle Build – build.gradle is given below −
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −
For Maven, you can use the command given below −
mvn clean install
After “BUILD SUCCESS”, you can find the JAR file under the target directory.
For Gradle, you can use the command shown below −
gradle clean build
After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory.
Now, run the JAR file by using the following command −
java –jar <JARFILE>
Now, the application has started on the Tomcat port 8080.
Now hit the below URL’s in POSTMAN application and you can see the output.
GET Products by Rest Template − http://localhost:8080/template/products
Create Products POST − http://localhost:8080/template/products
Update Product PUT − http://localhost:8080/template/products/3
Delete Product − http://localhost:8080/template/products/3
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3294,
"s": 3025,
"text": "Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods. The code given below shows how to create Bean for Rest Template to auto wiring the Rest Template object."
},
{
"code": null,
"e": 3806,
"s": 3294,
"text": "package com.tutorialspoint.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.web.client.RestTemplate;\n\n@SpringBootApplication\npublic class DemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(DemoApplication.class, args);\n }\n @Bean\n public RestTemplate getRestTemplate() {\n return new RestTemplate();\n }\n}"
},
{
"code": null,
"e": 3870,
"s": 3806,
"text": "Consuming the GET API by using RestTemplate - exchange() method"
},
{
"code": null,
"e": 4040,
"s": 3870,
"text": "Assume this URL http://localhost:8080/products returns the following JSON and we are going to consume this API response by using Rest Template using the following code −"
},
{
"code": null,
"e": 4144,
"s": 4040,
"text": "[\n {\n \"id\": \"1\",\n \"name\": \"Honey\"\n },\n {\n \"id\": \"2\",\n \"name\": \"Almond\"\n }\n]"
},
{
"code": null,
"e": 4206,
"s": 4144,
"text": "You will have to follow the given points to consume the API −"
},
{
"code": null,
"e": 4242,
"s": 4206,
"text": "Autowired the Rest Template Object."
},
{
"code": null,
"e": 4286,
"s": 4242,
"text": "Use HttpHeaders to set the Request Headers."
},
{
"code": null,
"e": 4329,
"s": 4286,
"text": "Use HttpEntity to wrap the request object."
},
{
"code": null,
"e": 4397,
"s": 4329,
"text": "Provide the URL, HttpMethod, and Return type for Exchange() method."
},
{
"code": null,
"e": 4901,
"s": 4397,
"text": "@RestController\npublic class ConsumeWebService {\n @Autowired\n RestTemplate restTemplate;\n\n @RequestMapping(value = \"/template/products\")\n public String getProductList() {\n HttpHeaders headers = new HttpHeaders();\n headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n HttpEntity <String> entity = new HttpEntity<String>(headers);\n \n return restTemplate.exchange(\"\n http://localhost:8080/products\", HttpMethod.GET, entity, String.class).getBody();\n }\n}"
},
{
"code": null,
"e": 4962,
"s": 4901,
"text": "Consuming POST API by using RestTemplate - exchange() method"
},
{
"code": null,
"e": 5113,
"s": 4962,
"text": "Assume this URL http://localhost:8080/products returns the response shown below, we are going to consume this API response by using the Rest Template."
},
{
"code": null,
"e": 5156,
"s": 5113,
"text": "The code given below is the Request body −"
},
{
"code": null,
"e": 5192,
"s": 5156,
"text": "{\n \"id\":\"3\",\n \"name\":\"Ginger\"\n}"
},
{
"code": null,
"e": 5236,
"s": 5192,
"text": "The code given below is the Response body −"
},
{
"code": null,
"e": 5269,
"s": 5236,
"text": "Product is created successfully\n"
},
{
"code": null,
"e": 5337,
"s": 5269,
"text": "You will have to follow the points given below to consume the API −"
},
{
"code": null,
"e": 5373,
"s": 5337,
"text": "Autowired the Rest Template Object."
},
{
"code": null,
"e": 5409,
"s": 5373,
"text": "Autowired the Rest Template Object."
},
{
"code": null,
"e": 5457,
"s": 5409,
"text": "Use the HttpHeaders to set the Request Headers."
},
{
"code": null,
"e": 5505,
"s": 5457,
"text": "Use the HttpHeaders to set the Request Headers."
},
{
"code": null,
"e": 5617,
"s": 5505,
"text": "Use the HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body."
},
{
"code": null,
"e": 5729,
"s": 5617,
"text": "Use the HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body."
},
{
"code": null,
"e": 5797,
"s": 5729,
"text": "Provide the URL, HttpMethod, and Return type for exchange() method."
},
{
"code": null,
"e": 5865,
"s": 5797,
"text": "Provide the URL, HttpMethod, and Return type for exchange() method."
},
{
"code": null,
"e": 6436,
"s": 5865,
"text": "@RestController\npublic class ConsumeWebService {\n @Autowired\n RestTemplate restTemplate;\n\n @RequestMapping(value = \"/template/products\", method = RequestMethod.POST)\n public String createProducts(@RequestBody Product product) {\n HttpHeaders headers = new HttpHeaders();\n headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);\n \n return restTemplate.exchange(\n \"http://localhost:8080/products\", HttpMethod.POST, entity, String.class).getBody();\n }\n}"
},
{
"code": null,
"e": 6496,
"s": 6436,
"text": "Consuming PUT API by using RestTemplate - exchange() method"
},
{
"code": null,
"e": 6642,
"s": 6496,
"text": "Assume this URL http://localhost:8080/products/3 returns the below response and we are going to consume this API response by using Rest Template."
},
{
"code": null,
"e": 6681,
"s": 6642,
"text": "The code given below is Request body −"
},
{
"code": null,
"e": 6711,
"s": 6681,
"text": "{\n \"name\":\"Indian Ginger\"\n}"
},
{
"code": null,
"e": 6755,
"s": 6711,
"text": "The code given below is the Response body −"
},
{
"code": null,
"e": 6788,
"s": 6755,
"text": "Product is updated successfully\n"
},
{
"code": null,
"e": 6856,
"s": 6788,
"text": "You will have to follow the points given below to consume the API −"
},
{
"code": null,
"e": 6892,
"s": 6856,
"text": "Autowired the Rest Template Object."
},
{
"code": null,
"e": 6928,
"s": 6892,
"text": "Autowired the Rest Template Object."
},
{
"code": null,
"e": 6972,
"s": 6928,
"text": "Use HttpHeaders to set the Request Headers."
},
{
"code": null,
"e": 7016,
"s": 6972,
"text": "Use HttpHeaders to set the Request Headers."
},
{
"code": null,
"e": 7124,
"s": 7016,
"text": "Use HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body."
},
{
"code": null,
"e": 7232,
"s": 7124,
"text": "Use HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body."
},
{
"code": null,
"e": 7300,
"s": 7232,
"text": "Provide the URL, HttpMethod, and Return type for exchange() method."
},
{
"code": null,
"e": 7368,
"s": 7300,
"text": "Provide the URL, HttpMethod, and Return type for exchange() method."
},
{
"code": null,
"e": 7976,
"s": 7368,
"text": "@RestController\npublic class ConsumeWebService {\n @Autowired\n RestTemplate restTemplate;\n\n @RequestMapping(value = \"/template/products/{id}\", method = RequestMethod.PUT)\n public String updateProduct(@PathVariable(\"id\") String id, @RequestBody Product product) {\n HttpHeaders headers = new HttpHeaders();\n headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);\n \n return restTemplate.exchange(\n \"http://localhost:8080/products/\"+id, HttpMethod.PUT, entity, String.class).getBody();\n }\n}"
},
{
"code": null,
"e": 8039,
"s": 7976,
"text": "Consuming DELETE API by using RestTemplate - exchange() method"
},
{
"code": null,
"e": 8191,
"s": 8039,
"text": "Assume this URL http://localhost:8080/products/3 returns the response given below and we are going to consume this API response by using Rest Template."
},
{
"code": null,
"e": 8244,
"s": 8191,
"text": "This line of code shown below is the Response body −"
},
{
"code": null,
"e": 8277,
"s": 8244,
"text": "Product is deleted successfully\n"
},
{
"code": null,
"e": 8345,
"s": 8277,
"text": "You will have to follow the points shown below to consume the API −"
},
{
"code": null,
"e": 8381,
"s": 8345,
"text": "Autowired the Rest Template Object."
},
{
"code": null,
"e": 8417,
"s": 8381,
"text": "Autowired the Rest Template Object."
},
{
"code": null,
"e": 8461,
"s": 8417,
"text": "Use HttpHeaders to set the Request Headers."
},
{
"code": null,
"e": 8505,
"s": 8461,
"text": "Use HttpHeaders to set the Request Headers."
},
{
"code": null,
"e": 8548,
"s": 8505,
"text": "Use HttpEntity to wrap the request object."
},
{
"code": null,
"e": 8591,
"s": 8548,
"text": "Use HttpEntity to wrap the request object."
},
{
"code": null,
"e": 8659,
"s": 8591,
"text": "Provide the URL, HttpMethod, and Return type for exchange() method."
},
{
"code": null,
"e": 8727,
"s": 8659,
"text": "Provide the URL, HttpMethod, and Return type for exchange() method."
},
{
"code": null,
"e": 9303,
"s": 8727,
"text": "@RestController\npublic class ConsumeWebService {\n @Autowired\n RestTemplate restTemplate;\n\n @RequestMapping(value = \"/template/products/{id}\", method = RequestMethod.DELETE)\n public String deleteProduct(@PathVariable(\"id\") String id) {\n HttpHeaders headers = new HttpHeaders();\n headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n HttpEntity<Product> entity = new HttpEntity<Product>(headers);\n \n return restTemplate.exchange(\n \"http://localhost:8080/products/\"+id, HttpMethod.DELETE, entity, String.class).getBody();\n }\n}"
},
{
"code": null,
"e": 9369,
"s": 9303,
"text": "The complete Rest Template Controller class file is given below −"
},
{
"code": null,
"e": 12059,
"s": 9369,
"text": "package com.tutorialspoint.demo.controller;\n\nimport java.util.Arrays;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpEntity;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.MediaType;\n\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.client.RestTemplate;\n\nimport com.tutorialspoint.demo.model.Product;\n\n@RestController\npublic class ConsumeWebService {\n @Autowired\n RestTemplate restTemplate;\n\n @RequestMapping(value = \"/template/products\")\n public String getProductList() {\n HttpHeaders headers = new HttpHeaders();\n headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n HttpEntity<String> entity = new HttpEntity<String>(headers);\n \n return restTemplate.exchange(\n \"http://localhost:8080/products\", HttpMethod.GET, entity, String.class).getBody();\n }\n @RequestMapping(value = \"/template/products\", method = RequestMethod.POST)\n public String createProducts(@RequestBody Product product) {\n HttpHeaders headers = new HttpHeaders();\n headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);\n \n return restTemplate.exchange(\n \"http://localhost:8080/products\", HttpMethod.POST, entity, String.class).getBody();\n }\n @RequestMapping(value = \"/template/products/{id}\", method = RequestMethod.PUT)\n public String updateProduct(@PathVariable(\"id\") String id, @RequestBody Product product) {\n HttpHeaders headers = new HttpHeaders();\n headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);\n \n return restTemplate.exchange(\n \"http://localhost:8080/products/\"+id, HttpMethod.PUT, entity, String.class).getBody();\n }\n @RequestMapping(value = \"/template/products/{id}\", method = RequestMethod.DELETE)\n public String deleteProduct(@PathVariable(\"id\") String id) {\n HttpHeaders headers = new HttpHeaders();\n headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));\n HttpEntity<Product> entity = new HttpEntity<Product>(headers);\n \n return restTemplate.exchange(\n \"http://localhost:8080/products/\"+id, HttpMethod.DELETE, entity, String.class).getBody();\n }\n}"
},
{
"code": null,
"e": 12142,
"s": 12059,
"text": "The code for Spring Boot Application Class – DemoApplication.java is given below −"
},
{
"code": null,
"e": 12460,
"s": 12142,
"text": "package com.tutorialspoint.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class DemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(DemoApplication.class, args);\n }\n}"
},
{
"code": null,
"e": 12512,
"s": 12460,
"text": "The code for Maven build – pom.xml is given below −"
},
{
"code": null,
"e": 14059,
"s": 12512,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>demo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>demo</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.8.RELEASE</version>\n <relativePath/> \n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n \n</project>"
},
{
"code": null,
"e": 14117,
"s": 14059,
"text": "The code for Gradle Build – build.gradle is given below −"
},
{
"code": null,
"e": 14701,
"s": 14117,
"text": "buildscript {\n ext {\n springBootVersion = '1.5.8.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\ndependencies {\n compile('org.springframework.boot:spring-boot-starter-web')\n testCompile('org.springframework.boot:spring-boot-starter-test')\n}"
},
{
"code": null,
"e": 14826,
"s": 14701,
"text": "You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −"
},
{
"code": null,
"e": 14875,
"s": 14826,
"text": "For Maven, you can use the command given below −"
},
{
"code": null,
"e": 14894,
"s": 14875,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 14971,
"s": 14894,
"text": "After “BUILD SUCCESS”, you can find the JAR file under the target directory."
},
{
"code": null,
"e": 15021,
"s": 14971,
"text": "For Gradle, you can use the command shown below −"
},
{
"code": null,
"e": 15041,
"s": 15021,
"text": "gradle clean build\n"
},
{
"code": null,
"e": 15121,
"s": 15041,
"text": "After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory."
},
{
"code": null,
"e": 15176,
"s": 15121,
"text": "Now, run the JAR file by using the following command −"
},
{
"code": null,
"e": 15198,
"s": 15176,
"text": "java –jar <JARFILE> \n"
},
{
"code": null,
"e": 15256,
"s": 15198,
"text": "Now, the application has started on the Tomcat port 8080."
},
{
"code": null,
"e": 15331,
"s": 15256,
"text": "Now hit the below URL’s in POSTMAN application and you can see the output."
},
{
"code": null,
"e": 15403,
"s": 15331,
"text": "GET Products by Rest Template − http://localhost:8080/template/products"
},
{
"code": null,
"e": 15466,
"s": 15403,
"text": "Create Products POST − http://localhost:8080/template/products"
},
{
"code": null,
"e": 15529,
"s": 15466,
"text": "Update Product PUT − http://localhost:8080/template/products/3"
},
{
"code": null,
"e": 15588,
"s": 15529,
"text": "Delete Product − http://localhost:8080/template/products/3"
},
{
"code": null,
"e": 15622,
"s": 15588,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 15636,
"s": 15622,
"text": " Karthikeya T"
},
{
"code": null,
"e": 15669,
"s": 15636,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 15684,
"s": 15669,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 15719,
"s": 15684,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 15731,
"s": 15719,
"text": " Senol Atac"
},
{
"code": null,
"e": 15766,
"s": 15731,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 15778,
"s": 15766,
"text": " Senol Atac"
},
{
"code": null,
"e": 15813,
"s": 15778,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 15825,
"s": 15813,
"text": " Senol Atac"
},
{
"code": null,
"e": 15858,
"s": 15825,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 15870,
"s": 15858,
"text": " Senol Atac"
},
{
"code": null,
"e": 15877,
"s": 15870,
"text": " Print"
},
{
"code": null,
"e": 15888,
"s": 15877,
"text": " Add Notes"
}
] |
Batch Script - DISKPART
|
This batch command shows and configures the properties of disk partitions.
Diskpart
@echo off
diskpart
The above command shows the properties of disk partitions. Following is an example of the output.
Microsoft DiskPart version 6.3.9600
Copyright (C) 1999-2013 Microsoft Corporation.
On computer: WIN-50GP30FGO75
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2244,
"s": 2169,
"text": "This batch command shows and configures the properties of disk partitions."
},
{
"code": null,
"e": 2254,
"s": 2244,
"text": "Diskpart\n"
},
{
"code": null,
"e": 2274,
"s": 2254,
"text": "@echo off \ndiskpart"
},
{
"code": null,
"e": 2372,
"s": 2274,
"text": "The above command shows the properties of disk partitions. Following is an example of the output."
},
{
"code": null,
"e": 2486,
"s": 2372,
"text": "Microsoft DiskPart version 6.3.9600\n\nCopyright (C) 1999-2013 Microsoft Corporation.\nOn computer: WIN-50GP30FGO75\n"
},
{
"code": null,
"e": 2493,
"s": 2486,
"text": " Print"
},
{
"code": null,
"e": 2504,
"s": 2493,
"text": " Add Notes"
}
] |
Assertions in Python
|
An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.
Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.
When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.
The syntax for assert is −
assert Expression[, Arguments]
If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.
Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature −
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
When the above code is executed, it produces the following result −
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2361,
"s": 2244,
"text": "An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program."
},
{
"code": null,
"e": 2576,
"s": 2361,
"text": "The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised."
},
{
"code": null,
"e": 2685,
"s": 2576,
"text": "Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5."
},
{
"code": null,
"e": 2826,
"s": 2685,
"text": "Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output."
},
{
"code": null,
"e": 3008,
"s": 2826,
"text": "When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception."
},
{
"code": null,
"e": 3035,
"s": 3008,
"text": "The syntax for assert is −"
},
{
"code": null,
"e": 3067,
"s": 3035,
"text": "assert Expression[, Arguments]\n"
},
{
"code": null,
"e": 3348,
"s": 3067,
"text": "If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback."
},
{
"code": null,
"e": 3546,
"s": 3348,
"text": "Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature −"
},
{
"code": null,
"e": 3795,
"s": 3546,
"text": "#!/usr/bin/python\n\ndef KelvinToFahrenheit(Temperature):\n assert (Temperature >= 0),\"Colder than absolute zero!\"\n return ((Temperature-273)*1.8)+32\n\nprint KelvinToFahrenheit(273)\nprint int(KelvinToFahrenheit(505.78))\nprint KelvinToFahrenheit(-5)"
},
{
"code": null,
"e": 3864,
"s": 3795,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4136,
"s": 3864,
"text": "32.0\n451\nTraceback (most recent call last):\n File \"test.py\", line 9, in <module>\n print KelvinToFahrenheit(-5)\n File \"test.py\", line 4, in KelvinToFahrenheit\n assert (Temperature >= 0),\"Colder than absolute zero!\"\nAssertionError: Colder than absolute zero!\n"
},
{
"code": null,
"e": 4173,
"s": 4136,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4189,
"s": 4173,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4222,
"s": 4189,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4241,
"s": 4222,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4276,
"s": 4241,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4298,
"s": 4276,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4332,
"s": 4298,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4360,
"s": 4332,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4395,
"s": 4360,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4409,
"s": 4395,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4442,
"s": 4409,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4459,
"s": 4442,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4466,
"s": 4459,
"text": " Print"
},
{
"code": null,
"e": 4477,
"s": 4466,
"text": " Add Notes"
}
] |
Java ResultSetMetaData getColumnTypeName() method with example
|
The getColumnTypeName() method of the ResultSetMetaData (interface) retrieves and returns the name of the datatype of the specified column in the current ResultSet object.
This method accepts an integer value representing the index of a column and, returns a String value representing the name of the SQL data type of the specified column.
To get the ResultSetMetaData object, you need to −
Register the Driver: Select the required database register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class.
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Get connection: Create a connection object by passing the URL of the database, username and password of a user in the database (in string format) as parameters to the getConnection() method of the DriverManager class.
Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password");
Create a Statement object: Create a Statement object using the createStatement method of the connection interface.
Statement stmt = con.createStatement();
Execute the Query: Execute the SELECT query using the executeQuery() methods of the Statement interface and Retrieve the results into the ResultSet object.
String query = "Select * from MyPlayers";
ResultSet rs = stmt.executeQuery(query);
Get the ResultSetMetaData object: Retrieve the ResultSetMetsdata object of the current ResultSet by invoking the getMetaData() method.
ResultSetMetaData resultSetMetaData = rs.getMetaData();
Finally, using the getColumnTypeName() method of the ResultSetMetaData interface get the data type name of the specified column as −
int columnType = resultSetMetaData.getColumnTypeName();
Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below -
CREATE TABLE MyPlayers(
ID INT,
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Date_Of_Birth date,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255),
PRIMARY KEY (ID)
);
Now, we will insert 7 records in MyPlayers table using INSERT statements −
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');
insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
Following JDBC program establishes connection with MySQL database, retrieves and displays the name of the data type of the 4th column in the MyPlayers table using the getColumnTypeName() method.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class ResultSetMetaData_getColumnTypeName {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to retrieve records
String query = "Select * from MyPlayers";
//Executing the query
ResultSet rs = stmt.executeQuery(query);
//retrieving the ResultSetMetaData object
ResultSetMetaData resultSetMetaData = rs.getMetaData();
//Retrieving the data type name of the column
String columnTypeName = resultSetMetaData.getColumnTypeName(4);
System.out.println("Data type name of the 4th column of the MyPlayers table: "+ columnTypeName);
}
}
Connection established......
Data type name of the 4th column: VARCHAR
|
[
{
"code": null,
"e": 1234,
"s": 1062,
"text": "The getColumnTypeName() method of the ResultSetMetaData (interface) retrieves and returns the name of the datatype of the specified column in the current ResultSet object."
},
{
"code": null,
"e": 1402,
"s": 1234,
"text": "This method accepts an integer value representing the index of a column and, returns a String value representing the name of the SQL data type of the specified column."
},
{
"code": null,
"e": 1453,
"s": 1402,
"text": "To get the ResultSetMetaData object, you need to −"
},
{
"code": null,
"e": 1668,
"s": 1453,
"text": "Register the Driver: Select the required database register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class."
},
{
"code": null,
"e": 1727,
"s": 1668,
"text": "DriverManager.registerDriver(new com.mysql.jdbc.Driver());"
},
{
"code": null,
"e": 1945,
"s": 1727,
"text": "Get connection: Create a connection object by passing the URL of the database, username and password of a user in the database (in string format) as parameters to the getConnection() method of the DriverManager class."
},
{
"code": null,
"e": 2026,
"s": 1945,
"text": "Connection mysqlCon = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");"
},
{
"code": null,
"e": 2141,
"s": 2026,
"text": "Create a Statement object: Create a Statement object using the createStatement method of the connection interface."
},
{
"code": null,
"e": 2181,
"s": 2141,
"text": "Statement stmt = con.createStatement();"
},
{
"code": null,
"e": 2337,
"s": 2181,
"text": "Execute the Query: Execute the SELECT query using the executeQuery() methods of the Statement interface and Retrieve the results into the ResultSet object."
},
{
"code": null,
"e": 2420,
"s": 2337,
"text": "String query = \"Select * from MyPlayers\";\nResultSet rs = stmt.executeQuery(query);"
},
{
"code": null,
"e": 2555,
"s": 2420,
"text": "Get the ResultSetMetaData object: Retrieve the ResultSetMetsdata object of the current ResultSet by invoking the getMetaData() method."
},
{
"code": null,
"e": 2611,
"s": 2555,
"text": "ResultSetMetaData resultSetMetaData = rs.getMetaData();"
},
{
"code": null,
"e": 2744,
"s": 2611,
"text": "Finally, using the getColumnTypeName() method of the ResultSetMetaData interface get the data type name of the specified column as −"
},
{
"code": null,
"e": 2800,
"s": 2744,
"text": "int columnType = resultSetMetaData.getColumnTypeName();"
},
{
"code": null,
"e": 2901,
"s": 2800,
"text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below - "
},
{
"code": null,
"e": 3094,
"s": 2901,
"text": "CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n PRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 3169,
"s": 3094,
"text": "Now, we will insert 7 records in MyPlayers table using INSERT statements −"
},
{
"code": null,
"e": 3831,
"s": 3169,
"text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\ninsert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');"
},
{
"code": null,
"e": 4026,
"s": 3831,
"text": "Following JDBC program establishes connection with MySQL database, retrieves and displays the name of the data type of the 4th column in the MyPlayers table using the getColumnTypeName() method."
},
{
"code": null,
"e": 5223,
"s": 4026,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.ResultSetMetaData;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ResultSetMetaData_getColumnTypeName {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to retrieve records\n String query = \"Select * from MyPlayers\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n //retrieving the ResultSetMetaData object\n ResultSetMetaData resultSetMetaData = rs.getMetaData();\n //Retrieving the data type name of the column\n String columnTypeName = resultSetMetaData.getColumnTypeName(4);\n System.out.println(\"Data type name of the 4th column of the MyPlayers table: \"+ columnTypeName);\n }\n}"
},
{
"code": null,
"e": 5294,
"s": 5223,
"text": "Connection established......\nData type name of the 4th column: VARCHAR"
}
] |
101 SQL with Python Code Tutorial | Towards Data Science
|
SQL is the world’s most loved (or at least most used) data storage/querying language — and Python the most popular programming language in the world. Both together can produce some spectacular results.
We will run through the basics of getting set up with a local, open-source SQL server (MySQL). And connecting to that server and executing SQL queries via Python. We will cover:
> Setting Up MySQL - Running a MySQL Server> MySQL For Python - Setup> Databases and Tables - The Database - Creating a Table 1. The SQL Way 2. The Pandas Way> Quick Queries - Reading Data - Filtering - Or Anything Else
First, we need to install MySQL. You can find the MS installation over here (make sure to download the full version — not web).
Once the installer opens, we select Developer Default and continue through the next few steps to install MySQL.
After installation, there will be a few more configuration steps. Follow these and use all of the default settings (unless you need to change them). You will also be able to set up the password for the root user — don’t forget this.
Once installed, our MySQL Server should be running over on port 3306. If it doesn’t seem to be running, we can instantiate it by opening a command prompt window (CMD, Bash, etc.) and typing mysqld.
If the command is not found, navigate to your MySQL Server /bin directory before running mysqld. For me, on Windows, the path is:
C:\Program Files\MySQL\MySQL Server 8.0\bin
Next, we need to install a MySQL connection package for Python called mysql.connector. We do this by opening CMD/Anaconda Prompt/Bash/etc. and typing:
pip install mysql-connector-python
Simple! Let’s switch over to Python and check that everything is working properly:
import mysql.connector# connect to our local MySQL instance using connection stringmydb = mysql.connector.connect( host="localhost", user="root", password="<PASSWORD>")
We should then be able to print our mydb like so:
The hierarchy of objects in SQL includes our server at the very top. Inside the server are the databases, and inside the databases are the SQL tables themselves.
Our data is stored within these tables. So, let’s go ahead and create our first database and table.
Back in Python, we can execute SQL statements using the execute method, like so:
Of course, we don’t have any databases to show yet. To create a database in SQL, we write CREATE DATABASE dbname — using Python, we write:
mycursor.execute("CREATE DATABASE dbname")
We can then connect to our new database using another connection string that specifies our database database="dbname":
Next up, we create our table, which will contain all of our data. We can do this in two ways.
1.After connecting to our new database, we can execute a CREATE TABLE query:
Now we have a table called dbtable! It contains just three columns:
user_id — an eight-character string
location — an up to 32 character string
number_of — an integer
We can then populate the table like we usually would in SQL:
The final line mydb.commit() is an extra step required when using Python. Typically, SQL commands auto-commit to a database. But, this is not the case when using a Python connection.
So, after every modification — we must commit it for the change to persist. We can check our changes like so:
2.We can take some data from a Pandas DataFrame to create our new data table.
I will use the Titanic dataset (train.csv) in this example — but feel free to use any dataset you like.
When adding data from a Pandas Dataframe, we actually need to switch to another framework and create a ‘SQLAlchemy’ connection. First, install sqlalchemy:
pip install sqlalchemy
Once installed, we can import this module and create our new connection like so:
And now we’re ready to create our new SQL table using a Pandas DataFrame. All we need is the to_sql method:
Now we’re done, we’ve uploaded the Titanic dataset to MySQL. We can head over to MySQL Workbench to see our new table too:
Let’s practice with some queries using our new titanic table.
First, let’s read our data. We can get the equivalent of a dataframe head in SQL using SELECT TOP(5) * FROM titanic:
Alternatively, we can extract our query results directly to a Pandas dataframe:
Of course, we can couple this up with any usual SQL query. We can filter on a specific condition using a WHERE statement:
We can perform any query that we usually would in SQL. Quickly putting together SQL code to analyze our data:
That’s all for this introduction to MySQL with Python! We’ve covered:
Installing and setting up MySQL
Setting up MySQL in Python
SQL databases and tables
Creating both from Python
Uploading dataframes to MySQL
Querying our data!
Fortunately, it’s remarkably straightforward to get up and running with Python and MySQL — and using both can really optimize data analytics/science workflows or serve as a great data management system.
I hope you enjoyed this article. If you’re interested in seeing more content, I post tutorials to YouTube here! Or, if you have any questions or ideas, let me know via Twitter or in the comments below.
Thanks for reading!
🤖 70% Discount on the NLP With Transformers Course
*All images are by the author except where stated otherwise
|
[
{
"code": null,
"e": 374,
"s": 172,
"text": "SQL is the world’s most loved (or at least most used) data storage/querying language — and Python the most popular programming language in the world. Both together can produce some spectacular results."
},
{
"code": null,
"e": 552,
"s": 374,
"text": "We will run through the basics of getting set up with a local, open-source SQL server (MySQL). And connecting to that server and executing SQL queries via Python. We will cover:"
},
{
"code": null,
"e": 785,
"s": 552,
"text": "> Setting Up MySQL - Running a MySQL Server> MySQL For Python - Setup> Databases and Tables - The Database - Creating a Table 1. The SQL Way 2. The Pandas Way> Quick Queries - Reading Data - Filtering - Or Anything Else"
},
{
"code": null,
"e": 913,
"s": 785,
"text": "First, we need to install MySQL. You can find the MS installation over here (make sure to download the full version — not web)."
},
{
"code": null,
"e": 1025,
"s": 913,
"text": "Once the installer opens, we select Developer Default and continue through the next few steps to install MySQL."
},
{
"code": null,
"e": 1258,
"s": 1025,
"text": "After installation, there will be a few more configuration steps. Follow these and use all of the default settings (unless you need to change them). You will also be able to set up the password for the root user — don’t forget this."
},
{
"code": null,
"e": 1456,
"s": 1258,
"text": "Once installed, our MySQL Server should be running over on port 3306. If it doesn’t seem to be running, we can instantiate it by opening a command prompt window (CMD, Bash, etc.) and typing mysqld."
},
{
"code": null,
"e": 1586,
"s": 1456,
"text": "If the command is not found, navigate to your MySQL Server /bin directory before running mysqld. For me, on Windows, the path is:"
},
{
"code": null,
"e": 1630,
"s": 1586,
"text": "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin"
},
{
"code": null,
"e": 1781,
"s": 1630,
"text": "Next, we need to install a MySQL connection package for Python called mysql.connector. We do this by opening CMD/Anaconda Prompt/Bash/etc. and typing:"
},
{
"code": null,
"e": 1816,
"s": 1781,
"text": "pip install mysql-connector-python"
},
{
"code": null,
"e": 1899,
"s": 1816,
"text": "Simple! Let’s switch over to Python and check that everything is working properly:"
},
{
"code": null,
"e": 2071,
"s": 1899,
"text": "import mysql.connector# connect to our local MySQL instance using connection stringmydb = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"<PASSWORD>\")"
},
{
"code": null,
"e": 2121,
"s": 2071,
"text": "We should then be able to print our mydb like so:"
},
{
"code": null,
"e": 2283,
"s": 2121,
"text": "The hierarchy of objects in SQL includes our server at the very top. Inside the server are the databases, and inside the databases are the SQL tables themselves."
},
{
"code": null,
"e": 2383,
"s": 2283,
"text": "Our data is stored within these tables. So, let’s go ahead and create our first database and table."
},
{
"code": null,
"e": 2464,
"s": 2383,
"text": "Back in Python, we can execute SQL statements using the execute method, like so:"
},
{
"code": null,
"e": 2603,
"s": 2464,
"text": "Of course, we don’t have any databases to show yet. To create a database in SQL, we write CREATE DATABASE dbname — using Python, we write:"
},
{
"code": null,
"e": 2646,
"s": 2603,
"text": "mycursor.execute(\"CREATE DATABASE dbname\")"
},
{
"code": null,
"e": 2765,
"s": 2646,
"text": "We can then connect to our new database using another connection string that specifies our database database=\"dbname\":"
},
{
"code": null,
"e": 2859,
"s": 2765,
"text": "Next up, we create our table, which will contain all of our data. We can do this in two ways."
},
{
"code": null,
"e": 2936,
"s": 2859,
"text": "1.After connecting to our new database, we can execute a CREATE TABLE query:"
},
{
"code": null,
"e": 3004,
"s": 2936,
"text": "Now we have a table called dbtable! It contains just three columns:"
},
{
"code": null,
"e": 3040,
"s": 3004,
"text": "user_id — an eight-character string"
},
{
"code": null,
"e": 3080,
"s": 3040,
"text": "location — an up to 32 character string"
},
{
"code": null,
"e": 3103,
"s": 3080,
"text": "number_of — an integer"
},
{
"code": null,
"e": 3164,
"s": 3103,
"text": "We can then populate the table like we usually would in SQL:"
},
{
"code": null,
"e": 3347,
"s": 3164,
"text": "The final line mydb.commit() is an extra step required when using Python. Typically, SQL commands auto-commit to a database. But, this is not the case when using a Python connection."
},
{
"code": null,
"e": 3457,
"s": 3347,
"text": "So, after every modification — we must commit it for the change to persist. We can check our changes like so:"
},
{
"code": null,
"e": 3535,
"s": 3457,
"text": "2.We can take some data from a Pandas DataFrame to create our new data table."
},
{
"code": null,
"e": 3639,
"s": 3535,
"text": "I will use the Titanic dataset (train.csv) in this example — but feel free to use any dataset you like."
},
{
"code": null,
"e": 3794,
"s": 3639,
"text": "When adding data from a Pandas Dataframe, we actually need to switch to another framework and create a ‘SQLAlchemy’ connection. First, install sqlalchemy:"
},
{
"code": null,
"e": 3817,
"s": 3794,
"text": "pip install sqlalchemy"
},
{
"code": null,
"e": 3898,
"s": 3817,
"text": "Once installed, we can import this module and create our new connection like so:"
},
{
"code": null,
"e": 4006,
"s": 3898,
"text": "And now we’re ready to create our new SQL table using a Pandas DataFrame. All we need is the to_sql method:"
},
{
"code": null,
"e": 4129,
"s": 4006,
"text": "Now we’re done, we’ve uploaded the Titanic dataset to MySQL. We can head over to MySQL Workbench to see our new table too:"
},
{
"code": null,
"e": 4191,
"s": 4129,
"text": "Let’s practice with some queries using our new titanic table."
},
{
"code": null,
"e": 4308,
"s": 4191,
"text": "First, let’s read our data. We can get the equivalent of a dataframe head in SQL using SELECT TOP(5) * FROM titanic:"
},
{
"code": null,
"e": 4388,
"s": 4308,
"text": "Alternatively, we can extract our query results directly to a Pandas dataframe:"
},
{
"code": null,
"e": 4510,
"s": 4388,
"text": "Of course, we can couple this up with any usual SQL query. We can filter on a specific condition using a WHERE statement:"
},
{
"code": null,
"e": 4620,
"s": 4510,
"text": "We can perform any query that we usually would in SQL. Quickly putting together SQL code to analyze our data:"
},
{
"code": null,
"e": 4690,
"s": 4620,
"text": "That’s all for this introduction to MySQL with Python! We’ve covered:"
},
{
"code": null,
"e": 4722,
"s": 4690,
"text": "Installing and setting up MySQL"
},
{
"code": null,
"e": 4749,
"s": 4722,
"text": "Setting up MySQL in Python"
},
{
"code": null,
"e": 4774,
"s": 4749,
"text": "SQL databases and tables"
},
{
"code": null,
"e": 4800,
"s": 4774,
"text": "Creating both from Python"
},
{
"code": null,
"e": 4830,
"s": 4800,
"text": "Uploading dataframes to MySQL"
},
{
"code": null,
"e": 4849,
"s": 4830,
"text": "Querying our data!"
},
{
"code": null,
"e": 5052,
"s": 4849,
"text": "Fortunately, it’s remarkably straightforward to get up and running with Python and MySQL — and using both can really optimize data analytics/science workflows or serve as a great data management system."
},
{
"code": null,
"e": 5254,
"s": 5052,
"text": "I hope you enjoyed this article. If you’re interested in seeing more content, I post tutorials to YouTube here! Or, if you have any questions or ideas, let me know via Twitter or in the comments below."
},
{
"code": null,
"e": 5274,
"s": 5254,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 5325,
"s": 5274,
"text": "🤖 70% Discount on the NLP With Transformers Course"
}
] |
clear() element method - Selenium Python - GeeksforGeeks
|
27 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use clear method in Selenium. clear method is used to clear text of any field, such as input field of a form or even to anchor tag paragraph, etc. It replaces its contents on the webpage in your browser.
element.clear()
Example –
<input type="text" name="passwd" id="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_name("passwd")
To enter text into a field, for example,
element.send_keys("some text")
Now one can clear this field with
element.clear()
Also note, it is possible to call clear on any element, which makes it possible to test keyboard shortcuts such as those used on Gmail.One can easily clear the contents of a text field or textarea with the clear method:
Let’s try to enter text in search field on geeksforgeeks and then clear its contents.Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_id("gsc-i-id2") # send keys element.send_keys("Arrays") # clear contentselement.clear()
Output-
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
|
[
{
"code": null,
"e": 23995,
"s": 23967,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 24552,
"s": 23995,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies"
},
{
"code": null,
"e": 24792,
"s": 24552,
"text": "This article revolves around how to use clear method in Selenium. clear method is used to clear text of any field, such as input field of a form or even to anchor tag paragraph, etc. It replaces its contents on the webpage in your browser."
},
{
"code": null,
"e": 24808,
"s": 24792,
"text": "element.clear()"
},
{
"code": null,
"e": 24818,
"s": 24808,
"text": "Example –"
},
{
"code": "<input type=\"text\" name=\"passwd\" id=\"passwd-id\" />",
"e": 24869,
"s": 24818,
"text": null
},
{
"code": null,
"e": 24950,
"s": 24869,
"text": "To find an element one needs to use one of the locating strategies, For example,"
},
{
"code": null,
"e": 25114,
"s": 24950,
"text": "element = driver.find_element_by_id(\"passwd-id\")\nelement = driver.find_element_by_name(\"passwd\")\nelement = driver.find_element_by_xpath(\"//input[@id='passwd-id']\")"
},
{
"code": null,
"e": 25160,
"s": 25114,
"text": "Also, to find multiple elements, we can use –"
},
{
"code": null,
"e": 25210,
"s": 25160,
"text": "elements = driver.find_elements_by_name(\"passwd\")"
},
{
"code": null,
"e": 25251,
"s": 25210,
"text": "To enter text into a field, for example,"
},
{
"code": null,
"e": 25282,
"s": 25251,
"text": "element.send_keys(\"some text\")"
},
{
"code": null,
"e": 25316,
"s": 25282,
"text": "Now one can clear this field with"
},
{
"code": null,
"e": 25332,
"s": 25316,
"text": "element.clear()"
},
{
"code": null,
"e": 25552,
"s": 25332,
"text": "Also note, it is possible to call clear on any element, which makes it possible to test keyboard shortcuts such as those used on Gmail.One can easily clear the contents of a text field or textarea with the clear method:"
},
{
"code": null,
"e": 25647,
"s": 25552,
"text": "Let’s try to enter text in search field on geeksforgeeks and then clear its contents.Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_id(\"gsc-i-id2\") # send keys element.send_keys(\"Arrays\") # clear contentselement.clear()",
"e": 25958,
"s": 25647,
"text": null
},
{
"code": null,
"e": 25966,
"s": 25958,
"text": "Output-"
},
{
"code": null,
"e": 25982,
"s": 25966,
"text": "Python-selenium"
},
{
"code": null,
"e": 25991,
"s": 25982,
"text": "selenium"
},
{
"code": null,
"e": 25998,
"s": 25991,
"text": "Python"
},
{
"code": null,
"e": 26096,
"s": 25998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26105,
"s": 26096,
"text": "Comments"
},
{
"code": null,
"e": 26118,
"s": 26105,
"text": "Old Comments"
},
{
"code": null,
"e": 26136,
"s": 26118,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26158,
"s": 26136,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26190,
"s": 26158,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26232,
"s": 26190,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26258,
"s": 26232,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26302,
"s": 26258,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26327,
"s": 26302,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26364,
"s": 26327,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26420,
"s": 26364,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
LinkedList AddFirst method in C#
|
In a Linked List, if you want to add a node at the first position, use AddFirst method.
Let’s first set a LinkedList.
string [] students = {"Jenifer","Angelina","Vera"};
LinkedList<string> list = new LinkedList<string>(students);
Now, to add an element as a first node, use AddFirst() method.
List.AddFirst(“Natalie”);
Live Demo
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
string [] students = {"Jenifer","Angelina","Vera"};
LinkedList<string> list = new LinkedList<string>(students);
foreach (var stu in list) {
Console.WriteLine(stu);
}
// add a node
Console.WriteLine("Node added at the first position...");
list.AddFirst("Natalie");
foreach (var stu in list) {
Console.WriteLine(stu);
}
}
}
Jenifer
Angelina
Vera
Node added at the first position...
Natalie
Jenifer
Angelina
Vera
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In a Linked List, if you want to add a node at the first position, use AddFirst method."
},
{
"code": null,
"e": 1180,
"s": 1150,
"text": "Let’s first set a LinkedList."
},
{
"code": null,
"e": 1292,
"s": 1180,
"text": "string [] students = {\"Jenifer\",\"Angelina\",\"Vera\"};\nLinkedList<string> list = new LinkedList<string>(students);"
},
{
"code": null,
"e": 1355,
"s": 1292,
"text": "Now, to add an element as a first node, use AddFirst() method."
},
{
"code": null,
"e": 1381,
"s": 1355,
"text": "List.AddFirst(“Natalie”);"
},
{
"code": null,
"e": 1392,
"s": 1381,
"text": " Live Demo"
},
{
"code": null,
"e": 1874,
"s": 1392,
"text": "using System;\nusing System.Collections.Generic;\nclass Demo {\n static void Main() {\n string [] students = {\"Jenifer\",\"Angelina\",\"Vera\"};\n LinkedList<string> list = new LinkedList<string>(students);\n foreach (var stu in list) {\n Console.WriteLine(stu);\n }\n // add a node\n Console.WriteLine(\"Node added at the first position...\");\n list.AddFirst(\"Natalie\");\n foreach (var stu in list) {\n Console.WriteLine(stu);\n }\n }\n}"
},
{
"code": null,
"e": 1962,
"s": 1874,
"text": "Jenifer\nAngelina\nVera\nNode added at the first position...\nNatalie\nJenifer\nAngelina\nVera"
}
] |
Perl | Array pop() Function - GeeksforGeeks
|
07 May, 2019
pop() function in Perl returns the last element of Array passed to it as an argument, removing that value from the array. Note that the value passed to it must explicitly be an array, not a list.
Syntax:pop(Array)
Returns:undef if list is empty else last element from the array.
Example 1:
#!/usr/bin/perl -w # Defining an array of integers@array = (10, 20, 30, 40); # Calling the pop function$popped_element = pop(@array); # Printing the Popped elementprint "Popped element is $popped_element"; # Printing the resultant arrayprint "\nResultant array after pop(): \n@array";
Popped element is 40
Resultant array after pop():
10 20 30
Example 2:
#!/usr/bin/perl -w # Defining an array of strings@array = ("Geeks", "For", "Geeks", "Best"); # Calling the pop function$popped_element = pop(@array); # Printing the Popped elementprint "Popped element is $popped_element"; # Printing the resultant arrayprint "\nResultant array after pop(): \n@array";
Popped element is Best
Resultant array after pop():
Geeks For Geeks
Perl-Array-Functions
Perl-Arrays
Perl-function
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Writing to a File
Perl Tutorial - Learn Perl With Examples
Perl | Operators | Set - 1
Perl | Multidimensional Hashes
Perl | Reading Excel Files
Perl | File Handling Introduction
Perl | index() Function
Perl | Data Types
Perl | shift() Function
Perl | Appending to a File
|
[
{
"code": null,
"e": 23990,
"s": 23962,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 24186,
"s": 23990,
"text": "pop() function in Perl returns the last element of Array passed to it as an argument, removing that value from the array. Note that the value passed to it must explicitly be an array, not a list."
},
{
"code": null,
"e": 24204,
"s": 24186,
"text": "Syntax:pop(Array)"
},
{
"code": null,
"e": 24269,
"s": 24204,
"text": "Returns:undef if list is empty else last element from the array."
},
{
"code": null,
"e": 24280,
"s": 24269,
"text": "Example 1:"
},
{
"code": "#!/usr/bin/perl -w # Defining an array of integers@array = (10, 20, 30, 40); # Calling the pop function$popped_element = pop(@array); # Printing the Popped elementprint \"Popped element is $popped_element\"; # Printing the resultant arrayprint \"\\nResultant array after pop(): \\n@array\";",
"e": 24569,
"s": 24280,
"text": null
},
{
"code": null,
"e": 24630,
"s": 24569,
"text": "Popped element is 40\nResultant array after pop(): \n10 20 30\n"
},
{
"code": null,
"e": 24641,
"s": 24630,
"text": "Example 2:"
},
{
"code": "#!/usr/bin/perl -w # Defining an array of strings@array = (\"Geeks\", \"For\", \"Geeks\", \"Best\"); # Calling the pop function$popped_element = pop(@array); # Printing the Popped elementprint \"Popped element is $popped_element\"; # Printing the resultant arrayprint \"\\nResultant array after pop(): \\n@array\";",
"e": 24946,
"s": 24641,
"text": null
},
{
"code": null,
"e": 25016,
"s": 24946,
"text": "Popped element is Best\nResultant array after pop(): \nGeeks For Geeks\n"
},
{
"code": null,
"e": 25037,
"s": 25016,
"text": "Perl-Array-Functions"
},
{
"code": null,
"e": 25049,
"s": 25037,
"text": "Perl-Arrays"
},
{
"code": null,
"e": 25063,
"s": 25049,
"text": "Perl-function"
},
{
"code": null,
"e": 25068,
"s": 25063,
"text": "Perl"
},
{
"code": null,
"e": 25073,
"s": 25068,
"text": "Perl"
},
{
"code": null,
"e": 25171,
"s": 25073,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25180,
"s": 25171,
"text": "Comments"
},
{
"code": null,
"e": 25193,
"s": 25180,
"text": "Old Comments"
},
{
"code": null,
"e": 25218,
"s": 25193,
"text": "Perl | Writing to a File"
},
{
"code": null,
"e": 25259,
"s": 25218,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 25286,
"s": 25259,
"text": "Perl | Operators | Set - 1"
},
{
"code": null,
"e": 25317,
"s": 25286,
"text": "Perl | Multidimensional Hashes"
},
{
"code": null,
"e": 25344,
"s": 25317,
"text": "Perl | Reading Excel Files"
},
{
"code": null,
"e": 25378,
"s": 25344,
"text": "Perl | File Handling Introduction"
},
{
"code": null,
"e": 25402,
"s": 25378,
"text": "Perl | index() Function"
},
{
"code": null,
"e": 25420,
"s": 25402,
"text": "Perl | Data Types"
},
{
"code": null,
"e": 25444,
"s": 25420,
"text": "Perl | shift() Function"
}
] |
Counting the number of non-NaN elements in a NumPy Array - GeeksforGeeks
|
17 Oct, 2021
In this article, we are going to see how to count the number of non-NaN elements in a NumPy array in Python.
NAN: It is used when you don’t care what the value is at that position. Maybe sometimes is used in place of missing data, or corrupted data.
In this example, we will use one-dimensional arrays. In the below-given code, we loop over every entry of the given NumPy array and check if the value is a NaN or not.
Python3
import numpy as np ex1 = np.array([1, 4, -9, np.nan])ex2 = np.array([1, 45, -2, np.nan, 3, -np.nan, 3, np.nan]) def approach_1(data): # here the input data, is a numpy ndarray # initialize the number of non-NaN elements # in data count = 0 # loop over each entry of the data for entry in data: # check whether the entry is a non-NaN value # or not if not np.isnan(entry): # if not NaN, increment "count" by 1 count += 1 return count print(approach_1(ex1))print(approach_1(ex2))
Output:
3
5
Using the functionality of NumPy arrays, that we can perform an operation on the whole array at once, instead of a single element.
Used function:
np.isnan(data): Returns a boolean array after performing np.isnan() operation on of the entries of the array, data
np.sum(): Since we are inputting a boolean array to the sum function, it returns the number of True values (1s) in the bool array.
Python3
import numpy as np ex3 = np.array([[3, 4, -390, np.nan], [np.nan, np.nan, np.nan, -90]]) def approach_2(data): return np.sum(~np.isnan(data)) print(approach_2(ex3))
Output:
4
numpy.count_nonzero() function counts the number of non-zero values in the array arr.
Syntax : numpy.count_nonzero(arr, axis=None)
Parameters :arr : [array_like] The array for which to count non-zeros.axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of arr.
Return : [int or array of int] Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned.
Python3
import numpy as np ex4 = np.array([[0.35834379, 0.67202438, np.nan, np.nan, np.nan, 0.47870971], [np.nan, np.nan, np.nan, 0.08113384, 0.70511741, 0.15260996], [0.09028477, np.nan, 0.16639899, 0.47740582, 0.7259116, 0.94797347], [0.80305651, np.nan, 0.67949724, 0.84112054, 0.15951702, 0.07510587], [0.28643337, 0.00804256, 0.36775056, 0.19360266, 0.07288145, 0.37076932]]) def approach_3(data): return data.size - np.count_nonzero(np.isnan(data)) print(approach_3(ex4))
Output:
22
Picked
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n17 Oct, 2021"
},
{
"code": null,
"e": 24010,
"s": 23901,
"text": "In this article, we are going to see how to count the number of non-NaN elements in a NumPy array in Python."
},
{
"code": null,
"e": 24152,
"s": 24010,
"text": "NAN: It is used when you don’t care what the value is at that position. Maybe sometimes is used in place of missing data, or corrupted data. "
},
{
"code": null,
"e": 24320,
"s": 24152,
"text": "In this example, we will use one-dimensional arrays. In the below-given code, we loop over every entry of the given NumPy array and check if the value is a NaN or not."
},
{
"code": null,
"e": 24328,
"s": 24320,
"text": "Python3"
},
{
"code": "import numpy as np ex1 = np.array([1, 4, -9, np.nan])ex2 = np.array([1, 45, -2, np.nan, 3, -np.nan, 3, np.nan]) def approach_1(data): # here the input data, is a numpy ndarray # initialize the number of non-NaN elements # in data count = 0 # loop over each entry of the data for entry in data: # check whether the entry is a non-NaN value # or not if not np.isnan(entry): # if not NaN, increment \"count\" by 1 count += 1 return count print(approach_1(ex1))print(approach_1(ex2))",
"e": 24964,
"s": 24328,
"text": null
},
{
"code": null,
"e": 24972,
"s": 24964,
"text": "Output:"
},
{
"code": null,
"e": 24976,
"s": 24972,
"text": "3\n5"
},
{
"code": null,
"e": 25107,
"s": 24976,
"text": "Using the functionality of NumPy arrays, that we can perform an operation on the whole array at once, instead of a single element."
},
{
"code": null,
"e": 25122,
"s": 25107,
"text": "Used function:"
},
{
"code": null,
"e": 25237,
"s": 25122,
"text": "np.isnan(data): Returns a boolean array after performing np.isnan() operation on of the entries of the array, data"
},
{
"code": null,
"e": 25368,
"s": 25237,
"text": "np.sum(): Since we are inputting a boolean array to the sum function, it returns the number of True values (1s) in the bool array."
},
{
"code": null,
"e": 25376,
"s": 25368,
"text": "Python3"
},
{
"code": "import numpy as np ex3 = np.array([[3, 4, -390, np.nan], [np.nan, np.nan, np.nan, -90]]) def approach_2(data): return np.sum(~np.isnan(data)) print(approach_2(ex3))",
"e": 25563,
"s": 25376,
"text": null
},
{
"code": null,
"e": 25571,
"s": 25563,
"text": "Output:"
},
{
"code": null,
"e": 25573,
"s": 25571,
"text": "4"
},
{
"code": null,
"e": 25659,
"s": 25573,
"text": "numpy.count_nonzero() function counts the number of non-zero values in the array arr."
},
{
"code": null,
"e": 25704,
"s": 25659,
"text": "Syntax : numpy.count_nonzero(arr, axis=None)"
},
{
"code": null,
"e": 25950,
"s": 25704,
"text": "Parameters :arr : [array_like] The array for which to count non-zeros.axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of arr."
},
{
"code": null,
"e": 26113,
"s": 25950,
"text": "Return : [int or array of int] Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned."
},
{
"code": null,
"e": 26121,
"s": 26113,
"text": "Python3"
},
{
"code": "import numpy as np ex4 = np.array([[0.35834379, 0.67202438, np.nan, np.nan, np.nan, 0.47870971], [np.nan, np.nan, np.nan, 0.08113384, 0.70511741, 0.15260996], [0.09028477, np.nan, 0.16639899, 0.47740582, 0.7259116, 0.94797347], [0.80305651, np.nan, 0.67949724, 0.84112054, 0.15951702, 0.07510587], [0.28643337, 0.00804256, 0.36775056, 0.19360266, 0.07288145, 0.37076932]]) def approach_3(data): return data.size - np.count_nonzero(np.isnan(data)) print(approach_3(ex4))",
"e": 26748,
"s": 26121,
"text": null
},
{
"code": null,
"e": 26756,
"s": 26748,
"text": "Output:"
},
{
"code": null,
"e": 26759,
"s": 26756,
"text": "22"
},
{
"code": null,
"e": 26766,
"s": 26759,
"text": "Picked"
},
{
"code": null,
"e": 26797,
"s": 26766,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 26810,
"s": 26797,
"text": "Python-numpy"
},
{
"code": null,
"e": 26817,
"s": 26810,
"text": "Python"
},
{
"code": null,
"e": 26915,
"s": 26817,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26924,
"s": 26915,
"text": "Comments"
},
{
"code": null,
"e": 26937,
"s": 26924,
"text": "Old Comments"
},
{
"code": null,
"e": 26973,
"s": 26937,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 26996,
"s": 26973,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 27035,
"s": 26996,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27068,
"s": 27035,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 27117,
"s": 27068,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 27158,
"s": 27117,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 27174,
"s": 27158,
"text": "loops in python"
},
{
"code": null,
"e": 27225,
"s": 27174,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 27257,
"s": 27225,
"text": "Python Dictionary keys() method"
}
] |
java.util.zip - GZIPOutputStream Class
|
The java.util.zip.GZIPOutputStream class implements a stream filter for writing compressed data in the GZIP file format.
Following is the declaration for java.util.zip.GZIPOutputStream class −
public class GZIPOutputStream
extends DeflaterOutputStream
Following are the fields for java.util.zip.GZIPOutputStream class −
protected CRC32 crc − CRC-32 for uncompressed data.
protected CRC32 crc − CRC-32 for uncompressed data.
GZIPOutputStream(OutputStream out)
Creates a new output stream with a default buffer size.
GZIPOutputStream(OutputStream out, boolean syncFlush)
Creates a new output stream with a default buffer size and the specified flush mode.
GZIPOutputStream(OutputStream out, int size)
Creates a new output stream with the specified buffer size.
GZIPOutputStream(OutputStream out, int size, boolean syncFlush)
Creates a new output stream with the specified buffer size and flush mode.
Finishes writing compressed data to the output stream without closing the underlying stream.
Writes array of bytes to the compressed output stream.
This class inherits methods from the following classes −
java.util.zip.DeflaterOutputStream
java.io.FilterOutputStream
java.lang.Object
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2313,
"s": 2192,
"text": "The java.util.zip.GZIPOutputStream class implements a stream filter for writing compressed data in the GZIP file format."
},
{
"code": null,
"e": 2385,
"s": 2313,
"text": "Following is the declaration for java.util.zip.GZIPOutputStream class −"
},
{
"code": null,
"e": 2448,
"s": 2385,
"text": "public class GZIPOutputStream\n extends DeflaterOutputStream\n"
},
{
"code": null,
"e": 2516,
"s": 2448,
"text": "Following are the fields for java.util.zip.GZIPOutputStream class −"
},
{
"code": null,
"e": 2568,
"s": 2516,
"text": "protected CRC32 crc − CRC-32 for uncompressed data."
},
{
"code": null,
"e": 2620,
"s": 2568,
"text": "protected CRC32 crc − CRC-32 for uncompressed data."
},
{
"code": null,
"e": 2655,
"s": 2620,
"text": "GZIPOutputStream(OutputStream out)"
},
{
"code": null,
"e": 2711,
"s": 2655,
"text": "Creates a new output stream with a default buffer size."
},
{
"code": null,
"e": 2765,
"s": 2711,
"text": "GZIPOutputStream(OutputStream out, boolean syncFlush)"
},
{
"code": null,
"e": 2850,
"s": 2765,
"text": "Creates a new output stream with a default buffer size and the specified flush mode."
},
{
"code": null,
"e": 2895,
"s": 2850,
"text": "GZIPOutputStream(OutputStream out, int size)"
},
{
"code": null,
"e": 2955,
"s": 2895,
"text": "Creates a new output stream with the specified buffer size."
},
{
"code": null,
"e": 3019,
"s": 2955,
"text": "GZIPOutputStream(OutputStream out, int size, boolean syncFlush)"
},
{
"code": null,
"e": 3094,
"s": 3019,
"text": "Creates a new output stream with the specified buffer size and flush mode."
},
{
"code": null,
"e": 3187,
"s": 3094,
"text": "Finishes writing compressed data to the output stream without closing the underlying stream."
},
{
"code": null,
"e": 3242,
"s": 3187,
"text": "Writes array of bytes to the compressed output stream."
},
{
"code": null,
"e": 3299,
"s": 3242,
"text": "This class inherits methods from the following classes −"
},
{
"code": null,
"e": 3334,
"s": 3299,
"text": "java.util.zip.DeflaterOutputStream"
},
{
"code": null,
"e": 3361,
"s": 3334,
"text": "java.io.FilterOutputStream"
},
{
"code": null,
"e": 3378,
"s": 3361,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3385,
"s": 3378,
"text": " Print"
},
{
"code": null,
"e": 3396,
"s": 3385,
"text": " Add Notes"
}
] |
Finding median for every window in JavaScript
|
Median in mathematics, median is the middle value in an ordered(sorted) integer list.
If the size of the list is even, and there is no middle value. Median is the mean (average) of the two middle values.
We are required to write a JavaScript function that takes in an array of Integers, arr, as the first argument and a number num (num <= length of array arr) as the second argument.
Now for each window of size num in the array arr, our function should calculate the median and push that median value into a new array and finally at the end of iteration return that median array.
For example, if the input to the function is −
const arr = [5, 3, 7, 5, 3, 1, 8, 9, 2, 4, 6, 8];
const num = 3;
Then the output should be −
const output = [5, 5, 5, 3, 3, 8, 8, 4, 4, 6];
The code for this will be −
Live Demo
const arr = [5, 3, 7, 5, 3, 1, 8, 9, 2, 4, 6, 8];
const num = 3;
const binarySearch = (arr, target, l, r) => {
while (l < r) {
const mid = Math.floor((l + r) / 2);
if (arr[mid] < target) l = mid + 1;
else if (arr[mid] > target) r = mid;
else return mid;
};
if (l === r) return arr[l] >= target ? l : l + 1;
}
const medianSlidingWindow = (arr = [], num = 1) => {
let l = 0, r = num - 1, res = [];
const window = arr.slice(l, num);
window.sort((a, b) => a - b);
while (r < arr.length) {
const median = num % 2 === 0 ? (window[Math.floor(num / 2) - 1] + window[Math.floor(num / 2)]) / 2 : window[Math.floor(num / 2)];
res.push(median);
let char = arr[l++];
let index = binarySearch(window, char, 0, window.length - 1);
window.splice(index, 1);
char = arr[++r];
index = binarySearch(window, char, 0, window.length - 1);
window.splice(index, 0, char);
}
return res;
};
console.log(medianSlidingWindow(arr, num));
Idea behind this solution is to use binary search to insert right number and remove left number when moving the sliding window to the right.
And the output in the console will be −
[5, 5, 5, 3, 3, 8, 8, 4, 4, 6 ]
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "Median in mathematics, median is the middle value in an ordered(sorted) integer list."
},
{
"code": null,
"e": 1266,
"s": 1148,
"text": "If the size of the list is even, and there is no middle value. Median is the mean (average) of the two middle values."
},
{
"code": null,
"e": 1446,
"s": 1266,
"text": "We are required to write a JavaScript function that takes in an array of Integers, arr, as the first argument and a number num (num <= length of array arr) as the second argument."
},
{
"code": null,
"e": 1643,
"s": 1446,
"text": "Now for each window of size num in the array arr, our function should calculate the median and push that median value into a new array and finally at the end of iteration return that median array."
},
{
"code": null,
"e": 1690,
"s": 1643,
"text": "For example, if the input to the function is −"
},
{
"code": null,
"e": 1755,
"s": 1690,
"text": "const arr = [5, 3, 7, 5, 3, 1, 8, 9, 2, 4, 6, 8];\nconst num = 3;"
},
{
"code": null,
"e": 1783,
"s": 1755,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1830,
"s": 1783,
"text": "const output = [5, 5, 5, 3, 3, 8, 8, 4, 4, 6];"
},
{
"code": null,
"e": 1858,
"s": 1830,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1869,
"s": 1858,
"text": " Live Demo"
},
{
"code": null,
"e": 2876,
"s": 1869,
"text": "const arr = [5, 3, 7, 5, 3, 1, 8, 9, 2, 4, 6, 8];\nconst num = 3;\nconst binarySearch = (arr, target, l, r) => {\n while (l < r) {\n const mid = Math.floor((l + r) / 2);\n if (arr[mid] < target) l = mid + 1;\n else if (arr[mid] > target) r = mid;\n else return mid;\n };\n if (l === r) return arr[l] >= target ? l : l + 1;\n}\nconst medianSlidingWindow = (arr = [], num = 1) => {\n let l = 0, r = num - 1, res = [];\n const window = arr.slice(l, num);\n window.sort((a, b) => a - b);\n while (r < arr.length) {\n const median = num % 2 === 0 ? (window[Math.floor(num / 2) - 1] + window[Math.floor(num / 2)]) / 2 : window[Math.floor(num / 2)];\n res.push(median);\n let char = arr[l++];\n let index = binarySearch(window, char, 0, window.length - 1);\n window.splice(index, 1);\n char = arr[++r];\n index = binarySearch(window, char, 0, window.length - 1);\n window.splice(index, 0, char);\n }\n return res;\n};\nconsole.log(medianSlidingWindow(arr, num));"
},
{
"code": null,
"e": 3017,
"s": 2876,
"text": "Idea behind this solution is to use binary search to insert right number and remove left number when moving the sliding window to the right."
},
{
"code": null,
"e": 3057,
"s": 3017,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 3089,
"s": 3057,
"text": "[5, 5, 5, 3, 3, 8, 8, 4, 4, 6 ]"
}
] |
How to Detect User Inactivity in Android? - GeeksforGeeks
|
11 Aug, 2021
It is important to detect user inactivity in applications that display or contain private credentials, such as social apps, banking apps, wallet apps, etc. In such applications, there is a login session that authenticates log-in credentials. Once the session starts, the user can perform desired actions. However, if the screen is unused for a long time, it is necessary for the application to start displaying alerts or log the user out of the current session, user inactivity being the grounds for logging out. So, there must have been a timer or counter running in the background, that counted the user inactivity for some specified time.
So, through this article, we will show you how you could detect user inactivity by knowing when the user last touched the screen and instantly starting a counter for a specific time.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Change the background of the layout to a darker color. We changed the background to black as we wanted to show touch impressions on the screen.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black" tools:context=".MainActivity"></RelativeLayout>
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Handlerimport android.os.Looperimport android.view.MotionEventimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toast class MainActivity : AppCompatActivity() { // Declaring handler, runnable and time in milli seconds private lateinit var mHandler: Handler private lateinit var mRunnable: Runnable private var mTime: Long = 2000 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initializing the handler and the runnable mHandler = Handler(Looper.getMainLooper()) mRunnable = Runnable { Toast.makeText(applicationContext, "User inactive for ${mTime/1000} secs!", Toast.LENGTH_SHORT).show() } // Start the handler startHandler() } // When the screen is touched or motion is detected override fun onTouchEvent(event: MotionEvent?): Boolean { // Removes the handler callbacks (if any) stopHandler() // Runs the handler (for the specified time) // If any touch or motion is detected before // the specified time, this override function is again called startHandler() return super.onTouchEvent(event) } // start handler function private fun startHandler(){ mHandler.postDelayed(mRunnable, mTime) } // stop handler function private fun stopHandler(){ mHandler.removeCallbacks(mRunnable) }}
Output:
You can see that if the screen is untouched for 2 seconds, the application displays a message regarding user inactivity.
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 25367,
"s": 24725,
"text": "It is important to detect user inactivity in applications that display or contain private credentials, such as social apps, banking apps, wallet apps, etc. In such applications, there is a login session that authenticates log-in credentials. Once the session starts, the user can perform desired actions. However, if the screen is unused for a long time, it is necessary for the application to start displaying alerts or log the user out of the current session, user inactivity being the grounds for logging out. So, there must have been a timer or counter running in the background, that counted the user inactivity for some specified time."
},
{
"code": null,
"e": 25550,
"s": 25367,
"text": "So, through this article, we will show you how you could detect user inactivity by knowing when the user last touched the screen and instantly starting a counter for a specific time."
},
{
"code": null,
"e": 25597,
"s": 25550,
"text": "Step 1: Create a New Project in Android Studio"
},
{
"code": null,
"e": 25836,
"s": 25597,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project."
},
{
"code": null,
"e": 25884,
"s": 25836,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26170,
"s": 25884,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Change the background of the layout to a darker color. We changed the background to black as we wanted to show touch impressions on the screen."
},
{
"code": null,
"e": 26174,
"s": 26170,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black\" tools:context=\".MainActivity\"></RelativeLayout>",
"e": 26563,
"s": 26174,
"text": null
},
{
"code": null,
"e": 26609,
"s": 26563,
"text": "Step 3: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 26795,
"s": 26609,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 26802,
"s": 26795,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Handlerimport android.os.Looperimport android.view.MotionEventimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toast class MainActivity : AppCompatActivity() { // Declaring handler, runnable and time in milli seconds private lateinit var mHandler: Handler private lateinit var mRunnable: Runnable private var mTime: Long = 2000 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initializing the handler and the runnable mHandler = Handler(Looper.getMainLooper()) mRunnable = Runnable { Toast.makeText(applicationContext, \"User inactive for ${mTime/1000} secs!\", Toast.LENGTH_SHORT).show() } // Start the handler startHandler() } // When the screen is touched or motion is detected override fun onTouchEvent(event: MotionEvent?): Boolean { // Removes the handler callbacks (if any) stopHandler() // Runs the handler (for the specified time) // If any touch or motion is detected before // the specified time, this override function is again called startHandler() return super.onTouchEvent(event) } // start handler function private fun startHandler(){ mHandler.postDelayed(mRunnable, mTime) } // stop handler function private fun stopHandler(){ mHandler.removeCallbacks(mRunnable) }}",
"e": 28382,
"s": 26802,
"text": null
},
{
"code": null,
"e": 28390,
"s": 28382,
"text": "Output:"
},
{
"code": null,
"e": 28511,
"s": 28390,
"text": "You can see that if the screen is untouched for 2 seconds, the application displays a message regarding user inactivity."
},
{
"code": null,
"e": 28519,
"s": 28511,
"text": "Android"
},
{
"code": null,
"e": 28526,
"s": 28519,
"text": "Kotlin"
},
{
"code": null,
"e": 28534,
"s": 28526,
"text": "Android"
},
{
"code": null,
"e": 28632,
"s": 28534,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28641,
"s": 28632,
"text": "Comments"
},
{
"code": null,
"e": 28654,
"s": 28641,
"text": "Old Comments"
},
{
"code": null,
"e": 28693,
"s": 28654,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28743,
"s": 28693,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 28781,
"s": 28743,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 28832,
"s": 28781,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 28874,
"s": 28832,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 28893,
"s": 28874,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 28906,
"s": 28893,
"text": "Kotlin Array"
},
{
"code": null,
"e": 28948,
"s": 28906,
"text": "Retrofit with Kotlin Coroutine in Android"
}
] |
Share WhatsApp Web without Scanning QR code using Python - GeeksforGeeks
|
23 Aug, 2021
Prerequisite: Selenium, Browser Automation Using Selenium
In this article, we are going to see how to share your Web-WhatsApp with anyone over the Internet without Scanning a QR code.
Web Whatsapp stores sessions in IndexedDB with the name wawc and syncs those key-value pairs to local storage. IndexedDB stores the data inside the user’s browser and allows to create web application that can query from this indexedDB with or without a network connection.
We can figure it out by trying the following. We will take help of chrome dev tool.
Steps:
Clear cookies and refresh the page: It will remain login.Clear localStorage and refresh the page: It will restore the local Storage and remain logged in.Clear IndexedDB and refresh the page: It will restore the IndexedDB and remain logged in.Now clear both localStorage and IndexedDB: It will log out.
Clear cookies and refresh the page: It will remain login.
Clear localStorage and refresh the page: It will restore the local Storage and remain logged in.
Clear IndexedDB and refresh the page: It will restore the IndexedDB and remain logged in.
Now clear both localStorage and IndexedDB: It will log out.
Steps demonstration:
We can extract sessions from IndexedDB by using the following javascript.
Javascript
function getResultFromRequest(request) { return new Promise((resolve, reject) => { request.onsuccess = function (event) { resolve(request.result); }; });} async function getDB() { var request = window.indexedDB.open("wawc"); return await getResultFromRequest(request);} async function readAllKeyValuePairs() { var db = await getDB(); var objectStore = db.transaction("user").objectStore("user"); var request = objectStore.getAll(); return await getResultFromRequest(request);} session = await readAllKeyValuePairs();console.log(session);
We can try to execute the above code in the browser’s console or tab where we had opened Web-Whatsapp and we will see the output as follows containing session key-value pairs.
Now we get those key-value pairs as text by running the following line of code.
Javascript
JSON.stringify(session);
Now let’s copy that text to a file to save a session and clear both localStorage and IndexedDB to log out. Now we can run the following code to inject a session by assigning the value of the session string we just copied to a file to variable SESSION_STRING. Then refresh the page and we will log in again without scanning the QR code.
Javascript
function getResultFromRequest(request) { return new Promise((resolve, reject) => { request.onsuccess = function(event) { resolve(request.result); }; })} async function getDB() { var request = window.indexedDB.open("wawc"); return await getResultFromRequest(request);} async function injectSession(SESSION_STRING) { var session = JSON.parse(SESSION_STRING); var db = await getDB(); var objectStore = db.transaction("user", "readwrite").objectStore("user"); for(var keyValue of session) { var request = objectStore.put(keyValue); await getResultFromRequest(request); }} var SESSION_STRING = "";await injectSession(SESSION_STRING);
We can automate the process of generating a session file that contains our session key-value pairs and also reading session key-value pairs from that generated session file to inject a session into the browser to open web-WhatsApp without scanning QR code
Take the session file path as a command-line argument.
Open Chrome browser.
Open Web Whatsapp.
Ask the user to scan the QR code.
Wait for the QR code to be scanned.
Execute javascript in the browser and extract the session.
Save the file with a session text file with the custom file extension “.wa”.
Close the browser.
Verify that the session file exists.
Read the given file into the “session” variable.
Open Chrome browser.
Open Web Whatsapp.
Wait for Web Whatsapp to be loaded properly.
Execute javascript in browser to inject session by using variable “session”.
Refresh the page.
Ask for the user to press enter key to close the browser.
Below is the implementation:
Note: Please download chormedrive before running the code.
By using selenium’s WebDriverWait, we can wait for some elements to be present on the browser as following:
Python3
def _wait_for_presence_of_an_element(browser, selector): element = None try: element = WebDriverWait(browser, DEFAULT_WAIT).until( EC.presence_of_element_located(selector) ) except: pass finally: return element
Python3
def sessionGenerator(sessionFilePath): # 1.1 Open Chrome browser browser = webdriver.Chrome() # 1.2 Open Web Whatsapp browser.get("https://web.whatsapp.com/") # 1.3 Ask user to scan QR code print("Waiting for QR code scan...") # 1.4 Wait for QR code to be scanned _wait_for_presence_of_an_element( browser, MAIN_SEARCH_BAR__SEARCH_ICON) # 1.5 Execute javascript in browser and # extract the session text session = browser.execute_script(EXTRACT_SESSION) # 1.6 Save file with session text file with # custom file extension ".wa" with open(sessionFilePath, "w", encoding="utf-8") as sessionFile: sessionFile.write(str(session)) print("Your session file is saved to: " + sessionFilePath) # 1.7 Close the browser browser.close()
Use the above methods for Generating session file:
Python3
from session import *import sys # Taked session file path as command line# argument and passed to following methodsessionFilePath = sys.argv[1] sessionGenerator(sessionFilePath)
Python3
def sessionOpener(sessionFilePath): # 2.1 Verify that session file is exist if sessionFilePath == "": raise IOError('"' + sessionFilePath + '" is not exist.') # 2.2 Read the given file into "session" variable with open(sessionFilePath, "r", encoding="utf-8") as sessionFile: session = sessionFile.read() # 2.3 Open Chrome browser browser = webdriver.Chrome() # 2.4 Open Web Whatsapp browser.get("https://web.whatsapp.com/") # 2.5 Wait for Web Whatsapp to be loaded properly _wait_for_presence_of_an_element(browser, QR_CODE) # 2.6 Execute javascript in browser to inject # session by using vaarible "session" print("Injecting session...") browser.execute_script(INJECT_SESSION, session) # 2.7 Refresh the page browser.refresh() # 2.8 Ask for user to enter any key to close browser input("Press enter to close browser.")
Use the above methods for Opening session file:
Python3
from session import *import sys # Taked session file path as command line # argument and passed to following methodsessionFilePath = sys.argv[1] sessionOpener(sessionFilePath)
We can generate a session file by using the following command:
For Generating session file:
python session_generator.py session.wa
After generating the session file then share it with someone and put that session file in the same folder where session_opener.py is located and run the following command to open the Web Whatsapp without scanning the QR code
For Opening session file:
python session_opener.py session.wa
OR open PowerShell normally without going to the folder and give absolute paths as following
python E:\share-web-whatsapp\session_generator.py E:\share-web-whatsapp\session.wa
python E:\share-web-whatsapp\session_opener.py E:\share-web-whatsapp\session.wa
Python-projects
Python-selenium
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24236,
"s": 24208,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 24294,
"s": 24236,
"text": "Prerequisite: Selenium, Browser Automation Using Selenium"
},
{
"code": null,
"e": 24420,
"s": 24294,
"text": "In this article, we are going to see how to share your Web-WhatsApp with anyone over the Internet without Scanning a QR code."
},
{
"code": null,
"e": 24694,
"s": 24420,
"text": "Web Whatsapp stores sessions in IndexedDB with the name wawc and syncs those key-value pairs to local storage. IndexedDB stores the data inside the user’s browser and allows to create web application that can query from this indexedDB with or without a network connection. "
},
{
"code": null,
"e": 24778,
"s": 24694,
"text": "We can figure it out by trying the following. We will take help of chrome dev tool."
},
{
"code": null,
"e": 24785,
"s": 24778,
"text": "Steps:"
},
{
"code": null,
"e": 25087,
"s": 24785,
"text": "Clear cookies and refresh the page: It will remain login.Clear localStorage and refresh the page: It will restore the local Storage and remain logged in.Clear IndexedDB and refresh the page: It will restore the IndexedDB and remain logged in.Now clear both localStorage and IndexedDB: It will log out."
},
{
"code": null,
"e": 25145,
"s": 25087,
"text": "Clear cookies and refresh the page: It will remain login."
},
{
"code": null,
"e": 25242,
"s": 25145,
"text": "Clear localStorage and refresh the page: It will restore the local Storage and remain logged in."
},
{
"code": null,
"e": 25332,
"s": 25242,
"text": "Clear IndexedDB and refresh the page: It will restore the IndexedDB and remain logged in."
},
{
"code": null,
"e": 25392,
"s": 25332,
"text": "Now clear both localStorage and IndexedDB: It will log out."
},
{
"code": null,
"e": 25413,
"s": 25392,
"text": "Steps demonstration:"
},
{
"code": null,
"e": 25488,
"s": 25413,
"text": "We can extract sessions from IndexedDB by using the following javascript. "
},
{
"code": null,
"e": 25499,
"s": 25488,
"text": "Javascript"
},
{
"code": "function getResultFromRequest(request) { return new Promise((resolve, reject) => { request.onsuccess = function (event) { resolve(request.result); }; });} async function getDB() { var request = window.indexedDB.open(\"wawc\"); return await getResultFromRequest(request);} async function readAllKeyValuePairs() { var db = await getDB(); var objectStore = db.transaction(\"user\").objectStore(\"user\"); var request = objectStore.getAll(); return await getResultFromRequest(request);} session = await readAllKeyValuePairs();console.log(session);",
"e": 26095,
"s": 25499,
"text": null
},
{
"code": null,
"e": 26272,
"s": 26095,
"text": "We can try to execute the above code in the browser’s console or tab where we had opened Web-Whatsapp and we will see the output as follows containing session key-value pairs. "
},
{
"code": null,
"e": 26352,
"s": 26272,
"text": "Now we get those key-value pairs as text by running the following line of code."
},
{
"code": null,
"e": 26363,
"s": 26352,
"text": "Javascript"
},
{
"code": "JSON.stringify(session);",
"e": 26388,
"s": 26363,
"text": null
},
{
"code": null,
"e": 26725,
"s": 26388,
"text": "Now let’s copy that text to a file to save a session and clear both localStorage and IndexedDB to log out. Now we can run the following code to inject a session by assigning the value of the session string we just copied to a file to variable SESSION_STRING. Then refresh the page and we will log in again without scanning the QR code. "
},
{
"code": null,
"e": 26736,
"s": 26725,
"text": "Javascript"
},
{
"code": "function getResultFromRequest(request) { return new Promise((resolve, reject) => { request.onsuccess = function(event) { resolve(request.result); }; })} async function getDB() { var request = window.indexedDB.open(\"wawc\"); return await getResultFromRequest(request);} async function injectSession(SESSION_STRING) { var session = JSON.parse(SESSION_STRING); var db = await getDB(); var objectStore = db.transaction(\"user\", \"readwrite\").objectStore(\"user\"); for(var keyValue of session) { var request = objectStore.put(keyValue); await getResultFromRequest(request); }} var SESSION_STRING = \"\";await injectSession(SESSION_STRING);",
"e": 27437,
"s": 26736,
"text": null
},
{
"code": null,
"e": 27695,
"s": 27439,
"text": "We can automate the process of generating a session file that contains our session key-value pairs and also reading session key-value pairs from that generated session file to inject a session into the browser to open web-WhatsApp without scanning QR code"
},
{
"code": null,
"e": 27750,
"s": 27695,
"text": "Take the session file path as a command-line argument."
},
{
"code": null,
"e": 27772,
"s": 27750,
"text": "Open Chrome browser. "
},
{
"code": null,
"e": 27791,
"s": 27772,
"text": "Open Web Whatsapp."
},
{
"code": null,
"e": 27825,
"s": 27791,
"text": "Ask the user to scan the QR code."
},
{
"code": null,
"e": 27861,
"s": 27825,
"text": "Wait for the QR code to be scanned."
},
{
"code": null,
"e": 27920,
"s": 27861,
"text": "Execute javascript in the browser and extract the session."
},
{
"code": null,
"e": 27997,
"s": 27920,
"text": "Save the file with a session text file with the custom file extension “.wa”."
},
{
"code": null,
"e": 28016,
"s": 27997,
"text": "Close the browser."
},
{
"code": null,
"e": 28053,
"s": 28016,
"text": "Verify that the session file exists."
},
{
"code": null,
"e": 28103,
"s": 28053,
"text": "Read the given file into the “session” variable. "
},
{
"code": null,
"e": 28124,
"s": 28103,
"text": "Open Chrome browser."
},
{
"code": null,
"e": 28143,
"s": 28124,
"text": "Open Web Whatsapp."
},
{
"code": null,
"e": 28188,
"s": 28143,
"text": "Wait for Web Whatsapp to be loaded properly."
},
{
"code": null,
"e": 28265,
"s": 28188,
"text": "Execute javascript in browser to inject session by using variable “session”."
},
{
"code": null,
"e": 28283,
"s": 28265,
"text": "Refresh the page."
},
{
"code": null,
"e": 28341,
"s": 28283,
"text": "Ask for the user to press enter key to close the browser."
},
{
"code": null,
"e": 28370,
"s": 28341,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 28429,
"s": 28370,
"text": "Note: Please download chormedrive before running the code."
},
{
"code": null,
"e": 28537,
"s": 28429,
"text": "By using selenium’s WebDriverWait, we can wait for some elements to be present on the browser as following:"
},
{
"code": null,
"e": 28545,
"s": 28537,
"text": "Python3"
},
{
"code": "def _wait_for_presence_of_an_element(browser, selector): element = None try: element = WebDriverWait(browser, DEFAULT_WAIT).until( EC.presence_of_element_located(selector) ) except: pass finally: return element",
"e": 28813,
"s": 28545,
"text": null
},
{
"code": null,
"e": 28821,
"s": 28813,
"text": "Python3"
},
{
"code": "def sessionGenerator(sessionFilePath): # 1.1 Open Chrome browser browser = webdriver.Chrome() # 1.2 Open Web Whatsapp browser.get(\"https://web.whatsapp.com/\") # 1.3 Ask user to scan QR code print(\"Waiting for QR code scan...\") # 1.4 Wait for QR code to be scanned _wait_for_presence_of_an_element( browser, MAIN_SEARCH_BAR__SEARCH_ICON) # 1.5 Execute javascript in browser and # extract the session text session = browser.execute_script(EXTRACT_SESSION) # 1.6 Save file with session text file with # custom file extension \".wa\" with open(sessionFilePath, \"w\", encoding=\"utf-8\") as sessionFile: sessionFile.write(str(session)) print(\"Your session file is saved to: \" + sessionFilePath) # 1.7 Close the browser browser.close()",
"e": 29626,
"s": 28821,
"text": null
},
{
"code": null,
"e": 29677,
"s": 29626,
"text": "Use the above methods for Generating session file:"
},
{
"code": null,
"e": 29685,
"s": 29677,
"text": "Python3"
},
{
"code": "from session import *import sys # Taked session file path as command line# argument and passed to following methodsessionFilePath = sys.argv[1] sessionGenerator(sessionFilePath)",
"e": 29865,
"s": 29685,
"text": null
},
{
"code": null,
"e": 29873,
"s": 29865,
"text": "Python3"
},
{
"code": "def sessionOpener(sessionFilePath): # 2.1 Verify that session file is exist if sessionFilePath == \"\": raise IOError('\"' + sessionFilePath + '\" is not exist.') # 2.2 Read the given file into \"session\" variable with open(sessionFilePath, \"r\", encoding=\"utf-8\") as sessionFile: session = sessionFile.read() # 2.3 Open Chrome browser browser = webdriver.Chrome() # 2.4 Open Web Whatsapp browser.get(\"https://web.whatsapp.com/\") # 2.5 Wait for Web Whatsapp to be loaded properly _wait_for_presence_of_an_element(browser, QR_CODE) # 2.6 Execute javascript in browser to inject # session by using vaarible \"session\" print(\"Injecting session...\") browser.execute_script(INJECT_SESSION, session) # 2.7 Refresh the page browser.refresh() # 2.8 Ask for user to enter any key to close browser input(\"Press enter to close browser.\")",
"e": 30777,
"s": 29873,
"text": null
},
{
"code": null,
"e": 30825,
"s": 30777,
"text": "Use the above methods for Opening session file:"
},
{
"code": null,
"e": 30833,
"s": 30825,
"text": "Python3"
},
{
"code": "from session import *import sys # Taked session file path as command line # argument and passed to following methodsessionFilePath = sys.argv[1] sessionOpener(sessionFilePath)",
"e": 31011,
"s": 30833,
"text": null
},
{
"code": null,
"e": 31074,
"s": 31011,
"text": "We can generate a session file by using the following command:"
},
{
"code": null,
"e": 31103,
"s": 31074,
"text": "For Generating session file:"
},
{
"code": null,
"e": 31142,
"s": 31103,
"text": "python session_generator.py session.wa"
},
{
"code": null,
"e": 31367,
"s": 31142,
"text": "After generating the session file then share it with someone and put that session file in the same folder where session_opener.py is located and run the following command to open the Web Whatsapp without scanning the QR code"
},
{
"code": null,
"e": 31393,
"s": 31367,
"text": "For Opening session file:"
},
{
"code": null,
"e": 31429,
"s": 31393,
"text": "python session_opener.py session.wa"
},
{
"code": null,
"e": 31522,
"s": 31429,
"text": "OR open PowerShell normally without going to the folder and give absolute paths as following"
},
{
"code": null,
"e": 31605,
"s": 31522,
"text": "python E:\\share-web-whatsapp\\session_generator.py E:\\share-web-whatsapp\\session.wa"
},
{
"code": null,
"e": 31685,
"s": 31605,
"text": "python E:\\share-web-whatsapp\\session_opener.py E:\\share-web-whatsapp\\session.wa"
},
{
"code": null,
"e": 31701,
"s": 31685,
"text": "Python-projects"
},
{
"code": null,
"e": 31717,
"s": 31701,
"text": "Python-selenium"
},
{
"code": null,
"e": 31732,
"s": 31717,
"text": "python-utility"
},
{
"code": null,
"e": 31739,
"s": 31732,
"text": "Python"
},
{
"code": null,
"e": 31837,
"s": 31739,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31846,
"s": 31837,
"text": "Comments"
},
{
"code": null,
"e": 31859,
"s": 31846,
"text": "Old Comments"
},
{
"code": null,
"e": 31891,
"s": 31859,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31947,
"s": 31891,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31968,
"s": 31947,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 32007,
"s": 31968,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 32049,
"s": 32007,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 32076,
"s": 32049,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 32107,
"s": 32076,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 32149,
"s": 32107,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 32185,
"s": 32149,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Reentrant Function - GeeksforGeeks
|
26 Apr, 2018
A function is said to be reentrant if there is a provision to interrupt the function in the course of execution, service the interrupt service routine and then resume the earlier going on function, without hampering its earlier course of action. Reentrant functions are used in applications like hardware interrupt handling, recursion, etc. The function has to satisfy certain conditions to be called as reentrant:1. It may not use global and static data. Though there are no restrictions, but it is generally not advised. because the interrupt may change certain global values and resuming the course of action of the reentrant function with the new data may give undesired results. 2. It should not modify it’s own code. This is important because the course of action of the function should remain the same throughout the code. But, this may be allowed in case the interrupt routine uses a local copy of the reentrant function every time it uses different values or before and after the interrupt. 3. Should not call another non-reentrant function.
Thread safety and Reentrant functionsReentrancy is distinct from, but closely related to, thread-safety. A function can be thread-safe and still not reentrant. For example, a function could be wrapped all around with a mutex (which avoids problems in multithreading environments), but if that function is used in an interrupt service routine, it could starve waiting for the first execution to release the mutex. The key for avoiding confusion is that reentrant refers to only one thread executing. It is a concept from the time when no multitasking operating systems existed. (Source : https://en.wikipedia.org/wiki/Reentrancy_(computing))
Example of Non-Reentrant Functions:
// A non-reentrant example // [The function depends on global variable i] int i; // Both fun1() and fun2() are not reentrant // fun1() is NOT reentrant because it uses global variable iint fun1(){ return i * 5;} // fun2() is NOT reentrant because it calls a non-reentrant// functionint fun2(){ return fun1() * 5;}
Example of Reentrant Functions:In the below code, fun2 is a reentrant function. If an interrupt that pauses its execution and shifts the control to fun1. After fun1 completes, the control is again transferred to fun2 and it reenters the execution phase.
// Both fun1() and fun2() are reentrantint fun1(int i){ return i * 5;} int fun2(int i){ return fun1(i) * 5;}
Article compiled by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
VictorDev
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
Difference between Min Heap and Max Heap
SQL | Date functions
Difference between Class and Object
Implementation of LinkedList in Javascript
Deploy Python Flask App on Heroku
How compare() method works in Java
SQL | CREATE
|
[
{
"code": null,
"e": 24029,
"s": 24001,
"text": "\n26 Apr, 2018"
},
{
"code": null,
"e": 25080,
"s": 24029,
"text": "A function is said to be reentrant if there is a provision to interrupt the function in the course of execution, service the interrupt service routine and then resume the earlier going on function, without hampering its earlier course of action. Reentrant functions are used in applications like hardware interrupt handling, recursion, etc. The function has to satisfy certain conditions to be called as reentrant:1. It may not use global and static data. Though there are no restrictions, but it is generally not advised. because the interrupt may change certain global values and resuming the course of action of the reentrant function with the new data may give undesired results. 2. It should not modify it’s own code. This is important because the course of action of the function should remain the same throughout the code. But, this may be allowed in case the interrupt routine uses a local copy of the reentrant function every time it uses different values or before and after the interrupt. 3. Should not call another non-reentrant function."
},
{
"code": null,
"e": 25721,
"s": 25080,
"text": "Thread safety and Reentrant functionsReentrancy is distinct from, but closely related to, thread-safety. A function can be thread-safe and still not reentrant. For example, a function could be wrapped all around with a mutex (which avoids problems in multithreading environments), but if that function is used in an interrupt service routine, it could starve waiting for the first execution to release the mutex. The key for avoiding confusion is that reentrant refers to only one thread executing. It is a concept from the time when no multitasking operating systems existed. (Source : https://en.wikipedia.org/wiki/Reentrancy_(computing))"
},
{
"code": null,
"e": 25758,
"s": 25721,
"text": " Example of Non-Reentrant Functions:"
},
{
"code": "// A non-reentrant example // [The function depends on global variable i] int i; // Both fun1() and fun2() are not reentrant // fun1() is NOT reentrant because it uses global variable iint fun1(){ return i * 5;} // fun2() is NOT reentrant because it calls a non-reentrant// functionint fun2(){ return fun1() * 5;}",
"e": 26081,
"s": 25758,
"text": null
},
{
"code": null,
"e": 26335,
"s": 26081,
"text": "Example of Reentrant Functions:In the below code, fun2 is a reentrant function. If an interrupt that pauses its execution and shifts the control to fun1. After fun1 completes, the control is again transferred to fun2 and it reenters the execution phase."
},
{
"code": "// Both fun1() and fun2() are reentrantint fun1(int i){ return i * 5;} int fun2(int i){ return fun1(i) * 5;}",
"e": 26450,
"s": 26335,
"text": null
},
{
"code": null,
"e": 26604,
"s": 26452,
"text": "Article compiled by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26614,
"s": 26604,
"text": "VictorDev"
},
{
"code": null,
"e": 26623,
"s": 26614,
"text": "Articles"
},
{
"code": null,
"e": 26721,
"s": 26623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26730,
"s": 26721,
"text": "Comments"
},
{
"code": null,
"e": 26743,
"s": 26730,
"text": "Old Comments"
},
{
"code": null,
"e": 26780,
"s": 26743,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 26806,
"s": 26780,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26853,
"s": 26806,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 26894,
"s": 26853,
"text": "Difference between Min Heap and Max Heap"
},
{
"code": null,
"e": 26915,
"s": 26894,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 26951,
"s": 26915,
"text": "Difference between Class and Object"
},
{
"code": null,
"e": 26994,
"s": 26951,
"text": "Implementation of LinkedList in Javascript"
},
{
"code": null,
"e": 27028,
"s": 26994,
"text": "Deploy Python Flask App on Heroku"
},
{
"code": null,
"e": 27063,
"s": 27028,
"text": "How compare() method works in Java"
}
] |
C program to find the solution of linear equation
|
We can apply the software development method to solve the linear equation of one variable in C programming language.
The equation should be in the form of ax+b=0
a and b are inputs, we need to find the value of x
Here,
An input is the a,b values.
An output is the x value.
Refer an algorithm given below to find solution of linear equation.
Step 1. Start
Step 2. Read a,b values
Step 3. Call function
Jump to step 5
Step 4. Print result
Step 5:
i. if(a == 0)Print value of c cannot be predictedElseCompute c=-b/aReturn cStep 6: Stop
i. if(a == 0)Print value of c cannot be predicted
Print value of c cannot be predicted
ElseCompute c=-b/a
Compute c=-b/a
Return c
Following is the C program to find the solution of linear equation −
Live Demo
#include <stdio.h>
#include <string.h>
float solve(float a, float b){
float c;
if(a == 0){
printf("value of c cannot be predicted\n");
}else{
c = -b / a;
}
return c;
}
int main(){
float a, b, c;
printf("\n enter a,b values: ");
scanf("%f%f", &a, &b);
c = solve(a, b);
printf("\n linear eq of one variable in the form of ax+b = 0, if a=%f,b=%f,then x= %f",a,b,c);
return 0;
}
When the above program is executed, it produces the following result −
enter a,b values: 4 8
linear eq of one variable in the form of ax+b = 0, if a=4.000000, b=8.000000,
then x= -2.000000
|
[
{
"code": null,
"e": 1179,
"s": 1062,
"text": "We can apply the software development method to solve the linear equation of one variable in C programming language."
},
{
"code": null,
"e": 1224,
"s": 1179,
"text": "The equation should be in the form of ax+b=0"
},
{
"code": null,
"e": 1275,
"s": 1224,
"text": "a and b are inputs, we need to find the value of x"
},
{
"code": null,
"e": 1281,
"s": 1275,
"text": "Here,"
},
{
"code": null,
"e": 1309,
"s": 1281,
"text": "An input is the a,b values."
},
{
"code": null,
"e": 1335,
"s": 1309,
"text": "An output is the x value."
},
{
"code": null,
"e": 1403,
"s": 1335,
"text": "Refer an algorithm given below to find solution of linear equation."
},
{
"code": null,
"e": 1595,
"s": 1403,
"text": "Step 1. Start\nStep 2. Read a,b values\nStep 3. Call function\nJump to step 5\nStep 4. Print result\nStep 5:\ni. if(a == 0)Print value of c cannot be predictedElseCompute c=-b/aReturn cStep 6: Stop"
},
{
"code": null,
"e": 1645,
"s": 1595,
"text": "i. if(a == 0)Print value of c cannot be predicted"
},
{
"code": null,
"e": 1682,
"s": 1645,
"text": "Print value of c cannot be predicted"
},
{
"code": null,
"e": 1701,
"s": 1682,
"text": "ElseCompute c=-b/a"
},
{
"code": null,
"e": 1716,
"s": 1701,
"text": "Compute c=-b/a"
},
{
"code": null,
"e": 1725,
"s": 1716,
"text": "Return c"
},
{
"code": null,
"e": 1794,
"s": 1725,
"text": "Following is the C program to find the solution of linear equation −"
},
{
"code": null,
"e": 1805,
"s": 1794,
"text": " Live Demo"
},
{
"code": null,
"e": 2228,
"s": 1805,
"text": "#include <stdio.h>\n#include <string.h>\nfloat solve(float a, float b){\n float c;\n if(a == 0){\n printf(\"value of c cannot be predicted\\n\");\n }else{\n c = -b / a;\n }\n return c;\n}\nint main(){\n float a, b, c;\n printf(\"\\n enter a,b values: \");\n scanf(\"%f%f\", &a, &b);\n c = solve(a, b);\n printf(\"\\n linear eq of one variable in the form of ax+b = 0, if a=%f,b=%f,then x= %f\",a,b,c);\n return 0;\n}"
},
{
"code": null,
"e": 2299,
"s": 2228,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2417,
"s": 2299,
"text": "enter a,b values: 4 8\nlinear eq of one variable in the form of ax+b = 0, if a=4.000000, b=8.000000,\nthen x= -2.000000"
}
] |
A Fast Introduction to FastAI — My Experience | by Yash Prakash | Towards Data Science
|
When I first heard about this powerful AI library that everyone seemed to be talking about, I was intrigued. FastAI — as its name stands, boasts to help coders deep dive into the vast and complicated world of deep learning in just a few lines of code and an extremely minimal setup too. Needless to say, I was pretty pumped to get my hands dirty and start experimenting with it a little.
If you’d like to get ahead and see all the code in one go, here’s the GitHub repo I put it all in:
https://github.com/yashprakash13/RockPaperScissorsFastAI
The installation on both Google Colaboratory as well as locally is very simple. It just takes one simple line of pip install fastai in the terminal/code block and you’re done!
Note: Do make sure you’re inside a new virtual environment when you install fastai and open the jupyter notebook to start writing your model! It’ll help a lot in managing the dependencies and later, if you want, you can even package it as a production ready model with just a bit of extra work.
Reading the book which is also provided freely in the convenience of Jupyter Notebooks was a great way to get started; I had already read the first three chapters before I got into writing my own model, utilising a pretty popular dataset from Kaggle for my convolutional neural network based image classification task.
The dataset I wanted to try my hands on was the Rock, Paper, Scissors dataset. It has a reasonable amount of images categorised into three respective folders of train, test and validation which can easily be read by the powerful high level APIs provided by fastai. Believe me, I was pretty surprised to see how easy it was to import data through their DataBlock API — if you’re coming from Keras, from my personal experience, this process feels much simpler than the Keras one.
Let me now get into the mechanics of the steps I went through to make my first model and see for yourself how simple it all is!
Here’s the data I used for this little project:
https://www.kaggle.com/sanikamal/rock-paper-scissors-dataset
Importing the vision modules from fastai is the first thing I did:
from fastai.vision.all import *
The next step was to create something called a ‘Path’ object to indicate where your data is. For example, I wrote it like this:
DATASET_PATH = Path('RockPaperScissors/data')
This process is pretty intuitive, you can in fact view your folders of data through the ls function too:
DATASET_PATH.ls()'''Output: [Path('RockPaperScissors/data/valid'),Path('RockPaperScissors/data/.DS_Store'),Path('RockPaperScissors/data/Rock-Paper-Scissors'),Path('RockPaperScissors/data/train'),Path('RockPaperScissors/data/test2')]'''
Now we get into supplying the data for our model through the DataBlock API I mentioned earlier.
rps_datablock = DataBlock( blocks = (ImageBlock, CategoryBlock), get_items = get_image_files, splitter = GrandparentSplitter(), get_y = parent_label, batch_tfms=aug_transforms(size=128, min_scale=0.75) )
Yes, it is that simple! If your data is arranged into folders like this:
Then importing the images with required labels and train + validation split is all done with just this single block of code!
Breaking it down a little: fastai takes the names of the grandparent folders — the train and valid folders — as the train and validation split for our dataset through the argument ‘splitter’, and parent folders — as the x and y for our dataset, the images being the ‘x’ and the rock, paper, scissors folder names being the ‘y’. And that’s it! Our data is now ready to be consumed by a model. And not only that, the DataBlock API also gives access to a variety of data augmentation functions as well, which I will be exploring in my future articles.
One of the first things Jeremy Howard, the co-founder of fastai, teaches in his book is to use the effectiveness of transfer learning for image classification. If you’re new to the world of ML, don’t worry about it too much. In the book, the introduction to using the power of transfer learning through the large pre-trained models is taught very well, and in simpler, non-mathematical terms too, so it’s really convenient to learn from there instead of many many other online resources) and especially if you are as bad at learning ML math as me :P
Loading a pre-trained model in fastai is even simpler. It looks like this:
learn = cnn_learner(dls, resnet34, metrics=accuracy)
Here, as you can see, we’re using the resnet34 pre-trained model for our purposes, and the accuracy after each evaluation on the validation set will be printed for our reference — to see how good or bad our model is performing.
We can also see the model architecture in detail with one simple line:
learn.model'''OUTPUT:Sequential( (0): Sequential( (0): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU(inplace=True) (3): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)... and so on.'''
Learning can then be initiated with this line:
learn.fit_one_cycle(2)# 2 being the number of epochs
One of the most useful methods of viewing how good your model is performing on the validation set via the Confusion Matrix. This is also very simple to do:
interpret = ClassificationInterpretation.from_learner(learn)interpret.plot_confusion_matrix()
This gives the confusion matrix for the three classes of images we have here. There are plenty of methods to customise the appearance of the matrix as well, display useful heatmaps for accuracy, etc.
All of this seemed pretty surreal to me when I first read the chapters and tried to attempt it myself. The power of fastai seems unmatched in the current world of AI — the effortless execution of neural networks in this simple project of mine is a testament to that. In the book, they also explain the in-depth, under-the-hood details of most of the algorithms used very commonly in machine learning, for example, the stochastic gradient descent algorithm and the back propagation algorithm.
As I continue on my journey to explore and learn more, it seems I’ll be doing some very interesting projects in the coming weeks, and if you’re here, after having read all the way through, I’ll encourage you to embark on it with me! I don’t remember the last time I was this excited about learning a new library, one that also encompasses all aspects of deep learning too!
The resources I’ll recommend for you to look up if you’re willing to learn more:
The fastai website and documentation, of course: https://docs.fast.aiThe fastbook delivered to you via jupyter notebooks: https://github.com/fastai/fastbook (I’ll recommend cloning the whole repository on your local machine to access them anytime).
The fastai website and documentation, of course: https://docs.fast.ai
The fastbook delivered to you via jupyter notebooks: https://github.com/fastai/fastbook (I’ll recommend cloning the whole repository on your local machine to access them anytime).
Follow me on Twitter. I post new Data Science tidbits every day.
Loved my article? Become a Medium member to continue to read all of my stories.
|
[
{
"code": null,
"e": 560,
"s": 172,
"text": "When I first heard about this powerful AI library that everyone seemed to be talking about, I was intrigued. FastAI — as its name stands, boasts to help coders deep dive into the vast and complicated world of deep learning in just a few lines of code and an extremely minimal setup too. Needless to say, I was pretty pumped to get my hands dirty and start experimenting with it a little."
},
{
"code": null,
"e": 659,
"s": 560,
"text": "If you’d like to get ahead and see all the code in one go, here’s the GitHub repo I put it all in:"
},
{
"code": null,
"e": 716,
"s": 659,
"text": "https://github.com/yashprakash13/RockPaperScissorsFastAI"
},
{
"code": null,
"e": 892,
"s": 716,
"text": "The installation on both Google Colaboratory as well as locally is very simple. It just takes one simple line of pip install fastai in the terminal/code block and you’re done!"
},
{
"code": null,
"e": 1187,
"s": 892,
"text": "Note: Do make sure you’re inside a new virtual environment when you install fastai and open the jupyter notebook to start writing your model! It’ll help a lot in managing the dependencies and later, if you want, you can even package it as a production ready model with just a bit of extra work."
},
{
"code": null,
"e": 1506,
"s": 1187,
"text": "Reading the book which is also provided freely in the convenience of Jupyter Notebooks was a great way to get started; I had already read the first three chapters before I got into writing my own model, utilising a pretty popular dataset from Kaggle for my convolutional neural network based image classification task."
},
{
"code": null,
"e": 1984,
"s": 1506,
"text": "The dataset I wanted to try my hands on was the Rock, Paper, Scissors dataset. It has a reasonable amount of images categorised into three respective folders of train, test and validation which can easily be read by the powerful high level APIs provided by fastai. Believe me, I was pretty surprised to see how easy it was to import data through their DataBlock API — if you’re coming from Keras, from my personal experience, this process feels much simpler than the Keras one."
},
{
"code": null,
"e": 2112,
"s": 1984,
"text": "Let me now get into the mechanics of the steps I went through to make my first model and see for yourself how simple it all is!"
},
{
"code": null,
"e": 2160,
"s": 2112,
"text": "Here’s the data I used for this little project:"
},
{
"code": null,
"e": 2221,
"s": 2160,
"text": "https://www.kaggle.com/sanikamal/rock-paper-scissors-dataset"
},
{
"code": null,
"e": 2288,
"s": 2221,
"text": "Importing the vision modules from fastai is the first thing I did:"
},
{
"code": null,
"e": 2320,
"s": 2288,
"text": "from fastai.vision.all import *"
},
{
"code": null,
"e": 2448,
"s": 2320,
"text": "The next step was to create something called a ‘Path’ object to indicate where your data is. For example, I wrote it like this:"
},
{
"code": null,
"e": 2494,
"s": 2448,
"text": "DATASET_PATH = Path('RockPaperScissors/data')"
},
{
"code": null,
"e": 2599,
"s": 2494,
"text": "This process is pretty intuitive, you can in fact view your folders of data through the ls function too:"
},
{
"code": null,
"e": 2835,
"s": 2599,
"text": "DATASET_PATH.ls()'''Output: [Path('RockPaperScissors/data/valid'),Path('RockPaperScissors/data/.DS_Store'),Path('RockPaperScissors/data/Rock-Paper-Scissors'),Path('RockPaperScissors/data/train'),Path('RockPaperScissors/data/test2')]'''"
},
{
"code": null,
"e": 2931,
"s": 2835,
"text": "Now we get into supplying the data for our model through the DataBlock API I mentioned earlier."
},
{
"code": null,
"e": 3153,
"s": 2931,
"text": "rps_datablock = DataBlock( blocks = (ImageBlock, CategoryBlock), get_items = get_image_files, splitter = GrandparentSplitter(), get_y = parent_label, batch_tfms=aug_transforms(size=128, min_scale=0.75) )"
},
{
"code": null,
"e": 3226,
"s": 3153,
"text": "Yes, it is that simple! If your data is arranged into folders like this:"
},
{
"code": null,
"e": 3351,
"s": 3226,
"text": "Then importing the images with required labels and train + validation split is all done with just this single block of code!"
},
{
"code": null,
"e": 3900,
"s": 3351,
"text": "Breaking it down a little: fastai takes the names of the grandparent folders — the train and valid folders — as the train and validation split for our dataset through the argument ‘splitter’, and parent folders — as the x and y for our dataset, the images being the ‘x’ and the rock, paper, scissors folder names being the ‘y’. And that’s it! Our data is now ready to be consumed by a model. And not only that, the DataBlock API also gives access to a variety of data augmentation functions as well, which I will be exploring in my future articles."
},
{
"code": null,
"e": 4450,
"s": 3900,
"text": "One of the first things Jeremy Howard, the co-founder of fastai, teaches in his book is to use the effectiveness of transfer learning for image classification. If you’re new to the world of ML, don’t worry about it too much. In the book, the introduction to using the power of transfer learning through the large pre-trained models is taught very well, and in simpler, non-mathematical terms too, so it’s really convenient to learn from there instead of many many other online resources) and especially if you are as bad at learning ML math as me :P"
},
{
"code": null,
"e": 4525,
"s": 4450,
"text": "Loading a pre-trained model in fastai is even simpler. It looks like this:"
},
{
"code": null,
"e": 4578,
"s": 4525,
"text": "learn = cnn_learner(dls, resnet34, metrics=accuracy)"
},
{
"code": null,
"e": 4806,
"s": 4578,
"text": "Here, as you can see, we’re using the resnet34 pre-trained model for our purposes, and the accuracy after each evaluation on the validation set will be printed for our reference — to see how good or bad our model is performing."
},
{
"code": null,
"e": 4877,
"s": 4806,
"text": "We can also see the model architecture in detail with one simple line:"
},
{
"code": null,
"e": 5228,
"s": 4877,
"text": "learn.model'''OUTPUT:Sequential( (0): Sequential( (0): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU(inplace=True) (3): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)... and so on.'''"
},
{
"code": null,
"e": 5275,
"s": 5228,
"text": "Learning can then be initiated with this line:"
},
{
"code": null,
"e": 5328,
"s": 5275,
"text": "learn.fit_one_cycle(2)# 2 being the number of epochs"
},
{
"code": null,
"e": 5484,
"s": 5328,
"text": "One of the most useful methods of viewing how good your model is performing on the validation set via the Confusion Matrix. This is also very simple to do:"
},
{
"code": null,
"e": 5578,
"s": 5484,
"text": "interpret = ClassificationInterpretation.from_learner(learn)interpret.plot_confusion_matrix()"
},
{
"code": null,
"e": 5778,
"s": 5578,
"text": "This gives the confusion matrix for the three classes of images we have here. There are plenty of methods to customise the appearance of the matrix as well, display useful heatmaps for accuracy, etc."
},
{
"code": null,
"e": 6270,
"s": 5778,
"text": "All of this seemed pretty surreal to me when I first read the chapters and tried to attempt it myself. The power of fastai seems unmatched in the current world of AI — the effortless execution of neural networks in this simple project of mine is a testament to that. In the book, they also explain the in-depth, under-the-hood details of most of the algorithms used very commonly in machine learning, for example, the stochastic gradient descent algorithm and the back propagation algorithm."
},
{
"code": null,
"e": 6643,
"s": 6270,
"text": "As I continue on my journey to explore and learn more, it seems I’ll be doing some very interesting projects in the coming weeks, and if you’re here, after having read all the way through, I’ll encourage you to embark on it with me! I don’t remember the last time I was this excited about learning a new library, one that also encompasses all aspects of deep learning too!"
},
{
"code": null,
"e": 6724,
"s": 6643,
"text": "The resources I’ll recommend for you to look up if you’re willing to learn more:"
},
{
"code": null,
"e": 6973,
"s": 6724,
"text": "The fastai website and documentation, of course: https://docs.fast.aiThe fastbook delivered to you via jupyter notebooks: https://github.com/fastai/fastbook (I’ll recommend cloning the whole repository on your local machine to access them anytime)."
},
{
"code": null,
"e": 7043,
"s": 6973,
"text": "The fastai website and documentation, of course: https://docs.fast.ai"
},
{
"code": null,
"e": 7223,
"s": 7043,
"text": "The fastbook delivered to you via jupyter notebooks: https://github.com/fastai/fastbook (I’ll recommend cloning the whole repository on your local machine to access them anytime)."
},
{
"code": null,
"e": 7288,
"s": 7223,
"text": "Follow me on Twitter. I post new Data Science tidbits every day."
}
] |
DirectX - Drawing
|
This chapter, in turn, focuses on the Direct3D API interfaces and methods which are needed to configure the rendering pipeline, define vertex and pixel shaders, and submit geometry to the rendering pipeline for drawing. After understanding the chapter, the user should be able to draw various geometric shapes with coloring or in wireframe mode.
Here, we will focus on drawing a triangle with Direct3D API.
In the first step, we include the basic header files, especially Direct3D header files which are required to draw a triangle with the code given below −
#include <windows.h>
#include <windowsx.h>
#include <d3d9.h>
In the second step, we define the necessary parameters such as screen resolution, function parameters, and Direct3D library file. Include the global declarations and function prototypes as given in the below code −
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#pragma comment (lib, "d3d9.lib")
LPDIRECT3D9 d3d; // the pointer to our Direct3D interface
LPDIRECT3DDEVICE9 d3ddev; // the pointer to the device class
LPDIRECT3DVERTEXBUFFER9 v_buffer = NULL; // the pointer to the vertex buffer
void initD3D(HWND hWnd); // sets up and initializes Direct3D
void render_frame(void); // renders a single frame
void cleanD3D(void); // closes Direct3D and releases memory
void init_graphics(void); // 3D declarations
struct CUSTOMVERTEX {FLOAT X, Y, Z, RHW; DWORD COLOR;};
In the next step, we declare the WindowProc function prototype with the required parameters as shown in the below code −
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow){
HWND hWnd;
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = L"WindowClass";
RegisterClassEx(&wc);
hWnd = CreateWindowEx(
NULL,
L"WindowClass",
L"Our Direct3D Program",
WS_OVERLAPPEDWINDOW,
0, 0,
SCREEN_WIDTH, SCREEN_HEIGHT,
NULL,
NULL,
hInstance,
NULL
);
ShowWindow(hWnd, nCmdShow);
}
In step 4, we call for the function which initializes the graphics and the necessary parameters as given in the below code −
void init_graphics(void){
// create the vertices using the CUSTOMVERTEX struct
CUSTOMVERTEX vertices[] = {
{ 400.0f, 62.5f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 0, 255), },
{ 650.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 255, 0), },
{ 150.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(255, 0, 0), },
};
// create a vertex buffer interface called v_buffer
d3ddev->CreateVertexBuffer(
3*sizeof(CUSTOMVERTEX),
0,
CUSTOMFVF,
D3DPOOL_MANAGED,
&v_buffer,
NULL
);
VOID* pVoid; // a void pointer
// lock v_buffer and load the vertices into it
v_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, vertices, sizeof(vertices));
v_buffer->Unlock();
}
The output generated is mentioned below −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2644,
"s": 2298,
"text": "This chapter, in turn, focuses on the Direct3D API interfaces and methods which are needed to configure the rendering pipeline, define vertex and pixel shaders, and submit geometry to the rendering pipeline for drawing. After understanding the chapter, the user should be able to draw various geometric shapes with coloring or in wireframe mode."
},
{
"code": null,
"e": 2705,
"s": 2644,
"text": "Here, we will focus on drawing a triangle with Direct3D API."
},
{
"code": null,
"e": 2858,
"s": 2705,
"text": "In the first step, we include the basic header files, especially Direct3D header files which are required to draw a triangle with the code given below −"
},
{
"code": null,
"e": 2919,
"s": 2858,
"text": "#include <windows.h>\n#include <windowsx.h>\n#include <d3d9.h>"
},
{
"code": null,
"e": 3134,
"s": 2919,
"text": "In the second step, we define the necessary parameters such as screen resolution, function parameters, and Direct3D library file. Include the global declarations and function prototypes as given in the below code −"
},
{
"code": null,
"e": 3688,
"s": 3134,
"text": "#define SCREEN_WIDTH 800\n#define SCREEN_HEIGHT 600\n#pragma comment (lib, \"d3d9.lib\")\nLPDIRECT3D9 d3d; // the pointer to our Direct3D interface\nLPDIRECT3DDEVICE9 d3ddev; // the pointer to the device class\nLPDIRECT3DVERTEXBUFFER9 v_buffer = NULL; // the pointer to the vertex buffer\nvoid initD3D(HWND hWnd); // sets up and initializes Direct3D\nvoid render_frame(void); // renders a single frame\nvoid cleanD3D(void); // closes Direct3D and releases memory\nvoid init_graphics(void); // 3D declarations\nstruct CUSTOMVERTEX {FLOAT X, Y, Z, RHW; DWORD COLOR;};"
},
{
"code": null,
"e": 3809,
"s": 3688,
"text": "In the next step, we declare the WindowProc function prototype with the required parameters as shown in the below code −"
},
{
"code": null,
"e": 4570,
"s": 3809,
"text": "LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, \n LPSTR lpCmdLine, int nCmdShow){\n \n HWND hWnd;\n WNDCLASSEX wc;\n ZeroMemory(&wc, sizeof(WNDCLASSEX));\n wc.cbSize = sizeof(WNDCLASSEX);\n wc.style = CS_HREDRAW | CS_VREDRAW;\n wc.lpfnWndProc = WindowProc;\n wc.hInstance = hInstance;\n wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n wc.lpszClassName = L\"WindowClass\";\n RegisterClassEx(&wc);\n hWnd = CreateWindowEx(\n NULL, \n L\"WindowClass\",\n L\"Our Direct3D Program\",\n WS_OVERLAPPEDWINDOW,\n 0, 0,\n SCREEN_WIDTH, SCREEN_HEIGHT,\n NULL,\n NULL,\n hInstance,\n NULL\n );\n ShowWindow(hWnd, nCmdShow);\n}"
},
{
"code": null,
"e": 4695,
"s": 4570,
"text": "In step 4, we call for the function which initializes the graphics and the necessary parameters as given in the below code −"
},
{
"code": null,
"e": 5406,
"s": 4695,
"text": "void init_graphics(void){\n // create the vertices using the CUSTOMVERTEX struct\n CUSTOMVERTEX vertices[] = {\n { 400.0f, 62.5f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 0, 255), },\n { 650.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 255, 0), },\n { 150.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(255, 0, 0), },\n };\n // create a vertex buffer interface called v_buffer\n d3ddev->CreateVertexBuffer(\n 3*sizeof(CUSTOMVERTEX),\n 0,\n CUSTOMFVF,\n D3DPOOL_MANAGED,\n &v_buffer,\n NULL\n );\n VOID* pVoid; // a void pointer\n // lock v_buffer and load the vertices into it\n v_buffer->Lock(0, 0, (void**)&pVoid, 0);\n memcpy(pVoid, vertices, sizeof(vertices));\n v_buffer->Unlock();\n}"
},
{
"code": null,
"e": 5448,
"s": 5406,
"text": "The output generated is mentioned below −"
},
{
"code": null,
"e": 5455,
"s": 5448,
"text": " Print"
},
{
"code": null,
"e": 5466,
"s": 5455,
"text": " Add Notes"
}
] |
Difference between user defined function and library function in C/C++ - GeeksforGeeks
|
21 Jun, 2020
Library function:These function are the built-in functions i.e., they are predefined in the library of the C. These are used to perform the most common operations like calculations, updatation, etc. Some of the library functions are printf, scanf, sqrt, etc. To use this functions in the program the user have to use associate header file associated to the corresponding function in the program.
For Example:If, the user have to use print the data or scan the data using input stream then we have to use functions printf() and scanf() in C program and cin and cout in C++ program. To use these functions the user have to include #include<stdio.h> preprocesser directive in C program and #include<iostream> preprocesser directive in C++ program.
C
C++
// C program to illustrate inbuilt function#include <stdio.h> // Driver Codeint main(){ // Print Statement printf("GeeksforGeeks!"); return 0;}
// C++ program to illustrate inbuilt function#include <iostream>using namespace std; // Driver Codeint main(){ // Print Statement cout << "GeeksforGeeks!"; return 0;}
GeeksforGeeks!
User-defined function:These functions are designed by the user when they are writing any program because for every task we do not have a library of functions where their definitions are predefined. To perform the according to the requirement of user the user have to develop some functions by itself, these functions are called user-defined functions. For such functions the user have to define the proper definition of the function.
For Example: If we want to perform the addition of two numbers then below is the program to illustrate the addition of two numbers using user-defined functions:
C
C++
// C program to illustrate user-defined function#include <stdio.h> // Function Call to find the sum of a and bvoid findSum(int a, int b){ // Print the sum printf("Sum is: %d", a + b);} // Driver Codeint main(){ // Given two numbers int a = 3, b = 5; // Function Call findSum(a, b); return 0;}
// C++ program to illustrate inbuilt function#include <iostream>using namespace std; // Function Call to find the sum of a and bvoid findSum(int a, int b){ // Print the sum cout << "Sum is: " << a + b;} // Driver Codeint main(){ // Given two numbers int a = 3, b = 5; // Function Call findSum(a, b); return 0;}
Sum is: 8
Tabular Representation to illustrate the difference between library and user-define function:
CPP-Basics
CPP-Functions
C++ Programs
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Handling the Divide by Zero Exception in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Stack vs Heap Memory Allocation
Difference between Process and Thread
|
[
{
"code": null,
"e": 24472,
"s": 24444,
"text": "\n21 Jun, 2020"
},
{
"code": null,
"e": 24868,
"s": 24472,
"text": "Library function:These function are the built-in functions i.e., they are predefined in the library of the C. These are used to perform the most common operations like calculations, updatation, etc. Some of the library functions are printf, scanf, sqrt, etc. To use this functions in the program the user have to use associate header file associated to the corresponding function in the program."
},
{
"code": null,
"e": 25217,
"s": 24868,
"text": "For Example:If, the user have to use print the data or scan the data using input stream then we have to use functions printf() and scanf() in C program and cin and cout in C++ program. To use these functions the user have to include #include<stdio.h> preprocesser directive in C program and #include<iostream> preprocesser directive in C++ program."
},
{
"code": null,
"e": 25219,
"s": 25217,
"text": "C"
},
{
"code": null,
"e": 25223,
"s": 25219,
"text": "C++"
},
{
"code": "// C program to illustrate inbuilt function#include <stdio.h> // Driver Codeint main(){ // Print Statement printf(\"GeeksforGeeks!\"); return 0;}",
"e": 25381,
"s": 25223,
"text": null
},
{
"code": "// C++ program to illustrate inbuilt function#include <iostream>using namespace std; // Driver Codeint main(){ // Print Statement cout << \"GeeksforGeeks!\"; return 0;}",
"e": 25562,
"s": 25381,
"text": null
},
{
"code": null,
"e": 25578,
"s": 25562,
"text": "GeeksforGeeks!\n"
},
{
"code": null,
"e": 26012,
"s": 25578,
"text": "User-defined function:These functions are designed by the user when they are writing any program because for every task we do not have a library of functions where their definitions are predefined. To perform the according to the requirement of user the user have to develop some functions by itself, these functions are called user-defined functions. For such functions the user have to define the proper definition of the function."
},
{
"code": null,
"e": 26173,
"s": 26012,
"text": "For Example: If we want to perform the addition of two numbers then below is the program to illustrate the addition of two numbers using user-defined functions:"
},
{
"code": null,
"e": 26175,
"s": 26173,
"text": "C"
},
{
"code": null,
"e": 26179,
"s": 26175,
"text": "C++"
},
{
"code": "// C program to illustrate user-defined function#include <stdio.h> // Function Call to find the sum of a and bvoid findSum(int a, int b){ // Print the sum printf(\"Sum is: %d\", a + b);} // Driver Codeint main(){ // Given two numbers int a = 3, b = 5; // Function Call findSum(a, b); return 0;}",
"e": 26499,
"s": 26179,
"text": null
},
{
"code": "// C++ program to illustrate inbuilt function#include <iostream>using namespace std; // Function Call to find the sum of a and bvoid findSum(int a, int b){ // Print the sum cout << \"Sum is: \" << a + b;} // Driver Codeint main(){ // Given two numbers int a = 3, b = 5; // Function Call findSum(a, b); return 0;}",
"e": 26837,
"s": 26499,
"text": null
},
{
"code": null,
"e": 26848,
"s": 26837,
"text": "Sum is: 8\n"
},
{
"code": null,
"e": 26942,
"s": 26848,
"text": "Tabular Representation to illustrate the difference between library and user-define function:"
},
{
"code": null,
"e": 26953,
"s": 26942,
"text": "CPP-Basics"
},
{
"code": null,
"e": 26967,
"s": 26953,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26980,
"s": 26967,
"text": "C++ Programs"
},
{
"code": null,
"e": 26999,
"s": 26980,
"text": "Difference Between"
},
{
"code": null,
"e": 27097,
"s": 26999,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27106,
"s": 27097,
"text": "Comments"
},
{
"code": null,
"e": 27119,
"s": 27106,
"text": "Old Comments"
},
{
"code": null,
"e": 27160,
"s": 27119,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 27219,
"s": 27160,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 27240,
"s": 27219,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 27252,
"s": 27240,
"text": "cout in C++"
},
{
"code": null,
"e": 27297,
"s": 27252,
"text": "Handling the Divide by Zero Exception in C++"
},
{
"code": null,
"e": 27328,
"s": 27297,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 27368,
"s": 27328,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 27400,
"s": 27368,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27432,
"s": 27400,
"text": "Stack vs Heap Memory Allocation"
}
] |
Customize the JOptionPane layout with updated color and image in Java
|
Customize the layout by changing the look and feel of the panel in which you added the component −
ImageIcon icon = new ImageIcon(new URL("http −//www.tutorialspoint.com/images/C-PLUS.png"));
JLabel label = new JLabel(icon);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setOpaque(true);
panel.setBackground(Color.ORANGE);
Above, we have added an image and even updated the background color of the panel.
Now, set it for the text panel −
JPanel textPanel = new JPanel(new GridLayout(10, 5)); textPanel.setBackground(Color.Magenta);
The following is an example to customize the JOptionPane layout −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingDemo {
public static void main(String[] args) throws Exception {
ImageIcon icon = new ImageIcon(new URL("http −//www.tutorialspoint.com/images/C-PLUS.png"));
JLabel label = new JLabel(icon);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);
panel.setOpaque(true); panel.setBackground(Color.ORANGE);
JPanel textPanel = new JPanel(new GridLayout(10, 5)); textPanel.setBackground(Color.MAGENTA);
for (int i = 0; i < 20; i++) {
textPanel.add(new JLabel("Learn C++"));
}
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(textPanel);
panel2.add(panel, BorderLayout.EAST);
JOptionPane.showMessageDialog(null, panel2, "Course",JOptionPane.DEFAULT_OPTION);
}
}
|
[
{
"code": null,
"e": 1161,
"s": 1062,
"text": "Customize the layout by changing the look and feel of the panel in which you added the component −"
},
{
"code": null,
"e": 1411,
"s": 1161,
"text": "ImageIcon icon = new ImageIcon(new URL(\"http −//www.tutorialspoint.com/images/C-PLUS.png\"));\nJLabel label = new JLabel(icon);\nJPanel panel = new JPanel(new GridBagLayout());\npanel.add(label);\npanel.setOpaque(true);\npanel.setBackground(Color.ORANGE);"
},
{
"code": null,
"e": 1493,
"s": 1411,
"text": "Above, we have added an image and even updated the background color of the panel."
},
{
"code": null,
"e": 1526,
"s": 1493,
"text": "Now, set it for the text panel −"
},
{
"code": null,
"e": 1620,
"s": 1526,
"text": "JPanel textPanel = new JPanel(new GridLayout(10, 5)); textPanel.setBackground(Color.Magenta);"
},
{
"code": null,
"e": 1686,
"s": 1620,
"text": "The following is an example to customize the JOptionPane layout −"
},
{
"code": null,
"e": 2729,
"s": 1686,
"text": "package my;\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.GridBagLayout;\nimport java.awt.GridLayout;\nimport java.net.URL;\nimport javax.swing.ImageIcon;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n ImageIcon icon = new ImageIcon(new URL(\"http −//www.tutorialspoint.com/images/C-PLUS.png\"));\n JLabel label = new JLabel(icon);\n JPanel panel = new JPanel(new GridBagLayout());\n panel.add(label);\n panel.setOpaque(true); panel.setBackground(Color.ORANGE);\n JPanel textPanel = new JPanel(new GridLayout(10, 5)); textPanel.setBackground(Color.MAGENTA);\n for (int i = 0; i < 20; i++) {\n textPanel.add(new JLabel(\"Learn C++\"));\n }\n JPanel panel2 = new JPanel(new BorderLayout());\n panel2.add(textPanel);\n panel2.add(panel, BorderLayout.EAST);\n JOptionPane.showMessageDialog(null, panel2, \"Course\",JOptionPane.DEFAULT_OPTION);\n }\n}"
}
] |
HTML - Marquees
|
An HTML marquee is a scrolling piece of text displayed either horizontally across or vertically down your webpage depending on the settings. This is created by using HTML <marquees> tag.
Note − The <marquee> tag deprecated in HTML5. Do not use this element, instead you can use JavaScript and CSS to create such effects.
A simple syntax to use HTML <marquee> tag is as follows −
<marquee attribute_name = "attribute_value"....more attributes>
One or more lines or text message or image
</marquee>
Following is the list of important attributes which can be used with <marquee> tag.
width
This specifies the width of the marquee. This can be a value like 10 or 20% etc.
height
This specifies the height of the marquee. This can be a value like 10 or 20% etc.
direction
This specifies the direction in which marquee should scroll. This can be a value like up, down, left or right.
behavior
This specifies the type of scrolling of the marquee. This can have a value like scroll, slide and alternate.
scrolldelay
This specifies how long to delay between each jump. This will have a value like 10 etc.
scrollamount
This specifies the speed of marquee text. This can have a value like 10 etc.
loop
This specifies how many times to loop. The default value is INFINITE, which means that the marquee loops endlessly.
bgcolor
This specifies background color in terms of color name or color hex value.
hspace
This specifies horizontal space around the marquee. This can be a value like 10 or 20% etc.
vspace
This specifies vertical space around the marquee. This can be a value like 10 or 20% etc.
Below are few examples to demonstrate the usage of marquee tag.
<!DOCTYPE html>
<html>
<head>
<title>HTML marquee Tag</title>
</head>
<body>
<marquee>This is basic example of marquee</marquee>
</body>
</html>
This will produce the following result −
<!DOCTYPE html>
<html>
<head>
<title>HTML marquee Tag</title>
</head>
<body>
<marquee width = "50%">This example will take only 50% width</marquee>
</body>
</html>
This will produce the following result −
<!DOCTYPE html>
<html>
<head>
<title>HTML marquee Tag</title>
</head>
<body>
<marquee direction = "right">This text will scroll from left to right</marquee>
</body>
</html>
This will produce the following result −
<!DOCTYPE html>
<html>
<head>
<title>HTML marquee Tag</title>
</head>
<body>
<marquee direction = "up">This text will scroll from bottom to up</marquee>
</body>
</html>
This 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": 2561,
"s": 2374,
"text": "An HTML marquee is a scrolling piece of text displayed either horizontally across or vertically down your webpage depending on the settings. This is created by using HTML <marquees> tag."
},
{
"code": null,
"e": 2695,
"s": 2561,
"text": "Note − The <marquee> tag deprecated in HTML5. Do not use this element, instead you can use JavaScript and CSS to create such effects."
},
{
"code": null,
"e": 2753,
"s": 2695,
"text": "A simple syntax to use HTML <marquee> tag is as follows −"
},
{
"code": null,
"e": 2875,
"s": 2753,
"text": "<marquee attribute_name = \"attribute_value\"....more attributes>\n One or more lines or text message or image\n</marquee>\n"
},
{
"code": null,
"e": 2959,
"s": 2875,
"text": "Following is the list of important attributes which can be used with <marquee> tag."
},
{
"code": null,
"e": 2965,
"s": 2959,
"text": "width"
},
{
"code": null,
"e": 3046,
"s": 2965,
"text": "This specifies the width of the marquee. This can be a value like 10 or 20% etc."
},
{
"code": null,
"e": 3053,
"s": 3046,
"text": "height"
},
{
"code": null,
"e": 3135,
"s": 3053,
"text": "This specifies the height of the marquee. This can be a value like 10 or 20% etc."
},
{
"code": null,
"e": 3145,
"s": 3135,
"text": "direction"
},
{
"code": null,
"e": 3256,
"s": 3145,
"text": "This specifies the direction in which marquee should scroll. This can be a value like up, down, left or right."
},
{
"code": null,
"e": 3265,
"s": 3256,
"text": "behavior"
},
{
"code": null,
"e": 3374,
"s": 3265,
"text": "This specifies the type of scrolling of the marquee. This can have a value like scroll, slide and alternate."
},
{
"code": null,
"e": 3386,
"s": 3374,
"text": "scrolldelay"
},
{
"code": null,
"e": 3474,
"s": 3386,
"text": "This specifies how long to delay between each jump. This will have a value like 10 etc."
},
{
"code": null,
"e": 3487,
"s": 3474,
"text": "scrollamount"
},
{
"code": null,
"e": 3564,
"s": 3487,
"text": "This specifies the speed of marquee text. This can have a value like 10 etc."
},
{
"code": null,
"e": 3569,
"s": 3564,
"text": "loop"
},
{
"code": null,
"e": 3685,
"s": 3569,
"text": "This specifies how many times to loop. The default value is INFINITE, which means that the marquee loops endlessly."
},
{
"code": null,
"e": 3693,
"s": 3685,
"text": "bgcolor"
},
{
"code": null,
"e": 3768,
"s": 3693,
"text": "This specifies background color in terms of color name or color hex value."
},
{
"code": null,
"e": 3775,
"s": 3768,
"text": "hspace"
},
{
"code": null,
"e": 3867,
"s": 3775,
"text": "This specifies horizontal space around the marquee. This can be a value like 10 or 20% etc."
},
{
"code": null,
"e": 3874,
"s": 3867,
"text": "vspace"
},
{
"code": null,
"e": 3964,
"s": 3874,
"text": "This specifies vertical space around the marquee. This can be a value like 10 or 20% etc."
},
{
"code": null,
"e": 4028,
"s": 3964,
"text": "Below are few examples to demonstrate the usage of marquee tag."
},
{
"code": null,
"e": 4202,
"s": 4028,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML marquee Tag</title>\n </head>\n\t\n <body>\n <marquee>This is basic example of marquee</marquee>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 4243,
"s": 4202,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4436,
"s": 4243,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML marquee Tag</title>\n </head>\n\t\n <body>\n <marquee width = \"50%\">This example will take only 50% width</marquee>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 4477,
"s": 4436,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4678,
"s": 4477,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML marquee Tag</title>\n </head>\n\n <body>\n <marquee direction = \"right\">This text will scroll from left to right</marquee>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 4719,
"s": 4678,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4917,
"s": 4719,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML marquee Tag</title>\n </head>\n\t\n <body>\n <marquee direction = \"up\">This text will scroll from bottom to up</marquee>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 4958,
"s": 4917,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4991,
"s": 4958,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5005,
"s": 4991,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5040,
"s": 5005,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5054,
"s": 5040,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5089,
"s": 5054,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5106,
"s": 5089,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5141,
"s": 5106,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5172,
"s": 5141,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5205,
"s": 5172,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5236,
"s": 5205,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5271,
"s": 5236,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5302,
"s": 5271,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5309,
"s": 5302,
"text": " Print"
},
{
"code": null,
"e": 5320,
"s": 5309,
"text": " Add Notes"
}
] |
Assembly - Strings
|
We have already used variable length strings in our previous examples. The variable length strings can have as many characters as required. Generally, we specify the length of the string by either of the two ways −
Explicitly storing string length
Using a sentinel character
We can store the string length explicitly by using the $ location counter symbol that represents the current value of the location counter. In the following example −
msg db 'Hello, world!',0xa ;our dear string
len equ $ - msg ;length of our dear string
$ points to the byte after the last character of the string variable msg. Therefore, $-msg gives the length of the string. We can also write
msg db 'Hello, world!',0xa ;our dear string
len equ 13 ;length of our dear string
Alternatively, you can store strings with a trailing sentinel character to delimit a string instead of storing the string length explicitly. The sentinel character should be a special character that does not appear within a string.
For example −
message DB 'I am loving it!', 0
Each string instruction may require a source operand, a destination operand or both. For 32-bit segments, string instructions use ESI and EDI registers to point to the source and destination operands, respectively.
For 16-bit segments, however, the SI and the DI registers are used to point to the source and destination, respectively.
There are five basic instructions for processing strings. They are −
MOVS − This instruction moves 1 Byte, Word or Doubleword of data from memory location to another.
MOVS − This instruction moves 1 Byte, Word or Doubleword of data from memory location to another.
LODS − This instruction loads from memory. If the operand is of one byte, it is loaded into the AL register, if the operand is one word, it is loaded into the AX register and a doubleword is loaded into the EAX register.
LODS − This instruction loads from memory. If the operand is of one byte, it is loaded into the AL register, if the operand is one word, it is loaded into the AX register and a doubleword is loaded into the EAX register.
STOS − This instruction stores data from register (AL, AX, or EAX) to memory.
STOS − This instruction stores data from register (AL, AX, or EAX) to memory.
CMPS − This instruction compares two data items in memory. Data could be of a byte size, word or doubleword.
CMPS − This instruction compares two data items in memory. Data could be of a byte size, word or doubleword.
SCAS − This instruction compares the contents of a register (AL, AX or EAX) with the contents of an item in memory.
SCAS − This instruction compares the contents of a register (AL, AX or EAX) with the contents of an item in memory.
Each of the above instruction has a byte, word, and doubleword version, and string instructions can be repeated by using a repetition prefix.
These instructions use the ES:DI and DS:SI pair of registers, where DI and SI registers contain valid offset addresses that refers to bytes stored in memory. SI is normally associated with DS (data segment) and DI is always associated with ES (extra segment).
The DS:SI (or ESI) and ES:DI (or EDI) registers point to the source and destination operands, respectively. The source operand is assumed to be at DS:SI (or ESI) and the destination operand at ES:DI (or EDI) in memory.
For 16-bit addresses, the SI and DI registers are used, and for 32-bit addresses, the ESI and EDI registers are used.
The following table provides various versions of string instructions and the assumed space of the operands.
The REP prefix, when set before a string instruction, for example - REP MOVSB, causes repetition of the instruction based on a counter placed at the CX register. REP executes the instruction, decreases CX by 1, and checks whether CX is zero. It repeats the instruction processing until CX is zero.
The Direction Flag (DF) determines the direction of the operation.
Use CLD (Clear Direction Flag, DF = 0) to make the operation left to right.
Use STD (Set Direction Flag, DF = 1) to make the operation right to left.
The REP prefix also has the following variations:
REP: It is the unconditional repeat. It repeats the operation until CX is zero.
REP: It is the unconditional repeat. It repeats the operation until CX is zero.
REPE or REPZ: It is conditional repeat. It repeats the operation while the zero flag indicates equal/zero. It stops when the ZF indicates not equal/zero or when CX is zero.
REPE or REPZ: It is conditional repeat. It repeats the operation while the zero flag indicates equal/zero. It stops when the ZF indicates not equal/zero or when CX is zero.
REPNE or REPNZ: It is also conditional repeat. It repeats the operation while the zero flag indicates not equal/zero. It stops when the ZF indicates equal/zero or when CX is decremented to zero.
REPNE or REPNZ: It is also conditional repeat. It repeats the operation while the zero flag indicates not equal/zero. It stops when the ZF indicates equal/zero or when CX is decremented to zero.
46 Lectures
2 hours
Frahaan Hussain
23 Lectures
12 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2300,
"s": 2085,
"text": "We have already used variable length strings in our previous examples. The variable length strings can have as many characters as required. Generally, we specify the length of the string by either of the two ways −"
},
{
"code": null,
"e": 2333,
"s": 2300,
"text": "Explicitly storing string length"
},
{
"code": null,
"e": 2360,
"s": 2333,
"text": "Using a sentinel character"
},
{
"code": null,
"e": 2527,
"s": 2360,
"text": "We can store the string length explicitly by using the $ location counter symbol that represents the current value of the location counter. In the following example −"
},
{
"code": null,
"e": 2629,
"s": 2527,
"text": "msg db 'Hello, world!',0xa ;our dear string\nlen equ $ - msg ;length of our dear string"
},
{
"code": null,
"e": 2770,
"s": 2629,
"text": "$ points to the byte after the last character of the string variable msg. Therefore, $-msg gives the length of the string. We can also write"
},
{
"code": null,
"e": 2868,
"s": 2770,
"text": "msg db 'Hello, world!',0xa ;our dear string\nlen equ 13 ;length of our dear string"
},
{
"code": null,
"e": 3100,
"s": 2868,
"text": "Alternatively, you can store strings with a trailing sentinel character to delimit a string instead of storing the string length explicitly. The sentinel character should be a special character that does not appear within a string."
},
{
"code": null,
"e": 3114,
"s": 3100,
"text": "For example −"
},
{
"code": null,
"e": 3146,
"s": 3114,
"text": "message DB 'I am loving it!', 0"
},
{
"code": null,
"e": 3361,
"s": 3146,
"text": "Each string instruction may require a source operand, a destination operand or both. For 32-bit segments, string instructions use ESI and EDI registers to point to the source and destination operands, respectively."
},
{
"code": null,
"e": 3482,
"s": 3361,
"text": "For 16-bit segments, however, the SI and the DI registers are used to point to the source and destination, respectively."
},
{
"code": null,
"e": 3551,
"s": 3482,
"text": "There are five basic instructions for processing strings. They are −"
},
{
"code": null,
"e": 3649,
"s": 3551,
"text": "MOVS − This instruction moves 1 Byte, Word or Doubleword of data from memory location to another."
},
{
"code": null,
"e": 3747,
"s": 3649,
"text": "MOVS − This instruction moves 1 Byte, Word or Doubleword of data from memory location to another."
},
{
"code": null,
"e": 3968,
"s": 3747,
"text": "LODS − This instruction loads from memory. If the operand is of one byte, it is loaded into the AL register, if the operand is one word, it is loaded into the AX register and a doubleword is loaded into the EAX register."
},
{
"code": null,
"e": 4189,
"s": 3968,
"text": "LODS − This instruction loads from memory. If the operand is of one byte, it is loaded into the AL register, if the operand is one word, it is loaded into the AX register and a doubleword is loaded into the EAX register."
},
{
"code": null,
"e": 4267,
"s": 4189,
"text": "STOS − This instruction stores data from register (AL, AX, or EAX) to memory."
},
{
"code": null,
"e": 4345,
"s": 4267,
"text": "STOS − This instruction stores data from register (AL, AX, or EAX) to memory."
},
{
"code": null,
"e": 4454,
"s": 4345,
"text": "CMPS − This instruction compares two data items in memory. Data could be of a byte size, word or doubleword."
},
{
"code": null,
"e": 4563,
"s": 4454,
"text": "CMPS − This instruction compares two data items in memory. Data could be of a byte size, word or doubleword."
},
{
"code": null,
"e": 4679,
"s": 4563,
"text": "SCAS − This instruction compares the contents of a register (AL, AX or EAX) with the contents of an item in memory."
},
{
"code": null,
"e": 4795,
"s": 4679,
"text": "SCAS − This instruction compares the contents of a register (AL, AX or EAX) with the contents of an item in memory."
},
{
"code": null,
"e": 4937,
"s": 4795,
"text": "Each of the above instruction has a byte, word, and doubleword version, and string instructions can be repeated by using a repetition prefix."
},
{
"code": null,
"e": 5197,
"s": 4937,
"text": "These instructions use the ES:DI and DS:SI pair of registers, where DI and SI registers contain valid offset addresses that refers to bytes stored in memory. SI is normally associated with DS (data segment) and DI is always associated with ES (extra segment)."
},
{
"code": null,
"e": 5416,
"s": 5197,
"text": "The DS:SI (or ESI) and ES:DI (or EDI) registers point to the source and destination operands, respectively. The source operand is assumed to be at DS:SI (or ESI) and the destination operand at ES:DI (or EDI) in memory."
},
{
"code": null,
"e": 5534,
"s": 5416,
"text": "For 16-bit addresses, the SI and DI registers are used, and for 32-bit addresses, the ESI and EDI registers are used."
},
{
"code": null,
"e": 5642,
"s": 5534,
"text": "The following table provides various versions of string instructions and the assumed space of the operands."
},
{
"code": null,
"e": 5940,
"s": 5642,
"text": "The REP prefix, when set before a string instruction, for example - REP MOVSB, causes repetition of the instruction based on a counter placed at the CX register. REP executes the instruction, decreases CX by 1, and checks whether CX is zero. It repeats the instruction processing until CX is zero."
},
{
"code": null,
"e": 6007,
"s": 5940,
"text": "The Direction Flag (DF) determines the direction of the operation."
},
{
"code": null,
"e": 6083,
"s": 6007,
"text": "Use CLD (Clear Direction Flag, DF = 0) to make the operation left to right."
},
{
"code": null,
"e": 6157,
"s": 6083,
"text": "Use STD (Set Direction Flag, DF = 1) to make the operation right to left."
},
{
"code": null,
"e": 6207,
"s": 6157,
"text": "The REP prefix also has the following variations:"
},
{
"code": null,
"e": 6287,
"s": 6207,
"text": "REP: It is the unconditional repeat. It repeats the operation until CX is zero."
},
{
"code": null,
"e": 6367,
"s": 6287,
"text": "REP: It is the unconditional repeat. It repeats the operation until CX is zero."
},
{
"code": null,
"e": 6540,
"s": 6367,
"text": "REPE or REPZ: It is conditional repeat. It repeats the operation while the zero flag indicates equal/zero. It stops when the ZF indicates not equal/zero or when CX is zero."
},
{
"code": null,
"e": 6713,
"s": 6540,
"text": "REPE or REPZ: It is conditional repeat. It repeats the operation while the zero flag indicates equal/zero. It stops when the ZF indicates not equal/zero or when CX is zero."
},
{
"code": null,
"e": 6908,
"s": 6713,
"text": "REPNE or REPNZ: It is also conditional repeat. It repeats the operation while the zero flag indicates not equal/zero. It stops when the ZF indicates equal/zero or when CX is decremented to zero."
},
{
"code": null,
"e": 7103,
"s": 6908,
"text": "REPNE or REPNZ: It is also conditional repeat. It repeats the operation while the zero flag indicates not equal/zero. It stops when the ZF indicates equal/zero or when CX is decremented to zero."
},
{
"code": null,
"e": 7136,
"s": 7103,
"text": "\n 46 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7153,
"s": 7136,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7187,
"s": 7153,
"text": "\n 23 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 7195,
"s": 7187,
"text": " Uplatz"
},
{
"code": null,
"e": 7202,
"s": 7195,
"text": " Print"
},
{
"code": null,
"e": 7213,
"s": 7202,
"text": " Add Notes"
}
] |
Explain the Post Correspondence Problem in TOC
|
The Post Correspondence Problem (PCP) was introduced by Emil Post in 1946 and is an undecidable decision problem.
The PCP problem over an alphabet Σ is state. Given the following two lists, M and N of non-empty strings over Σ−
M = (x1, x2, x3,........., xn)
N = (y1, y2, y3,........., yn)
We can say that there is a Post Correspondence Solution, if for some i1,i2,............ ik,
Where 1≤ ij ≤ n, the condition xi1 .......xik = yi1 .......yik satisfies.
Find whether the lists M = (abb, aa, aaa) and N = (bba, aaa, aa) have a Post Correspondence Solution.
Here,
x2x1x3 = ‘aaabbaaa’
and y2y1y3 = ‘aaabbaaa’
We can see that
x2x1x3 = y2y1y3
Hence, the solution is i = 2, j = 1, and k = 3.
Let us consider ,in PCP problem we have N number of Dominos (tiles). The aim is to arrange tiles in such order that string made by Numerators is same as string made by Denominators.
In simple words, lets assume we have two lists both containing N words, aim is to find out concatenation of these words in some sequence such that both lists yield same result.
Let’s try understanding this by taking two lists A and B
A=[aa, bb, abb] and B=[aab, ba, b]
Now for sequence 1, 2, 1, 3 first list will yield aabbaaabb and second list will yield same string aabbaaabb.
So the solution to this PCP becomes 1, 2, 1, 3.
Domino’s Form.
Domino’s Form.
Table form
Table form
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "The Post Correspondence Problem (PCP) was introduced by Emil Post in 1946 and is an undecidable decision problem."
},
{
"code": null,
"e": 1289,
"s": 1176,
"text": "The PCP problem over an alphabet Σ is state. Given the following two lists, M and N of non-empty strings over Σ−"
},
{
"code": null,
"e": 1351,
"s": 1289,
"text": "M = (x1, x2, x3,........., xn)\nN = (y1, y2, y3,........., yn)"
},
{
"code": null,
"e": 1443,
"s": 1351,
"text": "We can say that there is a Post Correspondence Solution, if for some i1,i2,............ ik,"
},
{
"code": null,
"e": 1517,
"s": 1443,
"text": "Where 1≤ ij ≤ n, the condition xi1 .......xik = yi1 .......yik satisfies."
},
{
"code": null,
"e": 1619,
"s": 1517,
"text": "Find whether the lists M = (abb, aa, aaa) and N = (bba, aaa, aa) have a Post Correspondence Solution."
},
{
"code": null,
"e": 1625,
"s": 1619,
"text": "Here,"
},
{
"code": null,
"e": 1645,
"s": 1625,
"text": "x2x1x3 = ‘aaabbaaa’"
},
{
"code": null,
"e": 1669,
"s": 1645,
"text": "and y2y1y3 = ‘aaabbaaa’"
},
{
"code": null,
"e": 1685,
"s": 1669,
"text": "We can see that"
},
{
"code": null,
"e": 1701,
"s": 1685,
"text": "x2x1x3 = y2y1y3"
},
{
"code": null,
"e": 1749,
"s": 1701,
"text": "Hence, the solution is i = 2, j = 1, and k = 3."
},
{
"code": null,
"e": 1931,
"s": 1749,
"text": "Let us consider ,in PCP problem we have N number of Dominos (tiles). The aim is to arrange tiles in such order that string made by Numerators is same as string made by Denominators."
},
{
"code": null,
"e": 2108,
"s": 1931,
"text": "In simple words, lets assume we have two lists both containing N words, aim is to find out concatenation of these words in some sequence such that both lists yield same result."
},
{
"code": null,
"e": 2165,
"s": 2108,
"text": "Let’s try understanding this by taking two lists A and B"
},
{
"code": null,
"e": 2200,
"s": 2165,
"text": "A=[aa, bb, abb] and B=[aab, ba, b]"
},
{
"code": null,
"e": 2310,
"s": 2200,
"text": "Now for sequence 1, 2, 1, 3 first list will yield aabbaaabb and second list will yield same string aabbaaabb."
},
{
"code": null,
"e": 2358,
"s": 2310,
"text": "So the solution to this PCP becomes 1, 2, 1, 3."
},
{
"code": null,
"e": 2373,
"s": 2358,
"text": "Domino’s Form."
},
{
"code": null,
"e": 2388,
"s": 2373,
"text": "Domino’s Form."
},
{
"code": null,
"e": 2399,
"s": 2388,
"text": "Table form"
},
{
"code": null,
"e": 2410,
"s": 2399,
"text": "Table form"
}
] |
Machine-Learning In Julia is FINALLY Getting Better | by Emmett Boudreau | Towards Data Science
|
Whenever I first started using Julia, an issue that I, as well as many other defectors coming from languages with strong ecosystems like Python and R took, is specifically with data processing. Data processing seems to of been quite neglected in Julia, often with individual packages being used to solve a single problem, and some problems being missed entirely. Sometimes there would be functions already available, but they would be incredibly difficult to use, requiring you to assert types and convert data before passing it through any pre-processing algorithms. For this reason not only was getting a model trained difficult, but putting a model into a Pipeline and deploying it was entirely out of the question.
However, with the futuristic and exciting strides that Julia developers have made, pre-processing has evolved further than I ever would have originally thought possible. As a result, Julia has become a much more viable option for machine-learning in general. With the luxurious additions to Genie, and its respective documentation as well, deploying APIs has become a
cake walk.
Genie manages all of the virtual environments for you, and now that documentation has been released, and is constantly being improved by the amazing developer Essenciary (Adrian Salceanu), making Julia more usable as a web framework everyday.
This might come as a surprise, but among the greatest challenges that Julia currently faces is PyCall.jl. This is because as it stands, too many packages depend on it, and in turn depend on Python. While I fully understand, the Python ecosystem is far greater than Julia’s, Julia, in turn, loses all of the speed gained, and with PyCall can even be slower than using Python itself,
so why even use Julia?
Train-Test-Splitting is an essential tool that is entirely required for any stretch of machine-learning. In order to validate an algorithm, you must first have a train and a test set, and some even opt for a validation set as well. Referring to this thread,
discourse.julialang.org
on Julia discourse, I think it’s pretty obvious that Test-Train-Splitting for data-frames has been overlooked to some extent. MLDataUtils is likely the package that most have used for Train-Test-Split, and take my word for it:
It could certainly be better.
Fortunately, for a few months now, there has been better from the module Lathe.
using Lathe.preprocess: TrainTestSplittrain, test = TrainTestSplit(df)
And we can even adjust our split percentage, like so:
train, test = TrainTestSplit(df,0.5)
This will split the data in half for our test and train sets.
Something that I think is all too common inside of Julia modules is SkLearn formality. I don’t think that we should be embracing or enforcing this conformation from an entirely separate language based in an entirely separate paradigm. A great example of this is the feature scalars inside of Julia. Most if not all feature scalars conform to SkLearn’s writing style which has defined Python machine-learning modules since 2010. But the reason why SkLearn’s scalars behave this way is for one sole reason, and that is SkLearn’s wonderful Pipelines.
In Julia, we don’t have classes, and in turn we can’t have methods be children of an object. Instead, we have structs which can take a method to perform an action with the data that the struct holds. Additionally, the only pipelines that Julia has to offer are syntactical pipelines — which are fine, but certainly eliminate the point of the conformation to SkLearn, given that they don’t use the same methods. To put this in perspective, this is the formula for a Standard Scalar (Z-Score normalizer):
With such a simple formula, the only things calculate on fit are the sample mean and the standard deviation. With Julia’s speed, these calculations are of course done in microseconds, as they are similarly in Python. This is not in any stretch of the imagination a difficult calculation to make, being done in one concise for loop and two additional lines. Fortunately, Lathe strikes again with an easy method that takes any array:
using Lathe.preprocess: StandardScalarscaledX = StandardScalar(trainX)
Pretty simple, right?
In addition to the standard scalar, Lathe also comes with plenty of other scalars, and in the future there are plans to implement a Unit Length Scalar, as well. As of right now, listing off Lathe.preprocess with the ?() method will show us all of the scalars available:
Rescalar
Arbitrary Rescale
Mean Normalization
Categorical encoders are another region of the Julia ecosystem that has been extremely lacking. There is only one encoder available, and typically it is used through Flux, and it is called the one hot encoder. To give you an idea of how senselessly over complicated Flux’s one hot encoder is, you can take a look at the source here:
github.com
The code totals out to 130 lines in that file, a size that is nowhere near necessary, in my opinion. To use Lathe’s one hot encoder, we simply call on the method “ OneHotEncode”:
using Lathe.preprocess: OneHotEncodeencoded_df = OneHotEncode(df,:columnname)
And here is the code that computes that, done in just 7 lines total:
Pipelines are a very important feature to SkLearn and machine-learning as a whole. Julia is severely lacking a really good library for using pipelines. Most pipelines in Julia don’t take constructed models, and disallow for any sort of easy serialization reading and writing. With Lathe, however there are in fact pipelines which use the same prediction function as the rest of the Lathe models, and allows for an iterable set of steps as well as a model to predict with. If you’d like to read a full, though outdated tutorial on Lathe’s pipelines, you can check it out here:
towardsdatascience.com
Additionally, for valuable documentation, you can simply use the ?() method on Lathe.models.Pipeline.
I believe a lot of Julia modules leave a lot to be desired. Some don’t offer any data-frame compatibility whatsoever, while others make even more problems by senselessly over-complicating simple algorithms. The Julia language is extremely flexible, and that can be used to our advantage not only in the notebooks, but also in the modules. I think that the Julia ecosystem puts off a lot of new people coming to the language for this exact reason, and that is frustrating to me. The truth is, in terms of packages, right now Python easily has done it better. I think this can easily be changed, and with eyes into the future I am very excited for where the Julia ecosystem, including Lathe will be!
|
[
{
"code": null,
"e": 890,
"s": 171,
"text": "Whenever I first started using Julia, an issue that I, as well as many other defectors coming from languages with strong ecosystems like Python and R took, is specifically with data processing. Data processing seems to of been quite neglected in Julia, often with individual packages being used to solve a single problem, and some problems being missed entirely. Sometimes there would be functions already available, but they would be incredibly difficult to use, requiring you to assert types and convert data before passing it through any pre-processing algorithms. For this reason not only was getting a model trained difficult, but putting a model into a Pipeline and deploying it was entirely out of the question."
},
{
"code": null,
"e": 1258,
"s": 890,
"text": "However, with the futuristic and exciting strides that Julia developers have made, pre-processing has evolved further than I ever would have originally thought possible. As a result, Julia has become a much more viable option for machine-learning in general. With the luxurious additions to Genie, and its respective documentation as well, deploying APIs has become a"
},
{
"code": null,
"e": 1269,
"s": 1258,
"text": "cake walk."
},
{
"code": null,
"e": 1512,
"s": 1269,
"text": "Genie manages all of the virtual environments for you, and now that documentation has been released, and is constantly being improved by the amazing developer Essenciary (Adrian Salceanu), making Julia more usable as a web framework everyday."
},
{
"code": null,
"e": 1894,
"s": 1512,
"text": "This might come as a surprise, but among the greatest challenges that Julia currently faces is PyCall.jl. This is because as it stands, too many packages depend on it, and in turn depend on Python. While I fully understand, the Python ecosystem is far greater than Julia’s, Julia, in turn, loses all of the speed gained, and with PyCall can even be slower than using Python itself,"
},
{
"code": null,
"e": 1917,
"s": 1894,
"text": "so why even use Julia?"
},
{
"code": null,
"e": 2175,
"s": 1917,
"text": "Train-Test-Splitting is an essential tool that is entirely required for any stretch of machine-learning. In order to validate an algorithm, you must first have a train and a test set, and some even opt for a validation set as well. Referring to this thread,"
},
{
"code": null,
"e": 2199,
"s": 2175,
"text": "discourse.julialang.org"
},
{
"code": null,
"e": 2426,
"s": 2199,
"text": "on Julia discourse, I think it’s pretty obvious that Test-Train-Splitting for data-frames has been overlooked to some extent. MLDataUtils is likely the package that most have used for Train-Test-Split, and take my word for it:"
},
{
"code": null,
"e": 2456,
"s": 2426,
"text": "It could certainly be better."
},
{
"code": null,
"e": 2536,
"s": 2456,
"text": "Fortunately, for a few months now, there has been better from the module Lathe."
},
{
"code": null,
"e": 2607,
"s": 2536,
"text": "using Lathe.preprocess: TrainTestSplittrain, test = TrainTestSplit(df)"
},
{
"code": null,
"e": 2661,
"s": 2607,
"text": "And we can even adjust our split percentage, like so:"
},
{
"code": null,
"e": 2698,
"s": 2661,
"text": "train, test = TrainTestSplit(df,0.5)"
},
{
"code": null,
"e": 2760,
"s": 2698,
"text": "This will split the data in half for our test and train sets."
},
{
"code": null,
"e": 3308,
"s": 2760,
"text": "Something that I think is all too common inside of Julia modules is SkLearn formality. I don’t think that we should be embracing or enforcing this conformation from an entirely separate language based in an entirely separate paradigm. A great example of this is the feature scalars inside of Julia. Most if not all feature scalars conform to SkLearn’s writing style which has defined Python machine-learning modules since 2010. But the reason why SkLearn’s scalars behave this way is for one sole reason, and that is SkLearn’s wonderful Pipelines."
},
{
"code": null,
"e": 3811,
"s": 3308,
"text": "In Julia, we don’t have classes, and in turn we can’t have methods be children of an object. Instead, we have structs which can take a method to perform an action with the data that the struct holds. Additionally, the only pipelines that Julia has to offer are syntactical pipelines — which are fine, but certainly eliminate the point of the conformation to SkLearn, given that they don’t use the same methods. To put this in perspective, this is the formula for a Standard Scalar (Z-Score normalizer):"
},
{
"code": null,
"e": 4243,
"s": 3811,
"text": "With such a simple formula, the only things calculate on fit are the sample mean and the standard deviation. With Julia’s speed, these calculations are of course done in microseconds, as they are similarly in Python. This is not in any stretch of the imagination a difficult calculation to make, being done in one concise for loop and two additional lines. Fortunately, Lathe strikes again with an easy method that takes any array:"
},
{
"code": null,
"e": 4314,
"s": 4243,
"text": "using Lathe.preprocess: StandardScalarscaledX = StandardScalar(trainX)"
},
{
"code": null,
"e": 4336,
"s": 4314,
"text": "Pretty simple, right?"
},
{
"code": null,
"e": 4606,
"s": 4336,
"text": "In addition to the standard scalar, Lathe also comes with plenty of other scalars, and in the future there are plans to implement a Unit Length Scalar, as well. As of right now, listing off Lathe.preprocess with the ?() method will show us all of the scalars available:"
},
{
"code": null,
"e": 4615,
"s": 4606,
"text": "Rescalar"
},
{
"code": null,
"e": 4633,
"s": 4615,
"text": "Arbitrary Rescale"
},
{
"code": null,
"e": 4652,
"s": 4633,
"text": "Mean Normalization"
},
{
"code": null,
"e": 4985,
"s": 4652,
"text": "Categorical encoders are another region of the Julia ecosystem that has been extremely lacking. There is only one encoder available, and typically it is used through Flux, and it is called the one hot encoder. To give you an idea of how senselessly over complicated Flux’s one hot encoder is, you can take a look at the source here:"
},
{
"code": null,
"e": 4996,
"s": 4985,
"text": "github.com"
},
{
"code": null,
"e": 5175,
"s": 4996,
"text": "The code totals out to 130 lines in that file, a size that is nowhere near necessary, in my opinion. To use Lathe’s one hot encoder, we simply call on the method “ OneHotEncode”:"
},
{
"code": null,
"e": 5253,
"s": 5175,
"text": "using Lathe.preprocess: OneHotEncodeencoded_df = OneHotEncode(df,:columnname)"
},
{
"code": null,
"e": 5322,
"s": 5253,
"text": "And here is the code that computes that, done in just 7 lines total:"
},
{
"code": null,
"e": 5898,
"s": 5322,
"text": "Pipelines are a very important feature to SkLearn and machine-learning as a whole. Julia is severely lacking a really good library for using pipelines. Most pipelines in Julia don’t take constructed models, and disallow for any sort of easy serialization reading and writing. With Lathe, however there are in fact pipelines which use the same prediction function as the rest of the Lathe models, and allows for an iterable set of steps as well as a model to predict with. If you’d like to read a full, though outdated tutorial on Lathe’s pipelines, you can check it out here:"
},
{
"code": null,
"e": 5921,
"s": 5898,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6023,
"s": 5921,
"text": "Additionally, for valuable documentation, you can simply use the ?() method on Lathe.models.Pipeline."
}
] |
Python – Extract Percentages from String
|
02 Sep, 2020
Given a String, extract all the numbers that are percentages.
Input : test_str = ‘geeksforgeeks 20% is 100% way to get 200% success’Output : [‘20%’, ‘100%’, ‘200%’]Explanation : 20%, 100% and 200% are percentages present.
Input : test_str = ‘geeksforgeeks is way to get success’Output : []Explanation : No percentages present.
Method #1 : Using findall() + regex
In this, we employ appropriate regex having “%” symbol in suffix and use findall() to get all occurrences of such numbers from String.
Python3
# Python3 code to demonstrate working of # Extract Percentages from String # Using regex + findall()import re # initializing stringstest_str = 'geeksforgeeks is 100 % way to get 200 % success' # printing original stringprint("The original string is : " + str(test_str)) # getting required result from string res = re.findall('\d*%', test_str) # printing result print("The percentages : " + str(res))
The original string is : geeksforgeeks is 100% way to get 200% success
The percentages : ['100%', '200%']
Method #2 : Using re.sub() + split()
In this, we perform split of all words, and then from words that have %, we remove all non-numeric strings. This can be buggy in cases, we have different ordering of % and numbers in string.
Python3
# Python3 code to demonstrate working of # Extract Percentages from String # Using re.sub() + split()import re # initializing stringstest_str = 'geeksforgeeks is 100 % way to get 200 % success' # printing original stringprint("The original string is : " + str(test_str)) # extracting wordstemp = test_str.split() # using res = []for sub in temp: if '%' in sub: # replace empty string to all non-number chars res.append(re.sub(r'[^\d, %]', '', sub)) # printing result print("The percentages : " + str(res))
The original string is : geeksforgeeks is 100% way to get 200% success
The percentages : ['100%', '200%']
Python list-programs
Python
Python Programs
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 ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 116,
"s": 54,
"text": "Given a String, extract all the numbers that are percentages."
},
{
"code": null,
"e": 276,
"s": 116,
"text": "Input : test_str = ‘geeksforgeeks 20% is 100% way to get 200% success’Output : [‘20%’, ‘100%’, ‘200%’]Explanation : 20%, 100% and 200% are percentages present."
},
{
"code": null,
"e": 381,
"s": 276,
"text": "Input : test_str = ‘geeksforgeeks is way to get success’Output : []Explanation : No percentages present."
},
{
"code": null,
"e": 417,
"s": 381,
"text": "Method #1 : Using findall() + regex"
},
{
"code": null,
"e": 552,
"s": 417,
"text": "In this, we employ appropriate regex having “%” symbol in suffix and use findall() to get all occurrences of such numbers from String."
},
{
"code": null,
"e": 560,
"s": 552,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract Percentages from String # Using regex + findall()import re # initializing stringstest_str = 'geeksforgeeks is 100 % way to get 200 % success' # printing original stringprint(\"The original string is : \" + str(test_str)) # getting required result from string res = re.findall('\\d*%', test_str) # printing result print(\"The percentages : \" + str(res)) ",
"e": 965,
"s": 560,
"text": null
},
{
"code": null,
"e": 1072,
"s": 965,
"text": "The original string is : geeksforgeeks is 100% way to get 200% success\nThe percentages : ['100%', '200%']\n"
},
{
"code": null,
"e": 1109,
"s": 1072,
"text": "Method #2 : Using re.sub() + split()"
},
{
"code": null,
"e": 1301,
"s": 1109,
"text": "In this, we perform split of all words, and then from words that have %, we remove all non-numeric strings. This can be buggy in cases, we have different ordering of % and numbers in string."
},
{
"code": null,
"e": 1309,
"s": 1301,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract Percentages from String # Using re.sub() + split()import re # initializing stringstest_str = 'geeksforgeeks is 100 % way to get 200 % success' # printing original stringprint(\"The original string is : \" + str(test_str)) # extracting wordstemp = test_str.split() # using res = []for sub in temp: if '%' in sub: # replace empty string to all non-number chars res.append(re.sub(r'[^\\d, %]', '', sub)) # printing result print(\"The percentages : \" + str(res)) ",
"e": 1850,
"s": 1309,
"text": null
},
{
"code": null,
"e": 1957,
"s": 1850,
"text": "The original string is : geeksforgeeks is 100% way to get 200% success\nThe percentages : ['100%', '200%']\n"
},
{
"code": null,
"e": 1978,
"s": 1957,
"text": "Python list-programs"
},
{
"code": null,
"e": 1985,
"s": 1978,
"text": "Python"
},
{
"code": null,
"e": 2001,
"s": 1985,
"text": "Python Programs"
},
{
"code": null,
"e": 2099,
"s": 2001,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2117,
"s": 2099,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2159,
"s": 2117,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2181,
"s": 2159,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2216,
"s": 2181,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2248,
"s": 2216,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2291,
"s": 2248,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2313,
"s": 2291,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2352,
"s": 2313,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2390,
"s": 2352,
"text": "Python | Convert a list to dictionary"
}
] |
GATE-CS-2016 (Set 2) - GeeksforGeeks
|
11 Oct, 2021
put up with - is a phrasal verb
Meaning : to accept somebody/something that is annoying, unpleasant without complaining
mock, deride, praise, jeer
--> Author has not said anything against internet and mobile computing
but is talking about the surprising usage of these.
"Many believe that the internet itself is an unintended consequence of
the original invention."
--> The author says that many believe that 'internet itself' is unplanned
but actually both internet and mobile computers are unplanned(unintended)
inventions.
(i) Ooty is not a hill-station.
(ii) No hill-station can have more than one lake.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Git - Difference Between Git Fetch and Git Pull
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Java Threads
Optimization of Basic Blocks
TCS NQT Coding Sheet
A Freshers Guide To Programming
|
[
{
"code": null,
"e": 29574,
"s": 29546,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 29695,
"s": 29574,
"text": "put up with - is a phrasal verb\nMeaning : to accept somebody/something that is annoying, unpleasant without complaining\n"
},
{
"code": null,
"e": 29723,
"s": 29695,
"text": "mock, deride, praise, jeer "
},
{
"code": null,
"e": 30109,
"s": 29723,
"text": "--> Author has not said anything against internet and mobile computing \nbut is talking about the surprising usage of these.\n\n\"Many believe that the internet itself is an unintended consequence of \nthe original invention.\"\n--> The author says that many believe that 'internet itself' is unplanned \nbut actually both internet and mobile computers are unplanned(unintended) \ninventions.\n\n"
},
{
"code": null,
"e": 30193,
"s": 30109,
"text": "\n(i) Ooty is not a hill-station.\n(ii) No hill-station can have more than one lake. "
},
{
"code": null,
"e": 30291,
"s": 30193,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 30365,
"s": 30291,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 30418,
"s": 30365,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 30484,
"s": 30418,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 30532,
"s": 30484,
"text": "Git - Difference Between Git Fetch and Git Pull"
},
{
"code": null,
"e": 30581,
"s": 30532,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30606,
"s": 30581,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30619,
"s": 30606,
"text": "Java Threads"
},
{
"code": null,
"e": 30648,
"s": 30619,
"text": "Optimization of Basic Blocks"
},
{
"code": null,
"e": 30669,
"s": 30648,
"text": "TCS NQT Coding Sheet"
}
] |
Semantic-UI | Step
|
20 May, 2020
Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements.
A step shows the completion of a series of activities.
Example 1: This example creating a simple step of completion.
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></head> <body> <div class="ui container"> <h2>Step</h2> <div class="ui steps"> <div class="step"> Placing Order </div> </div> </div></body> </html>
Output:
Example 2: This example creating a group of steps.
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></head> <body> <div class="ui container"> <h2>Steps</h2> <div class="ui ordered steps"> <div class="completed step"> <div class="content"> <div class="title">Order</div> <div class="description"> Order the food </div> </div> </div> <div class="completed step"> <div class="content"> <div class="title">Preparing</div> <div class="description"> Preparing the food </div> </div> </div> <div class="step"> <div class="content"> <div class="title">On the way</div> <div class="description"> Food is on your way </div> </div> </div> <div class="disabled step"> <div class="content"> <div class="title">Delieverd</div> <div class="description"> Food Delieverd </div> </div> </div> </div> </div></body> </html>
Add ‘completed’ class to the steps which recompleted.
Add ‘active’ class to the step which is on going.
Add ‘disabled’ class to the step which are after the active step.
Output:
For showing these steps in vertical order replace ‘ordered’ class with ‘vertical’ class.
Example 3: This example creating the Steps with Icon.
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></head> <body> <div class="ui container"> <h2>Steps</h2> <div class="ui ordered steps"> <div class="completed step"> <i class="code icon"></i> <div class="content"> <div class="title">Code</div> <div class="description"> Write Code. </div> </div> </div> <div class="completed step"> <i class="terminal icon"></i> <div class="content"> <div class="title">Compile</div> <div class="description"> Compile Code. </div> </div> </div> <div class="step"> <i class="window close icon"></i> <div class="content"> <div class="title">Fix Error</div> <div class="description"> If it gives error fix </div> </div> </div> <div class="disabled step"> <i class="terminal icon"></i> <div class="content"> <div class="title">Compile Again</div> <div class="description"> Compile Code. </div> </div> </div> <div class="disabled step"> <i class="computer icon"></i> <div class="content"> <div class="title">Output</div> <div class="description"> See the output </div> </div> </div> </div> </div></body> </html>
Output:
Note: You can add <a> tag to make it link
Example 4: This example creating the Completed, active, disabled state in steps.
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></head> <body> <div class="ui container"> <h2>Active Step</h2> <div class="ui steps"> <div class="active step"> <i class="code icon"></i> <div class="content"> <div class="title">Coding</div> <div class="description"> Writing the Code </div> </div> </div> </div> <h2>Completed Step</h2> <div class="ui steps"> <div class="completed step"> <i class="code icon"></i> <div class="content"> <div class="title">Coding</div> <div class="description"> Finsished Coding </div> </div> </div> </div> <h2>Disabled Step</h2> <div class="ui steps"> <div class="disabled step"> <i class="code icon"></i> <div class="content"> <div class="title">Coding</div> <div class="description"> Pending </div> </div> </div> </div> </div></body> </html>
Output:
Note:
You can add stackable class to make group steps stackable.
You can add ‘UI tiny steps’ class for steps to show them tiny for another size, just replace tiny with small, large, massive.
Semantic-UI
CSS
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": "\n20 May, 2020"
},
{
"code": null,
"e": 287,
"s": 28,
"text": "Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements."
},
{
"code": null,
"e": 342,
"s": 287,
"text": "A step shows the completion of a series of activities."
},
{
"code": null,
"e": 404,
"s": 342,
"text": "Example 1: This example creating a simple step of completion."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></head> <body> <div class=\"ui container\"> <h2>Step</h2> <div class=\"ui steps\"> <div class=\"step\"> Placing Order </div> </div> </div></body> </html>",
"e": 898,
"s": 404,
"text": null
},
{
"code": null,
"e": 906,
"s": 898,
"text": "Output:"
},
{
"code": null,
"e": 957,
"s": 906,
"text": "Example 2: This example creating a group of steps."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></head> <body> <div class=\"ui container\"> <h2>Steps</h2> <div class=\"ui ordered steps\"> <div class=\"completed step\"> <div class=\"content\"> <div class=\"title\">Order</div> <div class=\"description\"> Order the food </div> </div> </div> <div class=\"completed step\"> <div class=\"content\"> <div class=\"title\">Preparing</div> <div class=\"description\"> Preparing the food </div> </div> </div> <div class=\"step\"> <div class=\"content\"> <div class=\"title\">On the way</div> <div class=\"description\"> Food is on your way </div> </div> </div> <div class=\"disabled step\"> <div class=\"content\"> <div class=\"title\">Delieverd</div> <div class=\"description\"> Food Delieverd </div> </div> </div> </div> </div></body> </html>",
"e": 2500,
"s": 957,
"text": null
},
{
"code": null,
"e": 2554,
"s": 2500,
"text": "Add ‘completed’ class to the steps which recompleted."
},
{
"code": null,
"e": 2604,
"s": 2554,
"text": "Add ‘active’ class to the step which is on going."
},
{
"code": null,
"e": 2670,
"s": 2604,
"text": "Add ‘disabled’ class to the step which are after the active step."
},
{
"code": null,
"e": 2678,
"s": 2670,
"text": "Output:"
},
{
"code": null,
"e": 2767,
"s": 2678,
"text": "For showing these steps in vertical order replace ‘ordered’ class with ‘vertical’ class."
},
{
"code": null,
"e": 2821,
"s": 2767,
"text": "Example 3: This example creating the Steps with Icon."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></head> <body> <div class=\"ui container\"> <h2>Steps</h2> <div class=\"ui ordered steps\"> <div class=\"completed step\"> <i class=\"code icon\"></i> <div class=\"content\"> <div class=\"title\">Code</div> <div class=\"description\"> Write Code. </div> </div> </div> <div class=\"completed step\"> <i class=\"terminal icon\"></i> <div class=\"content\"> <div class=\"title\">Compile</div> <div class=\"description\"> Compile Code. </div> </div> </div> <div class=\"step\"> <i class=\"window close icon\"></i> <div class=\"content\"> <div class=\"title\">Fix Error</div> <div class=\"description\"> If it gives error fix </div> </div> </div> <div class=\"disabled step\"> <i class=\"terminal icon\"></i> <div class=\"content\"> <div class=\"title\">Compile Again</div> <div class=\"description\"> Compile Code. </div> </div> </div> <div class=\"disabled step\"> <i class=\"computer icon\"></i> <div class=\"content\"> <div class=\"title\">Output</div> <div class=\"description\"> See the output </div> </div> </div> </div> </div></body> </html>",
"e": 4860,
"s": 2821,
"text": null
},
{
"code": null,
"e": 4868,
"s": 4860,
"text": "Output:"
},
{
"code": null,
"e": 4910,
"s": 4868,
"text": "Note: You can add <a> tag to make it link"
},
{
"code": null,
"e": 4991,
"s": 4910,
"text": "Example 4: This example creating the Completed, active, disabled state in steps."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></head> <body> <div class=\"ui container\"> <h2>Active Step</h2> <div class=\"ui steps\"> <div class=\"active step\"> <i class=\"code icon\"></i> <div class=\"content\"> <div class=\"title\">Coding</div> <div class=\"description\"> Writing the Code </div> </div> </div> </div> <h2>Completed Step</h2> <div class=\"ui steps\"> <div class=\"completed step\"> <i class=\"code icon\"></i> <div class=\"content\"> <div class=\"title\">Coding</div> <div class=\"description\"> Finsished Coding </div> </div> </div> </div> <h2>Disabled Step</h2> <div class=\"ui steps\"> <div class=\"disabled step\"> <i class=\"code icon\"></i> <div class=\"content\"> <div class=\"title\">Coding</div> <div class=\"description\"> Pending </div> </div> </div> </div> </div></body> </html>",
"e": 6513,
"s": 4991,
"text": null
},
{
"code": null,
"e": 6521,
"s": 6513,
"text": "Output:"
},
{
"code": null,
"e": 6527,
"s": 6521,
"text": "Note:"
},
{
"code": null,
"e": 6586,
"s": 6527,
"text": "You can add stackable class to make group steps stackable."
},
{
"code": null,
"e": 6712,
"s": 6586,
"text": "You can add ‘UI tiny steps’ class for steps to show them tiny for another size, just replace tiny with small, large, massive."
},
{
"code": null,
"e": 6724,
"s": 6712,
"text": "Semantic-UI"
},
{
"code": null,
"e": 6728,
"s": 6724,
"text": "CSS"
},
{
"code": null,
"e": 6745,
"s": 6728,
"text": "Web Technologies"
}
] |
Kotlin Sealed Classes
|
30 Jun, 2022
Kotlin provides an important new type of class that is not present in Java. These are known as sealed classes. As the word sealed suggests, sealed classes conform to restricted or bounded class hierarchies. A sealed class defines a set of subclasses within it. It is used when it is known in advance that a type will conform to one of the subclass types. Sealed classes ensure type safety by restricting the types to be matched at compile-time rather than at runtime.
Syntax: Declaration of sealed class
sealed class Demo
To define a sealed class, just precede the class modifier with the sealed keyword. The sealed classes also have one another distinct feature, their constructors are protected by default. A sealed class is implicitly abstract and hence it cannot be instantiated.
sealed class Demo
fun main(args: Array)
{
var d = Demo() //compiler error
}
Example: Kotlin program of sealed class
Kotlin
sealed class Demo { class A:Demo(){ fun display(){ println("Subclass A of Sealed class Demo ") } } class B:Demo(){ fun display(){ println("Subclass B of sealed class Demo") } }} fun main(args: Array<String>){ val obj =Demo.B() obj.display() val obj1=Demo.A() obj1.display()}
Output:
Subclass B of sealed class Demo
Subclass A of sealed class Demo
Note: All the subclasses of the sealed class must be defined within the same Kotlin file. However, it not necessary to define them within the sealed class, they can be defined in any scope where the sealed class is visible.
Example:
// A sealed class with a single subclass defined inside
sealed class ABC {
class X: ABC(){...}
}
// Another subclass of the sealed class defined
class Y: ABC() {
class Z: ABC() // This will cause an error. Sealed class is not visible here
}
Remember Sealed class with when a sealed class is most commonly used with a when clause, as the types to which a sealed class reference can conform to are limited. This completely eliminates the use of else clause.
Example: demonstrate sealed classes with a when clause
Java
// A sealed class with a string propertysealed class Fruit(val x : String){ // Two subclasses of sealed class defined within class Apple : Fruit(" Apple& quot;) class Mango : Fruit(" Mango& quot;)} // A subclass defined outside the sealed classclass Pomegranate: Fruit("Pomegranate& quot;) // A function to take in an object of type Fruit// And to display an appropriate message depending on the type of Fruitfun display(fruit: Fruit){ when(fruit) { is Fruit.Apple - > println("${fruit.x} is good for iron") is Fruit.Mango -> println(" ${ fruit.x } is delicious & quot;) is Pomegranate - > println("${fruit.x} is good for vitamin d") }}fun main(){ // Objects of different subclasses created val obj = Fruit.Apple() val obj1 = Fruit.Mango() val obj2 = Pomegranate() // Function called with different objects display(obj) display(obj1) display(obj2)}
Output:
Apple is good for iron
Mango is delicious
Pomegranate is good for vitamin d
gopal awasthi
reddygofr7p
Kotlin OOPs
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 7 Books to Learn and Master Kotlin
Download Image From URL in Android
Kotlin generics
Android - RecyclerView using GridLayoutManager with Kotlin
Bundle in Android with Example
MVP (Model View Presenter) Architecture Pattern in Android with Example
Kotlin list : listOf()
How to Get Current Location in Android?
Understanding Activity Lifecycle to Retain UI Data when Back Pressed in Android
Java Interoperability - Calling Java from Kotlin
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 496,
"s": 28,
"text": "Kotlin provides an important new type of class that is not present in Java. These are known as sealed classes. As the word sealed suggests, sealed classes conform to restricted or bounded class hierarchies. A sealed class defines a set of subclasses within it. It is used when it is known in advance that a type will conform to one of the subclass types. Sealed classes ensure type safety by restricting the types to be matched at compile-time rather than at runtime."
},
{
"code": null,
"e": 532,
"s": 496,
"text": "Syntax: Declaration of sealed class"
},
{
"code": null,
"e": 550,
"s": 532,
"text": "sealed class Demo"
},
{
"code": null,
"e": 812,
"s": 550,
"text": "To define a sealed class, just precede the class modifier with the sealed keyword. The sealed classes also have one another distinct feature, their constructors are protected by default. A sealed class is implicitly abstract and hence it cannot be instantiated."
},
{
"code": null,
"e": 898,
"s": 812,
"text": "sealed class Demo\nfun main(args: Array)\n{\n var d = Demo() //compiler error \n}"
},
{
"code": null,
"e": 940,
"s": 898,
"text": "Example: Kotlin program of sealed class "
},
{
"code": null,
"e": 947,
"s": 940,
"text": "Kotlin"
},
{
"code": "sealed class Demo { class A:Demo(){ fun display(){ println(\"Subclass A of Sealed class Demo \") } } class B:Demo(){ fun display(){ println(\"Subclass B of sealed class Demo\") } }} fun main(args: Array<String>){ val obj =Demo.B() obj.display() val obj1=Demo.A() obj1.display()}",
"e": 1296,
"s": 947,
"text": null
},
{
"code": null,
"e": 1304,
"s": 1296,
"text": "Output:"
},
{
"code": null,
"e": 1368,
"s": 1304,
"text": "Subclass B of sealed class Demo\nSubclass A of sealed class Demo"
},
{
"code": null,
"e": 1592,
"s": 1368,
"text": "Note: All the subclasses of the sealed class must be defined within the same Kotlin file. However, it not necessary to define them within the sealed class, they can be defined in any scope where the sealed class is visible."
},
{
"code": null,
"e": 1601,
"s": 1592,
"text": "Example:"
},
{
"code": null,
"e": 1848,
"s": 1601,
"text": "// A sealed class with a single subclass defined inside\nsealed class ABC {\n class X: ABC(){...}\n}\n\n// Another subclass of the sealed class defined\nclass Y: ABC() {\n class Z: ABC() // This will cause an error. Sealed class is not visible here\n}"
},
{
"code": null,
"e": 2064,
"s": 1848,
"text": "Remember Sealed class with when a sealed class is most commonly used with a when clause, as the types to which a sealed class reference can conform to are limited. This completely eliminates the use of else clause. "
},
{
"code": null,
"e": 2119,
"s": 2064,
"text": "Example: demonstrate sealed classes with a when clause"
},
{
"code": null,
"e": 2124,
"s": 2119,
"text": "Java"
},
{
"code": "// A sealed class with a string propertysealed class Fruit(val x : String){ // Two subclasses of sealed class defined within class Apple : Fruit(\" Apple& quot;) class Mango : Fruit(\" Mango& quot;)} // A subclass defined outside the sealed classclass Pomegranate: Fruit(\"Pomegranate& quot;) // A function to take in an object of type Fruit// And to display an appropriate message depending on the type of Fruitfun display(fruit: Fruit){ when(fruit) { is Fruit.Apple - > println(\"${fruit.x} is good for iron\") is Fruit.Mango -> println(\" ${ fruit.x } is delicious & quot;) is Pomegranate - > println(\"${fruit.x} is good for vitamin d\") }}fun main(){ // Objects of different subclasses created val obj = Fruit.Apple() val obj1 = Fruit.Mango() val obj2 = Pomegranate() // Function called with different objects display(obj) display(obj1) display(obj2)}",
"e": 3072,
"s": 2124,
"text": null
},
{
"code": null,
"e": 3080,
"s": 3072,
"text": "Output:"
},
{
"code": null,
"e": 3156,
"s": 3080,
"text": "Apple is good for iron\nMango is delicious\nPomegranate is good for vitamin d"
},
{
"code": null,
"e": 3170,
"s": 3156,
"text": "gopal awasthi"
},
{
"code": null,
"e": 3182,
"s": 3170,
"text": "reddygofr7p"
},
{
"code": null,
"e": 3194,
"s": 3182,
"text": "Kotlin OOPs"
},
{
"code": null,
"e": 3201,
"s": 3194,
"text": "Picked"
},
{
"code": null,
"e": 3208,
"s": 3201,
"text": "Kotlin"
},
{
"code": null,
"e": 3306,
"s": 3208,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3345,
"s": 3306,
"text": "Top 7 Books to Learn and Master Kotlin"
},
{
"code": null,
"e": 3380,
"s": 3345,
"text": "Download Image From URL in Android"
},
{
"code": null,
"e": 3396,
"s": 3380,
"text": "Kotlin generics"
},
{
"code": null,
"e": 3455,
"s": 3396,
"text": "Android - RecyclerView using GridLayoutManager with Kotlin"
},
{
"code": null,
"e": 3486,
"s": 3455,
"text": "Bundle in Android with Example"
},
{
"code": null,
"e": 3558,
"s": 3486,
"text": "MVP (Model View Presenter) Architecture Pattern in Android with Example"
},
{
"code": null,
"e": 3581,
"s": 3558,
"text": "Kotlin list : listOf()"
},
{
"code": null,
"e": 3621,
"s": 3581,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 3701,
"s": 3621,
"text": "Understanding Activity Lifecycle to Retain UI Data when Back Pressed in Android"
}
] |
Array Partition I in Python
|
Suppose we have an array of 2n number of integers, we have to group these integers into n pairs of integer, like (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i in range 1 to n as large as possible. So if the input is [1, 4, 3, 2], then output will be 4. So n is 2. And the maximum sum of pairs is 4. This is min(1, 2) + min(3, 4) = 4
To solve this, we will follow these steps −
let n is the size of the array
sort the array
answer := 0
for i in range 0 to n, jump by 2answer := answer + array[i]
answer := answer + array[i]
return answer
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def arrayPairSum(self, a):
"""
:type nums: List[int]
:rtype: int
"""
n = len(a)
a.sort()
ans = 0
for i in range(0,n,2):
ans += a[i]
return ans
ob1 = Solution()
print(ob1.arrayPairSum([1,4,3,2]))
[1,4,3,2]
4
|
[
{
"code": null,
"e": 1549,
"s": 1187,
"text": "Suppose we have an array of 2n number of integers, we have to group these integers into n pairs of integer, like (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i in range 1 to n as large as possible. So if the input is [1, 4, 3, 2], then output will be 4. So n is 2. And the maximum sum of pairs is 4. This is min(1, 2) + min(3, 4) = 4"
},
{
"code": null,
"e": 1593,
"s": 1549,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1624,
"s": 1593,
"text": "let n is the size of the array"
},
{
"code": null,
"e": 1639,
"s": 1624,
"text": "sort the array"
},
{
"code": null,
"e": 1651,
"s": 1639,
"text": "answer := 0"
},
{
"code": null,
"e": 1711,
"s": 1651,
"text": "for i in range 0 to n, jump by 2answer := answer + array[i]"
},
{
"code": null,
"e": 1739,
"s": 1711,
"text": "answer := answer + array[i]"
},
{
"code": null,
"e": 1753,
"s": 1739,
"text": "return answer"
},
{
"code": null,
"e": 1823,
"s": 1753,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1834,
"s": 1823,
"text": " Live Demo"
},
{
"code": null,
"e": 2119,
"s": 1834,
"text": "class Solution(object):\n def arrayPairSum(self, a):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n = len(a)\n a.sort()\n ans = 0\n for i in range(0,n,2):\n ans += a[i]\n return ans\nob1 = Solution()\nprint(ob1.arrayPairSum([1,4,3,2]))"
},
{
"code": null,
"e": 2129,
"s": 2119,
"text": "[1,4,3,2]"
},
{
"code": null,
"e": 2131,
"s": 2129,
"text": "4"
}
] |
How to delete last N rows from Numpy array?
|
28 Apr, 2021
In this article, we will discuss how to delete the last N rows from the NumPy array.
Slicing is an indexing operation that is used to iterate over an array.
Syntax: array_name[start:stop]
where start is the start is the index and stop is the last index.
We can also do negative slicing in Python. It is denoted by the below syntax.
Syntax: array_name[: -n]
where, n is the number of rows from last to be deleted.
Example1:
We are going to create an array with 6 rows and 3 columns and delete last N rows using slicing.
Python3
# importing numpy moduleimport numpy as np # create an array with 6 rows and 3 columnsa = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]) print(a) # delete last 1 st rowprint("data after deleting last one row ", a[:-1]) # delete last 2 nd rowprint("data after deleting last two rows ", a[:-2]) # delete last 3 rd rowprint("data after deleting last theww rows ", a[:-3]) # delete last 4 th rowprint("data after deleting last four rows ", a[:-4]) # delete last 5 th rowprint("data after deleting last five rows ", a[:-5]) # delete last 6 th rowprint("data after deleting last six rows ", a[:-6])
Output:
Example 2:
We use for loop to iterate over the elements and use the slice operator, we are going to delete the data and then print the data.
Python3
# importing numpy moduleimport numpy as np # create an array with 5 rows and # 4 columnsa = np.array([[21, 7, 8, 9], [34, 10, 11, 12], [1, 3, 14, 15], [1, 6, 17, 18], [4, 5, 6, 7]]) # use for loop to iterate over the# elementsfor i in range(1, len(a)+1): print("Iteration No", i, "deleted", i, "Rows") print("Remaining data present in the array is\n ", a[:-i])
Output:
Example 3:
We can also specify the elements that we need and store them into another array variable using the slice operator. In this way, we will not get the last N rows (delete those).
Python3
# importing numpy moduleimport numpy as np # create an array with 5 rows and # 4 columnsa = np.array([[21, 7, 8, 9], [34, 10, 11, 12], [1, 3, 14, 15], [1, 6, 17, 18], [4, 5, 6, 7]]) # place first 2 rows in b variable # using slice operatorb = a[:2] print(b)
Output:
[[21 7 8 9]
[34 10 11 12]]
It is used to delete the elements in a NumPy array based on the row number.
Syntax: numpy.delete(array_name,[rownumber1,rownumber2,.,rownumber n],axis)
Parameters:
array_name is the name of the array.
row numbers is the row values
axis specifies row or columnaxis=0 specifies rowaxis=1 specifies column
axis=0 specifies row
axis=1 specifies column
Here we are going to delete the last rows so specify the rows numbers in the list.
Example 1: Delete last three rows
Python3
# importing numpy moduleimport numpy as np # create an array with 5 rows and # 4 columnsa = np.array([[21, 7, 8, 9], [34, 10, 11, 12], [1, 3, 14, 15], [1, 6, 17, 18], [4, 5, 6, 7]]) # delete last three rows# using numpy.deletea = np.delete(a, [2, 3, 4], 0)print(a)
Output:
[[21 7 8 9]
[34 10 11 12]]
Example 2: Delete all rows
Python3
# importing numpy moduleimport numpy as np # create an array with 5 rows and 4 columnsa = np.array([[21, 7, 8, 9], [34, 10, 11, 12], [1, 3, 14, 15], [1, 6, 17, 18], [4, 5, 6, 7]]) # delete last three rows# using numpy.deletea = np.delete(a, [0, 1, 2, 3, 4], 0)print(a)
Output:
[ ]
Picked
Python numpy-Indexing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 113,
"s": 28,
"text": "In this article, we will discuss how to delete the last N rows from the NumPy array."
},
{
"code": null,
"e": 185,
"s": 113,
"text": "Slicing is an indexing operation that is used to iterate over an array."
},
{
"code": null,
"e": 217,
"s": 185,
"text": " Syntax: array_name[start:stop]"
},
{
"code": null,
"e": 283,
"s": 217,
"text": "where start is the start is the index and stop is the last index."
},
{
"code": null,
"e": 361,
"s": 283,
"text": "We can also do negative slicing in Python. It is denoted by the below syntax."
},
{
"code": null,
"e": 386,
"s": 361,
"text": "Syntax: array_name[: -n]"
},
{
"code": null,
"e": 442,
"s": 386,
"text": "where, n is the number of rows from last to be deleted."
},
{
"code": null,
"e": 452,
"s": 442,
"text": "Example1:"
},
{
"code": null,
"e": 548,
"s": 452,
"text": "We are going to create an array with 6 rows and 3 columns and delete last N rows using slicing."
},
{
"code": null,
"e": 556,
"s": 548,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # create an array with 6 rows and 3 columnsa = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]) print(a) # delete last 1 st rowprint(\"data after deleting last one row \", a[:-1]) # delete last 2 nd rowprint(\"data after deleting last two rows \", a[:-2]) # delete last 3 rd rowprint(\"data after deleting last theww rows \", a[:-3]) # delete last 4 th rowprint(\"data after deleting last four rows \", a[:-4]) # delete last 5 th rowprint(\"data after deleting last five rows \", a[:-5]) # delete last 6 th rowprint(\"data after deleting last six rows \", a[:-6])",
"e": 1220,
"s": 556,
"text": null
},
{
"code": null,
"e": 1228,
"s": 1220,
"text": "Output:"
},
{
"code": null,
"e": 1240,
"s": 1228,
"text": "Example 2: "
},
{
"code": null,
"e": 1370,
"s": 1240,
"text": "We use for loop to iterate over the elements and use the slice operator, we are going to delete the data and then print the data."
},
{
"code": null,
"e": 1378,
"s": 1370,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # create an array with 5 rows and # 4 columnsa = np.array([[21, 7, 8, 9], [34, 10, 11, 12], [1, 3, 14, 15], [1, 6, 17, 18], [4, 5, 6, 7]]) # use for loop to iterate over the# elementsfor i in range(1, len(a)+1): print(\"Iteration No\", i, \"deleted\", i, \"Rows\") print(\"Remaining data present in the array is\\n \", a[:-i])",
"e": 1775,
"s": 1378,
"text": null
},
{
"code": null,
"e": 1783,
"s": 1775,
"text": "Output:"
},
{
"code": null,
"e": 1794,
"s": 1783,
"text": "Example 3:"
},
{
"code": null,
"e": 1970,
"s": 1794,
"text": "We can also specify the elements that we need and store them into another array variable using the slice operator. In this way, we will not get the last N rows (delete those)."
},
{
"code": null,
"e": 1978,
"s": 1970,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # create an array with 5 rows and # 4 columnsa = np.array([[21, 7, 8, 9], [34, 10, 11, 12], [1, 3, 14, 15], [1, 6, 17, 18], [4, 5, 6, 7]]) # place first 2 rows in b variable # using slice operatorb = a[:2] print(b)",
"e": 2266,
"s": 1978,
"text": null
},
{
"code": null,
"e": 2274,
"s": 2266,
"text": "Output:"
},
{
"code": null,
"e": 2305,
"s": 2274,
"text": "[[21 7 8 9]\n [34 10 11 12]]"
},
{
"code": null,
"e": 2381,
"s": 2305,
"text": "It is used to delete the elements in a NumPy array based on the row number."
},
{
"code": null,
"e": 2457,
"s": 2381,
"text": "Syntax: numpy.delete(array_name,[rownumber1,rownumber2,.,rownumber n],axis)"
},
{
"code": null,
"e": 2469,
"s": 2457,
"text": "Parameters:"
},
{
"code": null,
"e": 2506,
"s": 2469,
"text": "array_name is the name of the array."
},
{
"code": null,
"e": 2536,
"s": 2506,
"text": "row numbers is the row values"
},
{
"code": null,
"e": 2608,
"s": 2536,
"text": "axis specifies row or columnaxis=0 specifies rowaxis=1 specifies column"
},
{
"code": null,
"e": 2629,
"s": 2608,
"text": "axis=0 specifies row"
},
{
"code": null,
"e": 2653,
"s": 2629,
"text": "axis=1 specifies column"
},
{
"code": null,
"e": 2736,
"s": 2653,
"text": "Here we are going to delete the last rows so specify the rows numbers in the list."
},
{
"code": null,
"e": 2770,
"s": 2736,
"text": "Example 1: Delete last three rows"
},
{
"code": null,
"e": 2778,
"s": 2770,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # create an array with 5 rows and # 4 columnsa = np.array([[21, 7, 8, 9], [34, 10, 11, 12], [1, 3, 14, 15], [1, 6, 17, 18], [4, 5, 6, 7]]) # delete last three rows# using numpy.deletea = np.delete(a, [2, 3, 4], 0)print(a)",
"e": 3073,
"s": 2778,
"text": null
},
{
"code": null,
"e": 3081,
"s": 3073,
"text": "Output:"
},
{
"code": null,
"e": 3112,
"s": 3081,
"text": "[[21 7 8 9]\n [34 10 11 12]]"
},
{
"code": null,
"e": 3139,
"s": 3112,
"text": "Example 2: Delete all rows"
},
{
"code": null,
"e": 3147,
"s": 3139,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # create an array with 5 rows and 4 columnsa = np.array([[21, 7, 8, 9], [34, 10, 11, 12], [1, 3, 14, 15], [1, 6, 17, 18], [4, 5, 6, 7]]) # delete last three rows# using numpy.deletea = np.delete(a, [0, 1, 2, 3, 4], 0)print(a)",
"e": 3446,
"s": 3147,
"text": null
},
{
"code": null,
"e": 3454,
"s": 3446,
"text": "Output:"
},
{
"code": null,
"e": 3458,
"s": 3454,
"text": "[ ]"
},
{
"code": null,
"e": 3465,
"s": 3458,
"text": "Picked"
},
{
"code": null,
"e": 3487,
"s": 3465,
"text": "Python numpy-Indexing"
},
{
"code": null,
"e": 3500,
"s": 3487,
"text": "Python-numpy"
},
{
"code": null,
"e": 3507,
"s": 3500,
"text": "Python"
}
] |
How to Make a Square Plot With Equal Axes in Matplotlib?
|
29 Oct, 2021
In this article, we are going to discuss how to illustrate a square plot with equal axis using matplotlib module. We can depict a Square plot using matplotlib.axes.Axes.set_aspect() and matplotlib.pyplot.axis() methods.
Syntax: matplotlib.axes.Axes.set_aspect()
Parameters:
aspect : This parameter accepts the following value {‘auto’, ‘equal’} or num.
adjustable : This defines which parameter will be adjusted to meet the required aspect.
anchor : This parameter is used to define where the Axes will be drawn if there is extra space due to aspect constraints.
share: This parameter is used to apply the settings to all shared Axes.
Example 1:
We can generate a square plot using matplotlib.axes.Axes.set_aspect() method. We will assign equal as an aspect argument and box as adjustable argument.
Python3
# import required module# import required modulesimport numpy as npimport matplotlib.pyplot as plt # adjust coordinatesx = y = [i for i in range(0, 6)] # depict illustrationfig = plt.figure()ax = fig.add_subplot()plt.plot(x, y) # square plotax.set_aspect('equal', adjustable='box')plt.show()
Output:
Example 2:
The above example possibly yields a square plot when ranges for the two tomahawks are set to be the equivalent. To produce a square plot in the overall case, we need to physically set the viewpoint proportion utilizing the accompanying order:
axes.set_aspect(1./axes.get_data_ratio())
Python3
# import required modulesimport numpy as npimport matplotlib.pyplot as plt # adjust coordinatesx = y = [i for i in range(0, 6)] # depict illustrationfig = plt.figure()ax = fig.add_subplot()plt.plot(x, y) # square plotax.set_aspect(1.0/ax.get_data_ratio(), adjustable='box')plt.show()
Output:
Syntax: matplotlib.pyplot.axis()
Parameters:
xmin, xmax, ymin, ymax:These parameters can be used to set the axis limits on the graph.
emit:Its a bool value used to notify observers of the axis limit change.
Example 1:
In this example, we pass square as an argument to matplotlib.pyplot.axis(), it illustrates a square plot.
Python3
# import required module# import required modulesimport numpy as npimport matplotlib.pyplot as plt # adjust coordinatesx=y=[i for i in range(0,6)] # plot coordinatesplt.plot(x,y) # square plotplt.axis('square') # depict illustrationplt.show()
Output:
Example 2:
Here is another example to illustrate a square plot using axis() method.
Python3
# importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesx = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]y = [] for i in range(len(x)): y.append(max(0, x[i])) # depicting the visualizationplt.plot(x, y, color='green')plt.xlabel('X')plt.ylabel('Y') # square plotplt.axis('square') # displaying the titleplt.title('ReLU Function')
Output:
sumitgumber28
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 275,
"s": 54,
"text": "In this article, we are going to discuss how to illustrate a square plot with equal axis using matplotlib module. We can depict a Square plot using matplotlib.axes.Axes.set_aspect() and matplotlib.pyplot.axis() methods."
},
{
"code": null,
"e": 317,
"s": 275,
"text": "Syntax: matplotlib.axes.Axes.set_aspect()"
},
{
"code": null,
"e": 330,
"s": 317,
"text": "Parameters: "
},
{
"code": null,
"e": 408,
"s": 330,
"text": "aspect : This parameter accepts the following value {‘auto’, ‘equal’} or num."
},
{
"code": null,
"e": 496,
"s": 408,
"text": "adjustable : This defines which parameter will be adjusted to meet the required aspect."
},
{
"code": null,
"e": 618,
"s": 496,
"text": "anchor : This parameter is used to define where the Axes will be drawn if there is extra space due to aspect constraints."
},
{
"code": null,
"e": 690,
"s": 618,
"text": "share: This parameter is used to apply the settings to all shared Axes."
},
{
"code": null,
"e": 701,
"s": 690,
"text": "Example 1:"
},
{
"code": null,
"e": 854,
"s": 701,
"text": "We can generate a square plot using matplotlib.axes.Axes.set_aspect() method. We will assign equal as an aspect argument and box as adjustable argument."
},
{
"code": null,
"e": 862,
"s": 854,
"text": "Python3"
},
{
"code": "# import required module# import required modulesimport numpy as npimport matplotlib.pyplot as plt # adjust coordinatesx = y = [i for i in range(0, 6)] # depict illustrationfig = plt.figure()ax = fig.add_subplot()plt.plot(x, y) # square plotax.set_aspect('equal', adjustable='box')plt.show()",
"e": 1154,
"s": 862,
"text": null
},
{
"code": null,
"e": 1162,
"s": 1154,
"text": "Output:"
},
{
"code": null,
"e": 1173,
"s": 1162,
"text": "Example 2:"
},
{
"code": null,
"e": 1418,
"s": 1173,
"text": "The above example possibly yields a square plot when ranges for the two tomahawks are set to be the equivalent. To produce a square plot in the overall case, we need to physically set the viewpoint proportion utilizing the accompanying order: "
},
{
"code": null,
"e": 1460,
"s": 1418,
"text": "axes.set_aspect(1./axes.get_data_ratio())"
},
{
"code": null,
"e": 1468,
"s": 1460,
"text": "Python3"
},
{
"code": "# import required modulesimport numpy as npimport matplotlib.pyplot as plt # adjust coordinatesx = y = [i for i in range(0, 6)] # depict illustrationfig = plt.figure()ax = fig.add_subplot()plt.plot(x, y) # square plotax.set_aspect(1.0/ax.get_data_ratio(), adjustable='box')plt.show()",
"e": 1752,
"s": 1468,
"text": null
},
{
"code": null,
"e": 1760,
"s": 1752,
"text": "Output:"
},
{
"code": null,
"e": 1793,
"s": 1760,
"text": "Syntax: matplotlib.pyplot.axis()"
},
{
"code": null,
"e": 1806,
"s": 1793,
"text": "Parameters: "
},
{
"code": null,
"e": 1895,
"s": 1806,
"text": "xmin, xmax, ymin, ymax:These parameters can be used to set the axis limits on the graph."
},
{
"code": null,
"e": 1968,
"s": 1895,
"text": "emit:Its a bool value used to notify observers of the axis limit change."
},
{
"code": null,
"e": 1979,
"s": 1968,
"text": "Example 1:"
},
{
"code": null,
"e": 2085,
"s": 1979,
"text": "In this example, we pass square as an argument to matplotlib.pyplot.axis(), it illustrates a square plot."
},
{
"code": null,
"e": 2093,
"s": 2085,
"text": "Python3"
},
{
"code": "# import required module# import required modulesimport numpy as npimport matplotlib.pyplot as plt # adjust coordinatesx=y=[i for i in range(0,6)] # plot coordinatesplt.plot(x,y) # square plotplt.axis('square') # depict illustrationplt.show()",
"e": 2336,
"s": 2093,
"text": null
},
{
"code": null,
"e": 2348,
"s": 2340,
"text": "Output:"
},
{
"code": null,
"e": 2363,
"s": 2352,
"text": "Example 2:"
},
{
"code": null,
"e": 2438,
"s": 2365,
"text": "Here is another example to illustrate a square plot using axis() method."
},
{
"code": null,
"e": 2448,
"s": 2440,
"text": "Python3"
},
{
"code": "# importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesx = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]y = [] for i in range(len(x)): y.append(max(0, x[i])) # depicting the visualizationplt.plot(x, y, color='green')plt.xlabel('X')plt.ylabel('Y') # square plotplt.axis('square') # displaying the titleplt.title('ReLU Function')",
"e": 2798,
"s": 2448,
"text": null
},
{
"code": null,
"e": 2806,
"s": 2798,
"text": "Output:"
},
{
"code": null,
"e": 2820,
"s": 2806,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2827,
"s": 2820,
"text": "Picked"
},
{
"code": null,
"e": 2845,
"s": 2827,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2852,
"s": 2845,
"text": "Python"
},
{
"code": null,
"e": 2950,
"s": 2852,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2982,
"s": 2950,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3009,
"s": 2982,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3040,
"s": 3009,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3061,
"s": 3040,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3117,
"s": 3061,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3140,
"s": 3117,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3182,
"s": 3140,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3224,
"s": 3182,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3263,
"s": 3224,
"text": "Python | datetime.timedelta() function"
}
] |
Fascinating Number
|
14 May, 2021
Given a number N, the task is to check whether it is fascinating or not. Fascinating Number: When a number( 3 digits or more ) is multiplied by 2 and 3, and when both these products are concatenated with the original number, then it results in all digits from 1 to 9 present exactly once. There could be any number of zeros and are ignored. Examples:
Input: 192 Output: Yes After multiplication with 2 and 3, and concatenating with original number, resultant number is 192384576 which contains all digits from 1 to 9.Input: 853 Output: No After multiplication with 2 and 3, and concatenating with original number, the resultant number is 85317062559. In this, number 4 is missing and the number 5 has appeared multiple times.
Approach:
Check if the given number has three digits or more. If not, print No.Else, Multiply the given number with 2 and 3.Concatenate these products with the given number to form a string.Traverse this string, keep the frequency count of the digits.Print No if any digit is missing or has appeared multiple times.Else, print Yes.
Check if the given number has three digits or more. If not, print No.
Else, Multiply the given number with 2 and 3.
Concatenate these products with the given number to form a string.
Traverse this string, keep the frequency count of the digits.
Print No if any digit is missing or has appeared multiple times.
Else, print Yes.
Below is the implementation of above approach:
C++14
Java
Python 3
C#
PHP
Javascript
// C++ program to implement// fascinating number#include <bits/stdc++.h>using namespace std; // function to check if number// is fascinating or notbool isFascinating(int num){ // frequency count array // using 1 indexing int freq[10] = {0}; // obtaining the resultant number // using string concatenation string val = "" + to_string(num) + to_string(num * 2) + to_string(num * 3); // Traversing the string // character by character for (int i = 0; i < val.length(); i++) { // gives integer value of // a character digit int digit = val[i] - '0'; // To check if any digit has // appeared multiple times if (freq[digit] and digit != 0 > 0) return false; else freq[digit]++; } // Traversing through freq array to // check if any digit was missing for (int i = 1; i < 10; i++) { if (freq[i] == 0) return false; } return true;} // Driver codeint main(){ // Input number int num = 192; // Not a valid number if (num < 100) cout << "No" << endl; else { // Calling the function to // check if input number // is fascinating or not bool ans = isFascinating(num); if (ans) cout << "Yes"; else cout << "No"; }} // This code is contributed// by Subhadeep
// Java program to implement// fascinating numberimport java.io.*;import java.util.*; public class GFG { // function to check if number // is fascinating or not public static boolean isFascinating( int num) { // frequency count array //using 1 indexing int[] freq = new int[10]; // obtaining the resultant number // using string concatenation String val = "" + num + num * 2 + num * 3; // Traversing the string character //by character for (int i = 0; i < val.length(); i++) { // gives integer value of //a character digit int digit = val.charAt(i) - '0'; // To check if any digit has // appeared multiple times if (freq[digit]>0 && digit != 0) return false; else freq[digit]++; } // Traversing through freq array to // check if any digit was missing for (int i = 1; i < freq.length; i++) { if (freq[i] == 0) return false; } return true; } // Driver code public static void main(String args[]) { // Input number int num = 192; // Not a valid number if (num < 100) System.out.println("No"); else { // Calling the function to check // if input number is fascinating or not boolean ans = isFascinating(num); if (ans) System.out.println("Yes"); else System.out.println("No"); } }}
# Python 3 program to implement# fascinating number # function to check if number# is fascinating or notdef isFascinating(num) : # frequency count array # using 1 indexing freq = [0] * 10 # obtaining the resultant number # using string concatenation val = (str(num) + str(num * 2) + str(num * 3)) # Traversing the string # character by character for i in range(len(val)) : # gives integer value of # a character digit digit = int(val[i]) # To check if any digit has # appeared multiple times if freq[digit] and digit != 0 > 0 : return False else : freq[digit] += 1 # Traversing through freq array to # check if any digit was missing for i in range(1, 10) : if freq[i] == 0 : return False return True # Driver Codeif __name__ == "__main__" : # Input number num = 192 # Not a valid number if num < 100 : print("No") else : # Calling the function to # check if input number # is fascinating or not ans = isFascinating(num) if ans : print("Yes") else : print("No") # This code is contributed by ANKITRAI1
// C# program to implement// fascinating numberusing System; class GFG{ // function to check if number// is fascinating or notpublic static bool isFascinating(int num){ // frequency count array // using 1 indexing int[] freq = new int[10]; // obtaining the resultant number // using string concatenation String val = "" + num.ToString() + (num * 2).ToString() + (num * 3).ToString(); // Traversing the string // character by character for (int i = 0; i < val.Length; i++) { // gives integer value of // a character digit int digit = val[i] - '0'; // To check if any digit has // appeared multiple times if (freq[digit] && digit != 0 > 0 ) return false; else freq[digit]++; } // Traversing through freq array to // check if any digit was missing for (int i = 1; i < freq.Length; i++) { if (freq[i] == 0) return false; } return true;} // Driver codestatic void Main(){ // Input number int num = 192; // Not a valid number if (num < 100) Console.WriteLine("No"); else { // Calling the function to check // if input number is fascinating or not bool ans = isFascinating(num); if (ans) Console.WriteLine("Yes"); else Console.WriteLine("No"); }}} // This code is contributed by mits
<?php// PHP program to implement// fascinating number // function to check if number// is fascinating or notfunction isFascinating($num){ // frequency count array // using 1 indexing $freq = array_fill(0, 10, NULL); // obtaining the resultant number // using string concatenation $val = "" . $num . ($num * 2). ($num * 3); // Traversing the string // character by character for ($i = 0; $i < strlen($val); $i++) { // gives integer value of // a character digit $digit = $val[$i] - '0'; // To check if any digit has // appeared multiple times if ($freq[$digit] > 0 && $digit != 0) return false; else $freq[$digit]++; } // Traversing through freq array to // check if any digit was missing for ($i = 1; $i < 10; $i++) { if ($freq[$i] == 0) return false; } return true;} // Driver code // Input number$num = 192; // Not a valid numberif ($num < 100) echo "No" ; else{ // Calling the function to // check if input number // is fascinating or not $ans = isFascinating($num); if ($ans) echo "Yes"; else echo "No";} // This code is contributed// by ChitraNayal?>
<script> // Javascript program to implement// fascinating number // function to check if number // is fascinating or not function isFascinating(num) { // frequency count array //using 1 indexing let freq = new Array(10); for(let i=0;i<freq.length;i++) { freq[i]=0; } // obtaining the resultant number // using string concatenation let val = "" + num + num * 2 + num * 3; // Traversing the string character //by character for (let i = 0; i < val.length; i++) { // gives integer value of //a character digit let digit = val[i].charCodeAt(0) - '0'.charCodeAt(0); // To check if any digit has // appeared multiple times if (freq[digit]>0 && digit != 0) return false; else freq[digit]++; } // Traversing through freq array to // check if any digit was missing for (let i = 1; i < freq.length; i++) { if (freq[i] == 0) return false; } return true; } // Driver code // Input number let num = 192; // Not a valid number if (num < 100) document.write("No"); else { // Calling the function to check // if input number is fascinating or not let ans = isFascinating(num); if (ans) document.write("Yes"); else document.write("No"); } // This code is contributed by rag2127 </script>
Yes
rachana soma
Mithun Kumar
tufan_gupta2000
ankthon
ukasp
sourav23
saunaknandi021000
rag2127
C-String-Question
Hash
Numbers
Arrays
Mathematical
Arrays
Hash
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Coin Change | DP-7
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 407,
"s": 54,
"text": "Given a number N, the task is to check whether it is fascinating or not. Fascinating Number: When a number( 3 digits or more ) is multiplied by 2 and 3, and when both these products are concatenated with the original number, then it results in all digits from 1 to 9 present exactly once. There could be any number of zeros and are ignored. Examples: "
},
{
"code": null,
"e": 784,
"s": 407,
"text": "Input: 192 Output: Yes After multiplication with 2 and 3, and concatenating with original number, resultant number is 192384576 which contains all digits from 1 to 9.Input: 853 Output: No After multiplication with 2 and 3, and concatenating with original number, the resultant number is 85317062559. In this, number 4 is missing and the number 5 has appeared multiple times. "
},
{
"code": null,
"e": 798,
"s": 786,
"text": "Approach: "
},
{
"code": null,
"e": 1120,
"s": 798,
"text": "Check if the given number has three digits or more. If not, print No.Else, Multiply the given number with 2 and 3.Concatenate these products with the given number to form a string.Traverse this string, keep the frequency count of the digits.Print No if any digit is missing or has appeared multiple times.Else, print Yes."
},
{
"code": null,
"e": 1190,
"s": 1120,
"text": "Check if the given number has three digits or more. If not, print No."
},
{
"code": null,
"e": 1236,
"s": 1190,
"text": "Else, Multiply the given number with 2 and 3."
},
{
"code": null,
"e": 1303,
"s": 1236,
"text": "Concatenate these products with the given number to form a string."
},
{
"code": null,
"e": 1365,
"s": 1303,
"text": "Traverse this string, keep the frequency count of the digits."
},
{
"code": null,
"e": 1430,
"s": 1365,
"text": "Print No if any digit is missing or has appeared multiple times."
},
{
"code": null,
"e": 1447,
"s": 1430,
"text": "Else, print Yes."
},
{
"code": null,
"e": 1496,
"s": 1447,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 1502,
"s": 1496,
"text": "C++14"
},
{
"code": null,
"e": 1507,
"s": 1502,
"text": "Java"
},
{
"code": null,
"e": 1516,
"s": 1507,
"text": "Python 3"
},
{
"code": null,
"e": 1519,
"s": 1516,
"text": "C#"
},
{
"code": null,
"e": 1523,
"s": 1519,
"text": "PHP"
},
{
"code": null,
"e": 1534,
"s": 1523,
"text": "Javascript"
},
{
"code": "// C++ program to implement// fascinating number#include <bits/stdc++.h>using namespace std; // function to check if number// is fascinating or notbool isFascinating(int num){ // frequency count array // using 1 indexing int freq[10] = {0}; // obtaining the resultant number // using string concatenation string val = \"\" + to_string(num) + to_string(num * 2) + to_string(num * 3); // Traversing the string // character by character for (int i = 0; i < val.length(); i++) { // gives integer value of // a character digit int digit = val[i] - '0'; // To check if any digit has // appeared multiple times if (freq[digit] and digit != 0 > 0) return false; else freq[digit]++; } // Traversing through freq array to // check if any digit was missing for (int i = 1; i < 10; i++) { if (freq[i] == 0) return false; } return true;} // Driver codeint main(){ // Input number int num = 192; // Not a valid number if (num < 100) cout << \"No\" << endl; else { // Calling the function to // check if input number // is fascinating or not bool ans = isFascinating(num); if (ans) cout << \"Yes\"; else cout << \"No\"; }} // This code is contributed// by Subhadeep",
"e": 2958,
"s": 1534,
"text": null
},
{
"code": "// Java program to implement// fascinating numberimport java.io.*;import java.util.*; public class GFG { // function to check if number // is fascinating or not public static boolean isFascinating( int num) { // frequency count array //using 1 indexing int[] freq = new int[10]; // obtaining the resultant number // using string concatenation String val = \"\" + num + num * 2 + num * 3; // Traversing the string character //by character for (int i = 0; i < val.length(); i++) { // gives integer value of //a character digit int digit = val.charAt(i) - '0'; // To check if any digit has // appeared multiple times if (freq[digit]>0 && digit != 0) return false; else freq[digit]++; } // Traversing through freq array to // check if any digit was missing for (int i = 1; i < freq.length; i++) { if (freq[i] == 0) return false; } return true; } // Driver code public static void main(String args[]) { // Input number int num = 192; // Not a valid number if (num < 100) System.out.println(\"No\"); else { // Calling the function to check // if input number is fascinating or not boolean ans = isFascinating(num); if (ans) System.out.println(\"Yes\"); else System.out.println(\"No\"); } }}",
"e": 4643,
"s": 2958,
"text": null
},
{
"code": "# Python 3 program to implement# fascinating number # function to check if number# is fascinating or notdef isFascinating(num) : # frequency count array # using 1 indexing freq = [0] * 10 # obtaining the resultant number # using string concatenation val = (str(num) + str(num * 2) + str(num * 3)) # Traversing the string # character by character for i in range(len(val)) : # gives integer value of # a character digit digit = int(val[i]) # To check if any digit has # appeared multiple times if freq[digit] and digit != 0 > 0 : return False else : freq[digit] += 1 # Traversing through freq array to # check if any digit was missing for i in range(1, 10) : if freq[i] == 0 : return False return True # Driver Codeif __name__ == \"__main__\" : # Input number num = 192 # Not a valid number if num < 100 : print(\"No\") else : # Calling the function to # check if input number # is fascinating or not ans = isFascinating(num) if ans : print(\"Yes\") else : print(\"No\") # This code is contributed by ANKITRAI1",
"e": 5908,
"s": 4643,
"text": null
},
{
"code": "// C# program to implement// fascinating numberusing System; class GFG{ // function to check if number// is fascinating or notpublic static bool isFascinating(int num){ // frequency count array // using 1 indexing int[] freq = new int[10]; // obtaining the resultant number // using string concatenation String val = \"\" + num.ToString() + (num * 2).ToString() + (num * 3).ToString(); // Traversing the string // character by character for (int i = 0; i < val.Length; i++) { // gives integer value of // a character digit int digit = val[i] - '0'; // To check if any digit has // appeared multiple times if (freq[digit] && digit != 0 > 0 ) return false; else freq[digit]++; } // Traversing through freq array to // check if any digit was missing for (int i = 1; i < freq.Length; i++) { if (freq[i] == 0) return false; } return true;} // Driver codestatic void Main(){ // Input number int num = 192; // Not a valid number if (num < 100) Console.WriteLine(\"No\"); else { // Calling the function to check // if input number is fascinating or not bool ans = isFascinating(num); if (ans) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }}} // This code is contributed by mits",
"e": 7357,
"s": 5908,
"text": null
},
{
"code": "<?php// PHP program to implement// fascinating number // function to check if number// is fascinating or notfunction isFascinating($num){ // frequency count array // using 1 indexing $freq = array_fill(0, 10, NULL); // obtaining the resultant number // using string concatenation $val = \"\" . $num . ($num * 2). ($num * 3); // Traversing the string // character by character for ($i = 0; $i < strlen($val); $i++) { // gives integer value of // a character digit $digit = $val[$i] - '0'; // To check if any digit has // appeared multiple times if ($freq[$digit] > 0 && $digit != 0) return false; else $freq[$digit]++; } // Traversing through freq array to // check if any digit was missing for ($i = 1; $i < 10; $i++) { if ($freq[$i] == 0) return false; } return true;} // Driver code // Input number$num = 192; // Not a valid numberif ($num < 100) echo \"No\" ; else{ // Calling the function to // check if input number // is fascinating or not $ans = isFascinating($num); if ($ans) echo \"Yes\"; else echo \"No\";} // This code is contributed// by ChitraNayal?>",
"e": 8615,
"s": 7357,
"text": null
},
{
"code": "<script> // Javascript program to implement// fascinating number // function to check if number // is fascinating or not function isFascinating(num) { // frequency count array //using 1 indexing let freq = new Array(10); for(let i=0;i<freq.length;i++) { freq[i]=0; } // obtaining the resultant number // using string concatenation let val = \"\" + num + num * 2 + num * 3; // Traversing the string character //by character for (let i = 0; i < val.length; i++) { // gives integer value of //a character digit let digit = val[i].charCodeAt(0) - '0'.charCodeAt(0); // To check if any digit has // appeared multiple times if (freq[digit]>0 && digit != 0) return false; else freq[digit]++; } // Traversing through freq array to // check if any digit was missing for (let i = 1; i < freq.length; i++) { if (freq[i] == 0) return false; } return true; } // Driver code // Input number let num = 192; // Not a valid number if (num < 100) document.write(\"No\"); else { // Calling the function to check // if input number is fascinating or not let ans = isFascinating(num); if (ans) document.write(\"Yes\"); else document.write(\"No\"); } // This code is contributed by rag2127 </script>",
"e": 10242,
"s": 8615,
"text": null
},
{
"code": null,
"e": 10246,
"s": 10242,
"text": "Yes"
},
{
"code": null,
"e": 10261,
"s": 10248,
"text": "rachana soma"
},
{
"code": null,
"e": 10274,
"s": 10261,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 10290,
"s": 10274,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 10298,
"s": 10290,
"text": "ankthon"
},
{
"code": null,
"e": 10304,
"s": 10298,
"text": "ukasp"
},
{
"code": null,
"e": 10313,
"s": 10304,
"text": "sourav23"
},
{
"code": null,
"e": 10331,
"s": 10313,
"text": "saunaknandi021000"
},
{
"code": null,
"e": 10339,
"s": 10331,
"text": "rag2127"
},
{
"code": null,
"e": 10357,
"s": 10339,
"text": "C-String-Question"
},
{
"code": null,
"e": 10362,
"s": 10357,
"text": "Hash"
},
{
"code": null,
"e": 10370,
"s": 10362,
"text": "Numbers"
},
{
"code": null,
"e": 10377,
"s": 10370,
"text": "Arrays"
},
{
"code": null,
"e": 10390,
"s": 10377,
"text": "Mathematical"
},
{
"code": null,
"e": 10397,
"s": 10390,
"text": "Arrays"
},
{
"code": null,
"e": 10402,
"s": 10397,
"text": "Hash"
},
{
"code": null,
"e": 10415,
"s": 10402,
"text": "Mathematical"
},
{
"code": null,
"e": 10423,
"s": 10415,
"text": "Numbers"
},
{
"code": null,
"e": 10521,
"s": 10423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10553,
"s": 10521,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 10578,
"s": 10553,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 10625,
"s": 10578,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 10656,
"s": 10625,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 10714,
"s": 10656,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 10744,
"s": 10714,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 10787,
"s": 10744,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10847,
"s": 10787,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10862,
"s": 10847,
"text": "C++ Data Types"
}
] |
Stitching input images (panorama) using OpenCV with C++
|
26 Apr, 2022
This program is intended to create a panorama from a set of images by stitching them together using OpenCV library stitching.hpp and the implementation for the same is done in C++. The program saves the resultant stitched image in the same directory as the program file. If the set of images are not stitched then it exits the program with an error. This error comes due to the fact that the input images don’t have common areas or they don’t share a common patch of pixels.
Steps to implement the code:1) Make sure OpenCV is installed on the local machine
2) Place the input images in the same directory as the program.
3) Compile the code from the command prompt as usual.
4) While running the code give all the input images as arguments.
5) Check the resultant image by the name “result.jpg”
Stitching Pipeline:This image shows the basic architecture of how the stitching algorithm works.It is based on the research paper with title “Automatic Panoramic Image Stitching using Invariant Features” by M. Brown and D. Lowe. Refer to the second link in references.Please refer this opencv.org image for details.
Implementation
CPP
// CPP program to Stitch// input images (panorama) using OpenCV#include <iostream>#include <fstream> // Include header files from OpenCV directory// required to stitch images.#include "opencv2/imgcodecs.hpp"#include "opencv2/highgui.hpp"#include "opencv2/stitching.hpp" using namespace std;using namespace cv; // Define mode for stitching as panorama// (One out of many functions of Stitcher)Stitcher::Mode mode = Stitcher::PANORAMA; // Array for picturesvector<Mat> imgs; int main(int argc, char* argv[]){ // Get all the images that need to be // stitched as arguments from command line for (int i = 1; i < argc; ++i) { // Read the ith argument or image // and push into the image array Mat img = imread(argv[i]); if (img.empty()) { // Exit if image is not present cout << "Can't read image '" << argv[i] << "'\n"; return -1; } imgs.push_back(img); } // Define object to store the stitched image Mat pano; // Create a Stitcher class object with mode panoroma Ptr<Stitcher> stitcher = Stitcher::create(mode, false); // Command to stitch all the images present in the image array Stitcher::Status status = stitcher->stitch(imgs, pano); if (status != Stitcher::OK) { // Check if images could not be stitched // status is OK if images are stitched successfully cout << "Can't stitch images\n"; return -1; } // Store a new image stitched from the given //set of images as "result.jpg" imwrite("result.jpg", pano); // Show the result imshow("Result", pano); waitKey(0); return 0;}
Input Images:
Output:
References:1) http://docs.opencv.org/2.4/modules/stitching/doc/stitching.html
2) http://docs.opencv.org/2.4/modules/stitching/doc/introduction.html
This article is contributed by Shashwat Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
surinderdawra388
Image-Processing
OpenCV
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": "\n26 Apr, 2022"
},
{
"code": null,
"e": 530,
"s": 54,
"text": "This program is intended to create a panorama from a set of images by stitching them together using OpenCV library stitching.hpp and the implementation for the same is done in C++. The program saves the resultant stitched image in the same directory as the program file. If the set of images are not stitched then it exits the program with an error. This error comes due to the fact that the input images don’t have common areas or they don’t share a common patch of pixels. "
},
{
"code": null,
"e": 613,
"s": 530,
"text": "Steps to implement the code:1) Make sure OpenCV is installed on the local machine "
},
{
"code": null,
"e": 678,
"s": 613,
"text": "2) Place the input images in the same directory as the program. "
},
{
"code": null,
"e": 733,
"s": 678,
"text": "3) Compile the code from the command prompt as usual. "
},
{
"code": null,
"e": 800,
"s": 733,
"text": "4) While running the code give all the input images as arguments. "
},
{
"code": null,
"e": 855,
"s": 800,
"text": "5) Check the resultant image by the name “result.jpg” "
},
{
"code": null,
"e": 1172,
"s": 855,
"text": "Stitching Pipeline:This image shows the basic architecture of how the stitching algorithm works.It is based on the research paper with title “Automatic Panoramic Image Stitching using Invariant Features” by M. Brown and D. Lowe. Refer to the second link in references.Please refer this opencv.org image for details. "
},
{
"code": null,
"e": 1188,
"s": 1172,
"text": "Implementation "
},
{
"code": null,
"e": 1192,
"s": 1188,
"text": "CPP"
},
{
"code": "// CPP program to Stitch// input images (panorama) using OpenCV#include <iostream>#include <fstream> // Include header files from OpenCV directory// required to stitch images.#include \"opencv2/imgcodecs.hpp\"#include \"opencv2/highgui.hpp\"#include \"opencv2/stitching.hpp\" using namespace std;using namespace cv; // Define mode for stitching as panorama// (One out of many functions of Stitcher)Stitcher::Mode mode = Stitcher::PANORAMA; // Array for picturesvector<Mat> imgs; int main(int argc, char* argv[]){ // Get all the images that need to be // stitched as arguments from command line for (int i = 1; i < argc; ++i) { // Read the ith argument or image // and push into the image array Mat img = imread(argv[i]); if (img.empty()) { // Exit if image is not present cout << \"Can't read image '\" << argv[i] << \"'\\n\"; return -1; } imgs.push_back(img); } // Define object to store the stitched image Mat pano; // Create a Stitcher class object with mode panoroma Ptr<Stitcher> stitcher = Stitcher::create(mode, false); // Command to stitch all the images present in the image array Stitcher::Status status = stitcher->stitch(imgs, pano); if (status != Stitcher::OK) { // Check if images could not be stitched // status is OK if images are stitched successfully cout << \"Can't stitch images\\n\"; return -1; } // Store a new image stitched from the given //set of images as \"result.jpg\" imwrite(\"result.jpg\", pano); // Show the result imshow(\"Result\", pano); waitKey(0); return 0;}",
"e": 2912,
"s": 1192,
"text": null
},
{
"code": null,
"e": 2926,
"s": 2912,
"text": "Input Images:"
},
{
"code": null,
"e": 2935,
"s": 2926,
"text": " Output:"
},
{
"code": null,
"e": 3018,
"s": 2939,
"text": "References:1) http://docs.opencv.org/2.4/modules/stitching/doc/stitching.html "
},
{
"code": null,
"e": 3089,
"s": 3018,
"text": "2) http://docs.opencv.org/2.4/modules/stitching/doc/introduction.html "
},
{
"code": null,
"e": 3511,
"s": 3089,
"text": "This article is contributed by Shashwat Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3528,
"s": 3511,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3545,
"s": 3528,
"text": "Image-Processing"
},
{
"code": null,
"e": 3552,
"s": 3545,
"text": "OpenCV"
},
{
"code": null,
"e": 3556,
"s": 3552,
"text": "C++"
},
{
"code": null,
"e": 3560,
"s": 3556,
"text": "CPP"
}
] |
Longest subarray with sum divisible by K
|
17 Jun, 2022
Given an arr[] containing n integers and a positive integer k. The problem is to find the longest subarray’s length with the sum of the elements divisible by the given value k.Examples:
Input: arr[] = {2, 7, 6, 1, 4, 5}, k = 3Output: 4Explaination: The subarray is {7, 6, 1, 4} with sum 18, which is divisible by 3.
Input: arr[] = {-2, 2, -5, 12, -11, -1, 7}, k = 3Output: 5
Method 1 (Naive Approach): Consider all the subarrays and return the length of the subarray with a sum divisible by k that has the longest length. Time Complexity: O(n2).
Method 2 (Efficient Approach): Create an array mod_arr[] where mod_arr[i] stores (sum(arr[0]+arr[1]..+arr[i]) % k). Create a hash table having tuple as (ele, i), where ele represents an element of mod_arr[] and i represents the element’s index of first occurrence in mod_arr[]. Now, traverse mod_arr[] from i = 0 to n and follow the steps given below.
If mod_arr[i] == 0, then update max_len = (i + 1).Else if mod_arr[i] is not present in the hash table, then create tuple (mod_arr[i], i) in the hash table.Else, get the hash table’s value associated with mod_arr[i]. Let this be i.If maxLen < (i – idx), then update max_len = (i – idx).Finally, return max_len.
If mod_arr[i] == 0, then update max_len = (i + 1).
Else if mod_arr[i] is not present in the hash table, then create tuple (mod_arr[i], i) in the hash table.
Else, get the hash table’s value associated with mod_arr[i]. Let this be i.
If maxLen < (i – idx), then update max_len = (i – idx).
Finally, return max_len.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the longest subarray// with sum divisible by k #include <bits/stdc++.h>using namespace std; // function to find the longest subarray// with sum divisible by k int longestSubarrWthSumDivByK(int arr[], int n, int k){ // unordered map 'um' implemented as // hash table unordered_map<int, int> um; // 'mod_arr[i]' stores (sum[0..i] % k) int mod_arr[n], max_len = 0; int curr_sum = 0; // traverse arr[] and build up the // array 'mod_arr[]' for (int i = 0; i < n; i++) { curr_sum += arr[i]; // as the sum can be negative, taking modulo twice mod_arr[i] = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible by k if (mod_arr[i] == 0) // update 'max' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.find(mod_arr[i]) == um.end()) um[mod_arr[i]] = i; else // if true, then update 'max' if (max_len < (i - um[mod_arr[i]])) max_len = i - um[mod_arr[i]]; } // return the required length of longest subarray // with sum divisible by 'k' return max_len;} // Driver codeint main(){ int arr[] = {2, 7, 6, 1, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << "Length = " << longestSubarrWthSumDivByK(arr, n, k); return 0; } // Code updated by Kshitij Dwivedi
// Java implementation to find the longest// subarray with sum divisible by kimport java.io.*;import java.util.*; class GfG { // function to find the longest subarray // with sum divisible by k static int longestSubarrWthSumDivByK(int arr[], int n, int k) { // unordered map 'um' implemented as // hash table HashMap<Integer, Integer> um= new HashMap<Integer, Integer>(); // 'mod_arr[i]' stores (sum[0..i] % k) int mod_arr[]= new int[n]; int max_len = 0; int curr_sum = 0; // traverse arr[] and build up the // array 'mod_arr[]' for (int i = 0; i < n; i++) { curr_sum += arr[i]; // as the sum can be negative, // taking modulo twice mod_arr[i] = ((curr_sum % k) + k) % k; // if true then sum(0..i) is // divisible by k if (mod_arr[i] == 0) // update 'max' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.containsKey(mod_arr[i]) == false) um.put(mod_arr[i] , i); else // if true, then update 'max' if (max_len < (i - um.get(mod_arr[i]))) max_len = i - um.get(mod_arr[i]); } // return the required length of longest subarray // with sum divisible by 'k' return max_len; } public static void main (String[] args) { int arr[] = {2, 7, 6, 1, 4, 5}; int n = arr.length; int k = 3; System.out.println("Length = "+ longestSubarrWthSumDivByK(arr, n, k)); }} // This code is contributed by Gitanjali, updated by Kshitij Dwivedi
# Python3 implementation to find the# longest subarray with sum divisible by k # Function to find the longest# subarray with sum divisible by k def longestSubarrWthSumDivByK(arr, n, k): # unordered map 'um' implemented # as hash table um = {} # 'mod_arr[i]' stores (sum[0..i] % k) mod_arr = [0 for i in range(n)] max_len = 0 curr_sum = 0 # Traverse arr[] and build up # the array 'mod_arr[]' for i in range(n): curr_sum += arr[i] # As the sum can be negative, # taking modulo twice mod_arr[i] = ((curr_sum % k) + k) % k # If true then sum(0..i) is # divisible by k if (mod_arr[i] == 0): # Update 'max_len' max_len = i + 1 # If value 'mod_arr[i]' not present in # 'um' then store it in 'um' with index # of its first occurrence elif (mod_arr[i] not in um): um[mod_arr[i]] = i else: # If true, then update 'max_len' if (max_len < (i - um[mod_arr[i]])): max_len = i - um[mod_arr[i]] # Return the required length of longest subarray # with sum divisible by 'k' return max_len # Driver Codeif __name__ == '__main__': arr = [2, 7, 6, 1, 4, 5] n = len(arr) k = 3 print("Length =", longestSubarrWthSumDivByK(arr, n, k)) # This code is contributed by Surendra_Gangwar, updated by Kshitij Dwivedi
using System;using System.Collections.Generic; // C# implementation to find the longest // subarray with sum divisible by k public class GfG{ // function to find the longest subarray // with sum divisible by k public static int longestSubarrWthSumDivByK(int[] arr, int n, int k) { // unordered map 'um' implemented as // hash table Dictionary<int, int> um = new Dictionary<int, int>(); // 'mod_arr[i]' stores (sum[0..i] % k) int[] mod_arr = new int[n]; int max_len = 0; int curr_sum = 0; // traverse arr[] and build up the // array 'mod_arr[]' for (int i = 0; i < n; i++) { curr_sum += arr[i]; // as the sum can be negative, // adjusting and calculating modulo twice mod_arr[i] = ((curr_sum % k) + k) % k; // if true then sum(0..i) is // divisible by k if (mod_arr[i] == 0) { // update 'max_len' max_len = i + 1; } // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.ContainsKey(mod_arr[i]) == false) { um[mod_arr[i]] = i; } else { // if true, then update 'max_len' if (max_len < (i - um[mod_arr[i]])) { max_len = i - um[mod_arr[i]]; } } } // return the required length of longest subarray with // sum divisible by 'k' return max_len; } public static void Main(string[] args) { int[] arr = new int[] {2, 7, 6, 1, 4, 5}; int n = arr.Length; int k = 3; Console.WriteLine("Length = " + longestSubarrWthSumDivByK(arr, n, k)); }} // This code is contributed by Shrikant13, updated by Kshitij Dwivedi
<script> // Javascript implementation to find the longest subarray// with sum divisible by k // function to find the longest subarray// with sum divisible by kfunction longestSubarrWthSumDivByK(arr, n, k){ // unordered map 'um' implemented as // hash table var um = new Map(); // 'mod_arr[i]' stores (sum[0..i] % k) var mod_arr = Array(n), max_len = 0; var curr_sum = 0; // traverse arr[] and build up the // array 'mod_arr[]' for (var i = 0; i < n; i++) { curr_sum += arr[i]; // as the sum can be negative, taking modulo twice mod_arr[i] = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible // by k if (mod_arr[i] == 0) // update 'max_len' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (!um.has(mod_arr[i])) um.set(mod_arr[i] , i); else // if true, then update 'max_len' if (max_len < (i - um.get(mod_arr[i]))) max_len = i - um.get(mod_arr[i]); } // return the required length of longest subarray with // sum divisible by 'k' return max_len;} // Driver program to test abovevar arr = [2, 7, 6, 1, 4, 5];var n = arr.length;var k = 3; document.write( "Length = " + longestSubarrWthSumDivByK(arr, n, k)); // This code is contributed by rrrtnx, and updated by Kshitij Dwivedi</script>
Length = 4
Time Complexity: O(n), as we traverse the input array only once.Auxiliary Space: O(n * k), O(n) for mod_arr[], and O(k) for storing the remainder values in the hash table.
Space Optimized approach: The space optimization for the above approach to O(n) Instead of keeping a separate array to store the modulus of all values, we compute it on the go and store remainders in the hash table.Below is the implementation:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h> using namespace std; // function to find the longest subarray// with sum divisible by kint longestSubarrWthSumDivByK(int arr[], int n, int k){ // unordered map 'um' implemented as // hash table unordered_map<int, int> um; int max_len = 0; int curr_sum = 0; for (int i = 0; i < n; i++) { curr_sum += arr[i]; int mod = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible // by k if (mod == 0) // update 'max_len' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.find(mod) == um.end()) um[mod] = i; else // if true, then update 'max_len' if (max_len < (i - um[mod])) max_len = i - um[mod]; } // return the required length of longest subarray with // sum divisible by 'k' return max_len;} // Driver codeint main(){ int arr[] = {2, 7, 6, 1, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << "Length = " << longestSubarrWthSumDivByK(arr, n, k); return 0;} // Code Updated by Kshitij Dwivedi
/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { static int longestSubarrWthSumDivByK(int arr[], int n, int k) { Map<Integer, Integer> map = new HashMap<>(); int max_len = 0; int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; // to handle negavtive values as well int mod = ((sum % k) + k) % k; if (mod == 0) max_len = i + 1; if (!map.containsKey(mod)) map.put(mod, i); else { int sz = i - map.get(mod); max_len = Math.max(max_len, sz); } } return max_len; } public static void main(String[] args) { int arr[] = {2, 7, 6, 1, 4, 5}; int n = arr.length; int k = 3; System.out.println("Length = " + longestSubarrWthSumDivByK(arr, n, k)); }} // Updated By Kshitij Dwivedi
# function to find the longest subarray# with sum divisible by kdef longestSubarrWthSumDivByK(arr, n, k): # unordered map 'um' implemented as # hash table um = {} max_len = 0 curr_sum = 0 for i in range(n): curr_sum += arr[i] mod = ((curr_sum % k) + k) % k # if true then sum(0..i) is divisible by k if mod == 0: # update 'max_len' max_len = i + 1 # if value 'mod_arr[i]' not present in 'um' # then store it in 'um' with index of its # first occurrence elif mod in um.keys(): if max_len < (i - um[mod]): max_len = i - um[mod] else: um[mod] = i # return the required length of longest subarray with # sum divisible by 'k' return max_len arr = [2, 7, 6, 1, 4, 5]n = len(arr)k = 3print("Length =", longestSubarrWthSumDivByK(arr, n, k)) # This code is contributed by amreshkumar3, and updated by Kshitij Dwivedi
using System;using System.Collections.Generic; // C# implementation to find the longest// subarray with sum divisible by kpublic class GFG { public static int longestSubarrWthSumDivByK(int[] arr, int n, int k) { // unordered map 'um' implemented as // hash table Dictionary<int, int> um = new Dictionary<int, int>(); int max_len = 0; int curr_sum = 0; for (int i = 0; i < n; i++) { curr_sum += arr[i]; int mod = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible // by k if (mod == 0) // update 'max_len' { max_len = i + 1; } // if value 'mod' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.ContainsKey(mod) == false) { um[mod] = i; } else { // if true, then update 'max' if (max_len < (i - um[mod])) { max_len = i - um[mod]; } } } // return the required length of longest subarray with // sum divisible by 'k' return max_len; } public static void Main(string[] args) { int[] arr = new int[] {2, 7, 6, 1, 4, 5}; int n = arr.Length; int k = 3; Console.WriteLine("Length = " + longestSubarrWthSumDivByK(arr, n, k)); }} // This code is contributed by ishankhandelwals and updated by Kshitij Dwivedi
<script>// function to find the longest subarray// with sum divisible by kfunction longestSubarrWthSumDivByK(arr,n,k){ // map 'um' implemented as // hash table let um = new Map(); let max_len = 0; let curr_sum = 0; for (let i = 0; i < n; i++) { curr_sum += arr[i]; let mod = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible // by k if (mod == 0) // update 'max_len' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.has(mod) == false) um.set(mod,i); else // if true, then update 'max' if (max_len < (i - um.get(mod))) max_len = i - um.get(mod); } // required length of longest subarray with // sum divisible by 'k' return max;} // Driver program to test above let arr = [2, 7, 6, 1, 4, 5];let n = arr.length;let k = 3; document.write("Length = " + longestSubarrWthSumDivByK(arr, n, k)); // This code is contributed by shinjanpatra, and updated by Kshitij Dwivedi.</script>
Length = 4
Time Complexity: O(n), as we traverse the input array only once.Auxiliary Space: O(n)
rex_wulf
shrikanth13
SURENDRA_GANGWAR
throne1032
1999shaswat
rrrtnx
surindertarika1234
ayush123ngp
amreshkumar3
shinjanpatra
ishankhandelwals
kshitijdwivedi28
harendrakumar123
Snapdeal
subarray
subarray-sum
Arrays
Hash
Snapdeal
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 238,
"s": 52,
"text": "Given an arr[] containing n integers and a positive integer k. The problem is to find the longest subarray’s length with the sum of the elements divisible by the given value k.Examples:"
},
{
"code": null,
"e": 368,
"s": 238,
"text": "Input: arr[] = {2, 7, 6, 1, 4, 5}, k = 3Output: 4Explaination: The subarray is {7, 6, 1, 4} with sum 18, which is divisible by 3."
},
{
"code": null,
"e": 427,
"s": 368,
"text": "Input: arr[] = {-2, 2, -5, 12, -11, -1, 7}, k = 3Output: 5"
},
{
"code": null,
"e": 598,
"s": 427,
"text": "Method 1 (Naive Approach): Consider all the subarrays and return the length of the subarray with a sum divisible by k that has the longest length. Time Complexity: O(n2)."
},
{
"code": null,
"e": 950,
"s": 598,
"text": "Method 2 (Efficient Approach): Create an array mod_arr[] where mod_arr[i] stores (sum(arr[0]+arr[1]..+arr[i]) % k). Create a hash table having tuple as (ele, i), where ele represents an element of mod_arr[] and i represents the element’s index of first occurrence in mod_arr[]. Now, traverse mod_arr[] from i = 0 to n and follow the steps given below."
},
{
"code": null,
"e": 1260,
"s": 950,
"text": "If mod_arr[i] == 0, then update max_len = (i + 1).Else if mod_arr[i] is not present in the hash table, then create tuple (mod_arr[i], i) in the hash table.Else, get the hash table’s value associated with mod_arr[i]. Let this be i.If maxLen < (i – idx), then update max_len = (i – idx).Finally, return max_len."
},
{
"code": null,
"e": 1311,
"s": 1260,
"text": "If mod_arr[i] == 0, then update max_len = (i + 1)."
},
{
"code": null,
"e": 1417,
"s": 1311,
"text": "Else if mod_arr[i] is not present in the hash table, then create tuple (mod_arr[i], i) in the hash table."
},
{
"code": null,
"e": 1493,
"s": 1417,
"text": "Else, get the hash table’s value associated with mod_arr[i]. Let this be i."
},
{
"code": null,
"e": 1549,
"s": 1493,
"text": "If maxLen < (i – idx), then update max_len = (i – idx)."
},
{
"code": null,
"e": 1574,
"s": 1549,
"text": "Finally, return max_len."
},
{
"code": null,
"e": 1625,
"s": 1574,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1629,
"s": 1625,
"text": "C++"
},
{
"code": null,
"e": 1634,
"s": 1629,
"text": "Java"
},
{
"code": null,
"e": 1642,
"s": 1634,
"text": "Python3"
},
{
"code": null,
"e": 1645,
"s": 1642,
"text": "C#"
},
{
"code": null,
"e": 1656,
"s": 1645,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the longest subarray// with sum divisible by k #include <bits/stdc++.h>using namespace std; // function to find the longest subarray// with sum divisible by k int longestSubarrWthSumDivByK(int arr[], int n, int k){ // unordered map 'um' implemented as // hash table unordered_map<int, int> um; // 'mod_arr[i]' stores (sum[0..i] % k) int mod_arr[n], max_len = 0; int curr_sum = 0; // traverse arr[] and build up the // array 'mod_arr[]' for (int i = 0; i < n; i++) { curr_sum += arr[i]; // as the sum can be negative, taking modulo twice mod_arr[i] = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible by k if (mod_arr[i] == 0) // update 'max' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.find(mod_arr[i]) == um.end()) um[mod_arr[i]] = i; else // if true, then update 'max' if (max_len < (i - um[mod_arr[i]])) max_len = i - um[mod_arr[i]]; } // return the required length of longest subarray // with sum divisible by 'k' return max_len;} // Driver codeint main(){ int arr[] = {2, 7, 6, 1, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << \"Length = \" << longestSubarrWthSumDivByK(arr, n, k); return 0; } // Code updated by Kshitij Dwivedi",
"e": 3264,
"s": 1656,
"text": null
},
{
"code": "// Java implementation to find the longest// subarray with sum divisible by kimport java.io.*;import java.util.*; class GfG { // function to find the longest subarray // with sum divisible by k static int longestSubarrWthSumDivByK(int arr[], int n, int k) { // unordered map 'um' implemented as // hash table HashMap<Integer, Integer> um= new HashMap<Integer, Integer>(); // 'mod_arr[i]' stores (sum[0..i] % k) int mod_arr[]= new int[n]; int max_len = 0; int curr_sum = 0; // traverse arr[] and build up the // array 'mod_arr[]' for (int i = 0; i < n; i++) { curr_sum += arr[i]; // as the sum can be negative, // taking modulo twice mod_arr[i] = ((curr_sum % k) + k) % k; // if true then sum(0..i) is // divisible by k if (mod_arr[i] == 0) // update 'max' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.containsKey(mod_arr[i]) == false) um.put(mod_arr[i] , i); else // if true, then update 'max' if (max_len < (i - um.get(mod_arr[i]))) max_len = i - um.get(mod_arr[i]); } // return the required length of longest subarray // with sum divisible by 'k' return max_len; } public static void main (String[] args) { int arr[] = {2, 7, 6, 1, 4, 5}; int n = arr.length; int k = 3; System.out.println(\"Length = \"+ longestSubarrWthSumDivByK(arr, n, k)); }} // This code is contributed by Gitanjali, updated by Kshitij Dwivedi",
"e": 5203,
"s": 3264,
"text": null
},
{
"code": "# Python3 implementation to find the# longest subarray with sum divisible by k # Function to find the longest# subarray with sum divisible by k def longestSubarrWthSumDivByK(arr, n, k): # unordered map 'um' implemented # as hash table um = {} # 'mod_arr[i]' stores (sum[0..i] % k) mod_arr = [0 for i in range(n)] max_len = 0 curr_sum = 0 # Traverse arr[] and build up # the array 'mod_arr[]' for i in range(n): curr_sum += arr[i] # As the sum can be negative, # taking modulo twice mod_arr[i] = ((curr_sum % k) + k) % k # If true then sum(0..i) is # divisible by k if (mod_arr[i] == 0): # Update 'max_len' max_len = i + 1 # If value 'mod_arr[i]' not present in # 'um' then store it in 'um' with index # of its first occurrence elif (mod_arr[i] not in um): um[mod_arr[i]] = i else: # If true, then update 'max_len' if (max_len < (i - um[mod_arr[i]])): max_len = i - um[mod_arr[i]] # Return the required length of longest subarray # with sum divisible by 'k' return max_len # Driver Codeif __name__ == '__main__': arr = [2, 7, 6, 1, 4, 5] n = len(arr) k = 3 print(\"Length =\", longestSubarrWthSumDivByK(arr, n, k)) # This code is contributed by Surendra_Gangwar, updated by Kshitij Dwivedi",
"e": 6693,
"s": 5203,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // C# implementation to find the longest // subarray with sum divisible by k public class GfG{ // function to find the longest subarray // with sum divisible by k public static int longestSubarrWthSumDivByK(int[] arr, int n, int k) { // unordered map 'um' implemented as // hash table Dictionary<int, int> um = new Dictionary<int, int>(); // 'mod_arr[i]' stores (sum[0..i] % k) int[] mod_arr = new int[n]; int max_len = 0; int curr_sum = 0; // traverse arr[] and build up the // array 'mod_arr[]' for (int i = 0; i < n; i++) { curr_sum += arr[i]; // as the sum can be negative, // adjusting and calculating modulo twice mod_arr[i] = ((curr_sum % k) + k) % k; // if true then sum(0..i) is // divisible by k if (mod_arr[i] == 0) { // update 'max_len' max_len = i + 1; } // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.ContainsKey(mod_arr[i]) == false) { um[mod_arr[i]] = i; } else { // if true, then update 'max_len' if (max_len < (i - um[mod_arr[i]])) { max_len = i - um[mod_arr[i]]; } } } // return the required length of longest subarray with // sum divisible by 'k' return max_len; } public static void Main(string[] args) { int[] arr = new int[] {2, 7, 6, 1, 4, 5}; int n = arr.Length; int k = 3; Console.WriteLine(\"Length = \" + longestSubarrWthSumDivByK(arr, n, k)); }} // This code is contributed by Shrikant13, updated by Kshitij Dwivedi",
"e": 8653,
"s": 6693,
"text": null
},
{
"code": "<script> // Javascript implementation to find the longest subarray// with sum divisible by k // function to find the longest subarray// with sum divisible by kfunction longestSubarrWthSumDivByK(arr, n, k){ // unordered map 'um' implemented as // hash table var um = new Map(); // 'mod_arr[i]' stores (sum[0..i] % k) var mod_arr = Array(n), max_len = 0; var curr_sum = 0; // traverse arr[] and build up the // array 'mod_arr[]' for (var i = 0; i < n; i++) { curr_sum += arr[i]; // as the sum can be negative, taking modulo twice mod_arr[i] = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible // by k if (mod_arr[i] == 0) // update 'max_len' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (!um.has(mod_arr[i])) um.set(mod_arr[i] , i); else // if true, then update 'max_len' if (max_len < (i - um.get(mod_arr[i]))) max_len = i - um.get(mod_arr[i]); } // return the required length of longest subarray with // sum divisible by 'k' return max_len;} // Driver program to test abovevar arr = [2, 7, 6, 1, 4, 5];var n = arr.length;var k = 3; document.write( \"Length = \" + longestSubarrWthSumDivByK(arr, n, k)); // This code is contributed by rrrtnx, and updated by Kshitij Dwivedi</script>",
"e": 10231,
"s": 8653,
"text": null
},
{
"code": null,
"e": 10242,
"s": 10231,
"text": "Length = 4"
},
{
"code": null,
"e": 10414,
"s": 10242,
"text": "Time Complexity: O(n), as we traverse the input array only once.Auxiliary Space: O(n * k), O(n) for mod_arr[], and O(k) for storing the remainder values in the hash table."
},
{
"code": null,
"e": 10658,
"s": 10414,
"text": "Space Optimized approach: The space optimization for the above approach to O(n) Instead of keeping a separate array to store the modulus of all values, we compute it on the go and store remainders in the hash table.Below is the implementation:"
},
{
"code": null,
"e": 10662,
"s": 10658,
"text": "C++"
},
{
"code": null,
"e": 10667,
"s": 10662,
"text": "Java"
},
{
"code": null,
"e": 10675,
"s": 10667,
"text": "Python3"
},
{
"code": null,
"e": 10678,
"s": 10675,
"text": "C#"
},
{
"code": null,
"e": 10689,
"s": 10678,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h> using namespace std; // function to find the longest subarray// with sum divisible by kint longestSubarrWthSumDivByK(int arr[], int n, int k){ // unordered map 'um' implemented as // hash table unordered_map<int, int> um; int max_len = 0; int curr_sum = 0; for (int i = 0; i < n; i++) { curr_sum += arr[i]; int mod = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible // by k if (mod == 0) // update 'max_len' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.find(mod) == um.end()) um[mod] = i; else // if true, then update 'max_len' if (max_len < (i - um[mod])) max_len = i - um[mod]; } // return the required length of longest subarray with // sum divisible by 'k' return max_len;} // Driver codeint main(){ int arr[] = {2, 7, 6, 1, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << \"Length = \" << longestSubarrWthSumDivByK(arr, n, k); return 0;} // Code Updated by Kshitij Dwivedi",
"e": 11917,
"s": 10689,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { static int longestSubarrWthSumDivByK(int arr[], int n, int k) { Map<Integer, Integer> map = new HashMap<>(); int max_len = 0; int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; // to handle negavtive values as well int mod = ((sum % k) + k) % k; if (mod == 0) max_len = i + 1; if (!map.containsKey(mod)) map.put(mod, i); else { int sz = i - map.get(mod); max_len = Math.max(max_len, sz); } } return max_len; } public static void main(String[] args) { int arr[] = {2, 7, 6, 1, 4, 5}; int n = arr.length; int k = 3; System.out.println(\"Length = \" + longestSubarrWthSumDivByK(arr, n, k)); }} // Updated By Kshitij Dwivedi",
"e": 12920,
"s": 11917,
"text": null
},
{
"code": "# function to find the longest subarray# with sum divisible by kdef longestSubarrWthSumDivByK(arr, n, k): # unordered map 'um' implemented as # hash table um = {} max_len = 0 curr_sum = 0 for i in range(n): curr_sum += arr[i] mod = ((curr_sum % k) + k) % k # if true then sum(0..i) is divisible by k if mod == 0: # update 'max_len' max_len = i + 1 # if value 'mod_arr[i]' not present in 'um' # then store it in 'um' with index of its # first occurrence elif mod in um.keys(): if max_len < (i - um[mod]): max_len = i - um[mod] else: um[mod] = i # return the required length of longest subarray with # sum divisible by 'k' return max_len arr = [2, 7, 6, 1, 4, 5]n = len(arr)k = 3print(\"Length =\", longestSubarrWthSumDivByK(arr, n, k)) # This code is contributed by amreshkumar3, and updated by Kshitij Dwivedi",
"e": 13916,
"s": 12920,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // C# implementation to find the longest// subarray with sum divisible by kpublic class GFG { public static int longestSubarrWthSumDivByK(int[] arr, int n, int k) { // unordered map 'um' implemented as // hash table Dictionary<int, int> um = new Dictionary<int, int>(); int max_len = 0; int curr_sum = 0; for (int i = 0; i < n; i++) { curr_sum += arr[i]; int mod = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible // by k if (mod == 0) // update 'max_len' { max_len = i + 1; } // if value 'mod' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.ContainsKey(mod) == false) { um[mod] = i; } else { // if true, then update 'max' if (max_len < (i - um[mod])) { max_len = i - um[mod]; } } } // return the required length of longest subarray with // sum divisible by 'k' return max_len; } public static void Main(string[] args) { int[] arr = new int[] {2, 7, 6, 1, 4, 5}; int n = arr.Length; int k = 3; Console.WriteLine(\"Length = \" + longestSubarrWthSumDivByK(arr, n, k)); }} // This code is contributed by ishankhandelwals and updated by Kshitij Dwivedi",
"e": 15563,
"s": 13916,
"text": null
},
{
"code": "<script>// function to find the longest subarray// with sum divisible by kfunction longestSubarrWthSumDivByK(arr,n,k){ // map 'um' implemented as // hash table let um = new Map(); let max_len = 0; let curr_sum = 0; for (let i = 0; i < n; i++) { curr_sum += arr[i]; let mod = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible // by k if (mod == 0) // update 'max_len' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.has(mod) == false) um.set(mod,i); else // if true, then update 'max' if (max_len < (i - um.get(mod))) max_len = i - um.get(mod); } // required length of longest subarray with // sum divisible by 'k' return max;} // Driver program to test above let arr = [2, 7, 6, 1, 4, 5];let n = arr.length;let k = 3; document.write(\"Length = \" + longestSubarrWthSumDivByK(arr, n, k)); // This code is contributed by shinjanpatra, and updated by Kshitij Dwivedi.</script>",
"e": 16714,
"s": 15563,
"text": null
},
{
"code": null,
"e": 16725,
"s": 16714,
"text": "Length = 4"
},
{
"code": null,
"e": 16811,
"s": 16725,
"text": "Time Complexity: O(n), as we traverse the input array only once.Auxiliary Space: O(n)"
},
{
"code": null,
"e": 16820,
"s": 16811,
"text": "rex_wulf"
},
{
"code": null,
"e": 16832,
"s": 16820,
"text": "shrikanth13"
},
{
"code": null,
"e": 16849,
"s": 16832,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 16860,
"s": 16849,
"text": "throne1032"
},
{
"code": null,
"e": 16872,
"s": 16860,
"text": "1999shaswat"
},
{
"code": null,
"e": 16879,
"s": 16872,
"text": "rrrtnx"
},
{
"code": null,
"e": 16898,
"s": 16879,
"text": "surindertarika1234"
},
{
"code": null,
"e": 16910,
"s": 16898,
"text": "ayush123ngp"
},
{
"code": null,
"e": 16923,
"s": 16910,
"text": "amreshkumar3"
},
{
"code": null,
"e": 16936,
"s": 16923,
"text": "shinjanpatra"
},
{
"code": null,
"e": 16953,
"s": 16936,
"text": "ishankhandelwals"
},
{
"code": null,
"e": 16970,
"s": 16953,
"text": "kshitijdwivedi28"
},
{
"code": null,
"e": 16987,
"s": 16970,
"text": "harendrakumar123"
},
{
"code": null,
"e": 16996,
"s": 16987,
"text": "Snapdeal"
},
{
"code": null,
"e": 17005,
"s": 16996,
"text": "subarray"
},
{
"code": null,
"e": 17018,
"s": 17005,
"text": "subarray-sum"
},
{
"code": null,
"e": 17025,
"s": 17018,
"text": "Arrays"
},
{
"code": null,
"e": 17030,
"s": 17025,
"text": "Hash"
},
{
"code": null,
"e": 17039,
"s": 17030,
"text": "Snapdeal"
},
{
"code": null,
"e": 17046,
"s": 17039,
"text": "Arrays"
},
{
"code": null,
"e": 17051,
"s": 17046,
"text": "Hash"
}
] |
How to convert a matrix into a data frame with column names and row names as variables in R?
|
To convert a matrix into a data frame with column names and row names as variables, we first need to convert the matrix into a table and then read it as data frame using as.data.frame. For example, if we have a matrix M then it can be done by using the below command −
as.data.frame(as.table(M))
Live Demo
> M1<-matrix(1:36,nrow=6)
> M1
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 7 13 19 25 31
[2,] 2 8 14 20 26 32
[3,] 3 9 15 21 27 33
[4,] 4 10 16 22 28 34
[5,] 5 11 17 23 29 35
[6,] 6 12 18 24 30 36
> rownames(M1)<-1:6
> colnames(M1)<-LETTERS[1:6]
> M1
A B C D E F
1 1 7 13 19 25 31
2 2 8 14 20 26 32
3 3 9 15 21 27 33
4 4 10 16 22 28 34
5 5 11 17 23 29 35
6 6 12 18 24 30 36
> as.data.frame(as.table(M1))
Var1 Var2 Freq
1 1 A 1
2 2 A 2
3 3 A 3
4 4 A 4
5 5 A 5
6 6 A 6
7 1 B 7
8 2 B 8
9 3 B 9
10 4 B 10
11 5 B 11
12 6 B 12
13 1 C 13
14 2 C 14
15 3 C 15
16 4 C 16
17 5 C 17
18 6 C 18
19 1 D 19
20 2 D 20
21 3 D 21
22 4 D 22
23 5 D 23
24 6 D 24
25 1 E 25
26 2 E 26
27 3 E 27
28 4 E 28
29 5 E 29
30 6 E 30
31 1 F 31
32 2 F 32
33 3 F 33
34 4 F 34
35 5 F 35
36 6 F 36
Live Demo
> M2<-matrix(rnorm(25),nrow=5)
> M2
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1811644 0.1186978 -0.48697926 -1.1266623 0.3416455
[2,] 0.3232652 1.4545730 -1.81291997 1.8850307 -1.7641560
[3,] 0.4408050 -0.1402909 -0.08482793 0.5007377 0.2754002
[4,] 2.9937629 -0.1804370 -0.05752013 -2.7011690 -0.1628883
[5,] -0.9448278 -0.2615532 -0.05046240 -0.9994324 1.4588645
> rownames(M2)<-c("R1","R2","R3","R4","R5")
> colnames(M2)<-c("C1","C2","C3","C4","C5")
> M2
C1 C2 C3 C4 C5
R1 0.1811644 0.1186978 -0.48697926 -1.1266623 0.3416455
R2 0.3232652 1.4545730 -1.81291997 1.8850307 -1.7641560
R3 0.4408050 -0.1402909 -0.08482793 0.5007377 0.2754002
R4 2.9937629 -0.1804370 -0.05752013 -2.7011690 -0.1628883
R5 -0.9448278 -0.2615532 -0.05046240 -0.9994324 1.4588645
> as.data.frame(as.table(M2))
Var1 Var2 Freq
1 R1 C1 0.18116436
2 R2 C1 0.32326518
3 R3 C1 0.44080495
4 R4 C1 2.99376289
5 R5 C1 -0.94482784
6 R1 C2 0.11869776
7 R2 C2 1.45457299
8 R3 C2 -0.14029090
9 R4 C2 -0.18043699
10 R5 C2 -0.26155322
11 R1 C3 -0.48697926
12 R2 C3 -1.81291997
13 R3 C3 -0.08482793
14 R4 C3 -0.05752013
15 R5 C3 -0.05046240
16 R1 C4 -1.12666228
17 R2 C4 1.88503065
18 R3 C4 0.50073769
19 R4 C4 -2.70116904
20 R5 C4 -0.99943242
21 R1 C5 0.34164554
22 R2 C5 -1.76415604
23 R3 C5 0.27540019
24 R4 C5 -0.16288833
25 R5 C5 1.45886447
|
[
{
"code": null,
"e": 1456,
"s": 1187,
"text": "To convert a matrix into a data frame with column names and row names as variables, we first need to convert the matrix into a table and then read it as data frame using as.data.frame. For example, if we have a matrix M then it can be done by using the below command −"
},
{
"code": null,
"e": 1483,
"s": 1456,
"text": "as.data.frame(as.table(M))"
},
{
"code": null,
"e": 1493,
"s": 1483,
"text": "Live Demo"
},
{
"code": null,
"e": 1524,
"s": 1493,
"text": "> M1<-matrix(1:36,nrow=6)\n> M1"
},
{
"code": null,
"e": 1683,
"s": 1524,
"text": "[,1] [,2] [,3] [,4] [,5] [,6]\n[1,] 1 7 13 19 25 31\n[2,] 2 8 14 20 26 32\n[3,] 3 9 15 21 27 33\n[4,] 4 10 16 22 28 34\n[5,] 5 11 17 23 29 35\n[6,] 6 12 18 24 30 36"
},
{
"code": null,
"e": 1737,
"s": 1683,
"text": "> rownames(M1)<-1:6\n> colnames(M1)<-LETTERS[1:6]\n> M1"
},
{
"code": null,
"e": 1860,
"s": 1737,
"text": "A B C D E F\n1 1 7 13 19 25 31\n2 2 8 14 20 26 32\n3 3 9 15 21 27 33\n4 4 10 16 22 28 34\n5 5 11 17 23 29 35\n6 6 12 18 24 30 36"
},
{
"code": null,
"e": 1890,
"s": 1860,
"text": "> as.data.frame(as.table(M1))"
},
{
"code": null,
"e": 2247,
"s": 1890,
"text": "Var1 Var2 Freq\n1 1 A 1\n2 2 A 2\n3 3 A 3\n4 4 A 4\n5 5 A 5\n6 6 A 6\n7 1 B 7\n8 2 B 8\n9 3 B 9\n10 4 B 10\n11 5 B 11\n12 6 B 12\n13 1 C 13\n14 2 C 14\n15 3 C 15\n16 4 C 16\n17 5 C 17\n18 6 C 18\n19 1 D 19\n20 2 D 20\n21 3 D 21\n22 4 D 22\n23 5 D 23\n24 6 D 24\n25 1 E 25\n26 2 E 26\n27 3 E 27\n28 4 E 28\n29 5 E 29\n30 6 E 30\n31 1 F 31\n32 2 F 32\n33 3 F 33\n34 4 F 34\n35 5 F 35\n36 6 F 36"
},
{
"code": null,
"e": 2257,
"s": 2247,
"text": "Live Demo"
},
{
"code": null,
"e": 2293,
"s": 2257,
"text": "> M2<-matrix(rnorm(25),nrow=5)\n> M2"
},
{
"code": null,
"e": 2612,
"s": 2293,
"text": "[,1] [,2] [,3] [,4] [,5]\n[1,] 0.1811644 0.1186978 -0.48697926 -1.1266623 0.3416455\n[2,] 0.3232652 1.4545730 -1.81291997 1.8850307 -1.7641560\n[3,] 0.4408050 -0.1402909 -0.08482793 0.5007377 0.2754002\n[4,] 2.9937629 -0.1804370 -0.05752013 -2.7011690 -0.1628883\n[5,] -0.9448278 -0.2615532 -0.05046240 -0.9994324 1.4588645"
},
{
"code": null,
"e": 2705,
"s": 2612,
"text": "> rownames(M2)<-c(\"R1\",\"R2\",\"R3\",\"R4\",\"R5\")\n> colnames(M2)<-c(\"C1\",\"C2\",\"C3\",\"C4\",\"C5\")\n> M2"
},
{
"code": null,
"e": 3004,
"s": 2705,
"text": "C1 C2 C3 C4 C5\nR1 0.1811644 0.1186978 -0.48697926 -1.1266623 0.3416455\nR2 0.3232652 1.4545730 -1.81291997 1.8850307 -1.7641560\nR3 0.4408050 -0.1402909 -0.08482793 0.5007377 0.2754002\nR4 2.9937629 -0.1804370 -0.05752013 -2.7011690 -0.1628883\nR5 -0.9448278 -0.2615532 -0.05046240 -0.9994324 1.4588645"
},
{
"code": null,
"e": 3034,
"s": 3004,
"text": "> as.data.frame(as.table(M2))"
},
{
"code": null,
"e": 3554,
"s": 3034,
"text": "Var1 Var2 Freq\n1 R1 C1 0.18116436\n2 R2 C1 0.32326518\n3 R3 C1 0.44080495\n4 R4 C1 2.99376289\n5 R5 C1 -0.94482784\n6 R1 C2 0.11869776\n7 R2 C2 1.45457299\n8 R3 C2 -0.14029090\n9 R4 C2 -0.18043699\n10 R5 C2 -0.26155322\n11 R1 C3 -0.48697926\n12 R2 C3 -1.81291997\n13 R3 C3 -0.08482793\n14 R4 C3 -0.05752013\n15 R5 C3 -0.05046240\n16 R1 C4 -1.12666228\n17 R2 C4 1.88503065\n18 R3 C4 0.50073769\n19 R4 C4 -2.70116904\n20 R5 C4 -0.99943242\n21 R1 C5 0.34164554\n22 R2 C5 -1.76415604\n23 R3 C5 0.27540019\n24 R4 C5 -0.16288833\n25 R5 C5 1.45886447"
}
] |
Java program to delete certain text from a file
|
30 May, 2018
Prerequisite : PrintWriter , BufferedReader
Given two files input.txt and delete.txt. Our Task is to perform file extraction(Input-Delete) and save the output in file say output.txt
Example :
Naive Algorithm :
1. Create PrintWriter object for output.txt
2. Open BufferedReader for input.txt
3. Run a loop for each line of input.txt
3.1 flag = false
3.2 Open BufferedReader for delete.txt
3.3 Run a loop for each line of delete.txt
-> If line of delete.txt is equal to current line of input.txt
-> flag = true
-> break loop
4. Check flag, if false
-> write current line of input.txt to output.txt
5. Flush PrintWriter stream and close resources.
To successfully run the below program input.txt and delete.txt must exits in same folder OR provide full path for them.
// Java program to perform file// operation output = input-delete import java.io.*; public class FileOperation{ public static void main(String[] args) throws IOException { // PrintWriter object for output.txt PrintWriter pw = new PrintWriter("output.txt"); // BufferedReader object for input.txt BufferedReader br1 = new BufferedReader(new FileReader("input.txt")); String line1 = br1.readLine(); // loop for each line of input.txt while(line1 != null) { boolean flag = false; // BufferedReader object for delete.txt BufferedReader br2 = new BufferedReader(new FileReader("delete.txt")); String line2 = br2.readLine(); // loop for each line of delete.txt while(line2 != null) { if(line1.equals(line2)) { flag = true; break; } line2 = br2.readLine(); } // if flag = false // write line of input.txt to output.txt if(!flag) pw.println(line1); line1 = br1.readLine(); } pw.flush(); // closing resources br1.close(); pw.close(); System.out.println("File operation performed successfully"); }}
Output:
File operation performed successfully
Note : If output.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created.
A better solution is to use HashSet to store each line of delete.txt and then while looping through lines of input.txt ,check if it is in hashset. If not present, write that line into output.txt.
To successfully run the below program input.txt and delete.txt must exits in same folder OR provide full path for them.
// Efficient Java program to perform file// operation output = input-delete import java.io.*;import java.util.HashSet; public class FileOperation{ public static void main(String[] args) throws IOException { // PrintWriter object for output.txt PrintWriter pw = new PrintWriter("output.txt"); // BufferedReader object for delete.txt BufferedReader br2 = new BufferedReader(new FileReader("delete.txt")); String line2 = br2.readLine(); // hashset for storing lines of delete.txt HashSet<String> hs = new HashSet<String>(); // loop for each line of delete.txt while(line2 != null) { hs.add(line2); line2 = br2.readLine(); } // BufferedReader object for input.txt BufferedReader br1 = new BufferedReader(new FileReader("input.txt")); String line1 = br1.readLine(); // loop for each line of input.txt while(line1 != null) { // if line is not present in delete.txt // write it to output.txt if(!hs.contains(line1)) pw.println(line1); line1 = br1.readLine(); } pw.flush(); // closing resources br1.close(); br2.close(); pw.close(); System.out.println("File operation performed successfully"); }}
Output:
File operation performed successfully
Note : If output.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created.
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
java-file-handling
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Queue Interface In Java
Multidimensional Arrays in Java
HashMap in Java with Examples
Math pow() method in Java with Example
PriorityQueue in Java
Stack Class in Java
List Interface in Java with Examples
Initialize an ArrayList in Java
ArrayList in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 May, 2018"
},
{
"code": null,
"e": 98,
"s": 54,
"text": "Prerequisite : PrintWriter , BufferedReader"
},
{
"code": null,
"e": 236,
"s": 98,
"text": "Given two files input.txt and delete.txt. Our Task is to perform file extraction(Input-Delete) and save the output in file say output.txt"
},
{
"code": null,
"e": 246,
"s": 236,
"text": "Example :"
},
{
"code": null,
"e": 266,
"s": 248,
"text": "Naive Algorithm :"
},
{
"code": null,
"e": 750,
"s": 266,
"text": "1. Create PrintWriter object for output.txt\n2. Open BufferedReader for input.txt\n3. Run a loop for each line of input.txt\n 3.1 flag = false\n 3.2 Open BufferedReader for delete.txt\n 3.3 Run a loop for each line of delete.txt\n -> If line of delete.txt is equal to current line of input.txt \n -> flag = true\n -> break loop\n\n4. Check flag, if false\n -> write current line of input.txt to output.txt\n5. Flush PrintWriter stream and close resources.\n"
},
{
"code": null,
"e": 870,
"s": 750,
"text": "To successfully run the below program input.txt and delete.txt must exits in same folder OR provide full path for them."
},
{
"code": "// Java program to perform file// operation output = input-delete import java.io.*; public class FileOperation{ public static void main(String[] args) throws IOException { // PrintWriter object for output.txt PrintWriter pw = new PrintWriter(\"output.txt\"); // BufferedReader object for input.txt BufferedReader br1 = new BufferedReader(new FileReader(\"input.txt\")); String line1 = br1.readLine(); // loop for each line of input.txt while(line1 != null) { boolean flag = false; // BufferedReader object for delete.txt BufferedReader br2 = new BufferedReader(new FileReader(\"delete.txt\")); String line2 = br2.readLine(); // loop for each line of delete.txt while(line2 != null) { if(line1.equals(line2)) { flag = true; break; } line2 = br2.readLine(); } // if flag = false // write line of input.txt to output.txt if(!flag) pw.println(line1); line1 = br1.readLine(); } pw.flush(); // closing resources br1.close(); pw.close(); System.out.println(\"File operation performed successfully\"); }}",
"e": 2376,
"s": 870,
"text": null
},
{
"code": null,
"e": 2384,
"s": 2376,
"text": "Output:"
},
{
"code": null,
"e": 2423,
"s": 2384,
"text": "File operation performed successfully\n"
},
{
"code": null,
"e": 2565,
"s": 2423,
"text": "Note : If output.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created."
},
{
"code": null,
"e": 2761,
"s": 2565,
"text": "A better solution is to use HashSet to store each line of delete.txt and then while looping through lines of input.txt ,check if it is in hashset. If not present, write that line into output.txt."
},
{
"code": null,
"e": 2881,
"s": 2761,
"text": "To successfully run the below program input.txt and delete.txt must exits in same folder OR provide full path for them."
},
{
"code": "// Efficient Java program to perform file// operation output = input-delete import java.io.*;import java.util.HashSet; public class FileOperation{ public static void main(String[] args) throws IOException { // PrintWriter object for output.txt PrintWriter pw = new PrintWriter(\"output.txt\"); // BufferedReader object for delete.txt BufferedReader br2 = new BufferedReader(new FileReader(\"delete.txt\")); String line2 = br2.readLine(); // hashset for storing lines of delete.txt HashSet<String> hs = new HashSet<String>(); // loop for each line of delete.txt while(line2 != null) { hs.add(line2); line2 = br2.readLine(); } // BufferedReader object for input.txt BufferedReader br1 = new BufferedReader(new FileReader(\"input.txt\")); String line1 = br1.readLine(); // loop for each line of input.txt while(line1 != null) { // if line is not present in delete.txt // write it to output.txt if(!hs.contains(line1)) pw.println(line1); line1 = br1.readLine(); } pw.flush(); // closing resources br1.close(); br2.close(); pw.close(); System.out.println(\"File operation performed successfully\"); }}",
"e": 4357,
"s": 2881,
"text": null
},
{
"code": null,
"e": 4365,
"s": 4357,
"text": "Output:"
},
{
"code": null,
"e": 4404,
"s": 4365,
"text": "File operation performed successfully\n"
},
{
"code": null,
"e": 4546,
"s": 4404,
"text": "Note : If output.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created."
},
{
"code": null,
"e": 4848,
"s": 4546,
"text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4973,
"s": 4848,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4992,
"s": 4973,
"text": "java-file-handling"
},
{
"code": null,
"e": 5001,
"s": 4992,
"text": "Java-I/O"
},
{
"code": null,
"e": 5006,
"s": 5001,
"text": "Java"
},
{
"code": null,
"e": 5011,
"s": 5006,
"text": "Java"
},
{
"code": null,
"e": 5109,
"s": 5011,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5128,
"s": 5109,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 5152,
"s": 5128,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 5184,
"s": 5152,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5214,
"s": 5184,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 5253,
"s": 5214,
"text": "Math pow() method in Java with Example"
},
{
"code": null,
"e": 5275,
"s": 5253,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 5295,
"s": 5275,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 5332,
"s": 5295,
"text": "List Interface in Java with Examples"
},
{
"code": null,
"e": 5364,
"s": 5332,
"text": "Initialize an ArrayList in Java"
}
] |
Power Set
|
08 Jul, 2022
Power Set: Power set P(S) of a set S is the set of all subsets of S. For example S = {a, b, c} then P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}.If S has n elements in it then P(s) will have 2n elements
Example:
Set = [a,b,c]power_set_size = pow(2, 3) = 8Run for binary counter = 000 to 111
Value of Counter Subset 000 -> Empty set 001 -> a 010 -> b 011 -> ab 100 -> c 101 -> ac 110 -> bc 111 -> abc
Algorithm:
Input: Set[], set_size1. Get the size of power set powet_set_size = pow(2, set_size)2 Loop for counter from 0 to pow_set_size (a) Loop for i = 0 to set_size (i) If ith bit in counter is set Print ith element from set for this subset (b) Print separator for subsets i.e., newline
Method 1:For a given set[] S, the power set can be found by generating all binary numbers between 0 and 2n-1, where n is the size of the set. For example, for the set S {x, y, z}, generate all binary numbers from 0 to 23-1 and for each generated number, the corresponding set can be found by considering set bits in the number.
Below is the implementation of the above approach.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print all the power setvoid printPowerSet(char* set, int set_size){ // Set_size of power set of a set with set_size // n is (2^n-1) unsigned int pow_set_size = pow(2, set_size); int counter, j; // Run from counter 000..0 to 111..1 for (counter = 0; counter < pow_set_size; counter++) { for (j = 0; j < set_size; j++) { // Check if jth bit in the counter is set // If set then print jth element from set if (counter & (1 << j)) cout << set[j]; } cout << endl; }} /*Driver code*/int main(){ char set[] = { 'a', 'b', 'c' }; printPowerSet(set, 3); return 0;} // This code is contributed by SoM15242
#include <stdio.h>#include <math.h> void printPowerSet(char *set, int set_size){ /*set_size of power set of a set with set_size n is (2**n -1)*/ unsigned int pow_set_size = pow(2, set_size); int counter, j; /*Run from counter 000..0 to 111..1*/ for(counter = 0; counter < pow_set_size; counter++) { for(j = 0; j < set_size; j++) { /* Check if jth bit in the counter is set If set then print jth element from set */ if(counter & (1<<j)) printf("%c", set[j]); } printf("\n"); }} /*Driver program to test printPowerSet*/int main(){ char set[] = {'a','b','c'}; printPowerSet(set, 3); return 0;}
// Java program for power setimport java .io.*; public class GFG { static void printPowerSet(char []set, int set_size) { /*set_size of power set of a set with set_size n is (2**n -1)*/ long pow_set_size = (long)Math.pow(2, set_size); int counter, j; /*Run from counter 000..0 to 111..1*/ for(counter = 0; counter < pow_set_size; counter++) { for(j = 0; j < set_size; j++) { /* Check if jth bit in the counter is set If set then print jth element from set */ if((counter & (1 << j)) > 0) System.out.print(set[j]); } System.out.println(); } } // Driver program to test printPowerSet public static void main (String[] args) { char []set = {'a', 'b', 'c'}; printPowerSet(set, 3); }} // This code is contributed by anuj_67.
# python3 program for power set import math; def printPowerSet(set,set_size): # set_size of power set of a set # with set_size n is (2**n -1) pow_set_size = (int) (math.pow(2, set_size)); counter = 0; j = 0; # Run from counter 000..0 to 111..1 for counter in range(0, pow_set_size): for j in range(0, set_size): # Check if jth bit in the # counter is set If set then # print jth element from set if((counter & (1 << j)) > 0): print(set[j], end = ""); print(""); # Driver program to test printPowerSetset = ['a', 'b', 'c'];printPowerSet(set, 3); # This code is contributed by mits.
// C# program for power setusing System; class GFG { static void printPowerSet(char []set, int set_size) { /*set_size of power set of a set with set_size n is (2**n -1)*/ uint pow_set_size = (uint)Math.Pow(2, set_size); int counter, j; /*Run from counter 000..0 to 111..1*/ for(counter = 0; counter < pow_set_size; counter++) { for(j = 0; j < set_size; j++) { /* Check if jth bit in the counter is set If set then print jth element from set */ if((counter & (1 << j)) > 0) Console.Write(set[j]); } Console.WriteLine(); } } // Driver program to test printPowerSet public static void Main () { char []set = {'a', 'b', 'c'}; printPowerSet(set, 3); }} // This code is contributed by anuj_67.
<?php// PHP program for power set function printPowerSet($set, $set_size){ // set_size of power set of // a set with set_size // n is (2**n -1) $pow_set_size = pow(2, $set_size); $counter; $j; // Run from counter 000..0 to // 111..1 for($counter = 0; $counter < $pow_set_size; $counter++) { for($j = 0; $j < $set_size; $j++) { /* Check if jth bit in the counter is set If set then print jth element from set */ if($counter & (1 << $j)) echo $set[$j]; } echo "\n"; }} // Driver Code $set = array('a','b','c'); printPowerSet($set, 3); // This code is contributed by Vishal Tripathi?>
<script>// javascript program for power setpublic function printPowerSet(set, set_size) { /* * set_size of power set of a set with set_size n is (2**n -1) */ var pow_set_size = parseInt(Math.pow(2, set_size)); var counter, j; /* * Run from counter 000..0 to 111..1 */ for (counter = 0; counter < pow_set_size; counter++) { for (j = 0; j < set_size; j++) { /* * Check if jth bit in the counter is set If set then print jth element from set */ if ((counter & (1 << j)) > 0) document.write(set[j]); } document.write("<br/>"); } } // Driver program to test printPowerSet let set = [ 'a', 'b', 'c' ]; printPowerSet(set, 3); // This code is contributed by shikhasingrajput</script>
a
b
ab
c
ac
bc
abc
Time Complexity: O(n2n)Auxiliary Space: O(1)
Method 2: (sorted by cardinality)
In auxiliary array of bool set all elements to 0. That represent an empty set. Set first element of auxiliary array to 1 and generate all permutations to produce all subsets with one element. Then set the second element to 1 which will produce all subsets with two elements, repeat until all elements are included.
Below is the implementation of the above approach.
C++
Python3
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print all the power setvoid printPowerSet(char set[], int n){ bool *contain = new bool[n]{0}; // Empty subset cout << "" << endl; for(int i = 0; i < n; i++) { contain[i] = 1; // All permutation do { for(int j = 0; j < n; j++) if(contain[j]) cout << set[j]; cout << endl; } while(prev_permutation(contain, contain + n)); }} /*Driver code*/int main(){ char set[] = {'a','b','c'}; printPowerSet(set, 3); return 0;} // This code is contributed by zlatkodamijanic
# Python3 program for the above approach # A function which gives previous# permutation of the array# and returns true if a permutation# exists.def prev_permutation(str): # Find index of the last # element of the string n = len(str) - 1 # Find largest index i such # that str[i - 1] > str[i] i = n while (i > 0 and str[i - 1] <= str[i]): i -= 1 # If string is sorted in # ascending order we're # at the last permutation if (i <= 0): return False # Note - str[i..n] is sorted # in ascending order Find # rightmost element's index # that is less than str[i - 1] j = i - 1 while (j + 1 <= n and str[j + 1] < str[i - 1]): j += 1 # Swap character at i-1 with j temper = str[i - 1] str[i - 1] = str[j] str[j] = temper # Reverse the substring [i..n] size = n-i+1 for idx in range(int(size / 2)): temp = str[idx + i] str[idx + i] = str[n - idx] str[n - idx] = temp return True # Function to print all the power setdef printPowerSet(set, n): contain = [0 for _ in range(n)] # Empty subset print() for i in range(n): contain[i] = 1 # To avoid changing original 'contain' # array creating a copy of it i.e. # "Contain" Contain = contain.copy() # All permutation while True: for j in range(n): if (Contain[j]): print(set[j], end="") print() if not prev_permutation(Contain): break # Driver codeset = ['a', 'b', 'c']printPowerSet(set, 3) # This code is contributed by phasing17
// JavaScript program for the above approach // A function which gives previous// permutation of the array// and returns true if a permutation// exists.function prev_permutation(str){ // Find index of the last // element of the string let n = str.length - 1; // Find largest index i such // that str[i - 1] > str[i] let i = n; while (i > 0 && str[i - 1] <= str[i]){ i--; } // If string is sorted in // ascending order we're // at the last permutation if (i <= 0){ return false; } // Note - str[i..n] is sorted // in ascending order Find // rightmost element's index // that is less than str[i - 1] let j = i - 1; while (j + 1 <= n && str[j + 1] < str[i - 1]){ j++; } // Swap character at i-1 with j const temper = str[i - 1]; str[i - 1] = str[j]; str[j] = temper; // Reverse the substring [i..n] let size = n-i+1; for (let idx = 0; idx < Math.floor(size / 2); idx++) { let temp = str[idx + i]; str[idx + i] = str[n - idx]; str[n - idx] = temp; } return true;} // Function to print all the power setfunction printPowerSet(set, n){ let contain = new Array(n).fill(0); // Empty subset document.write("<br>"); for(let i = 0; i < n; i++){ contain[i] = 1; // To avoid changing original 'contain' // array creating a copy of it i.e. // "Contain" let Contain = new Array(n); for(let indx = 0; indx < n; indx++){ Contain[indx] = contain[indx]; } // All permutation do{ for(let j = 0; j < n; j++){ if(Contain[j]){ document.write(set[j]); } } document.write("<br>"); } while(prev_permutation(Contain)); }} /*Driver code*/const set = ['a','b','c'];printPowerSet(set, 3); // This code is contributed by Gautam goel (gautamgoel962)
a
b
c
ab
ac
bc
abc
Time Complexity: O(n2n)Auxiliary Space: O(n)
Method 3: This method is specific to the python programming language. We can iterate a loop over 0 to the length of the set to obtain and generate all possible combinations of that string with the iterable length. The program below will give the implementation of the above idea.
Below is the implementation of the above approach.
Python3
#Python program to find powersetfrom itertools import combinationsdef print_powerset(string): for i in range(0,len(string)+1): for element in combinations(string,i): print(''.join(element))string=['a','b','c']print_powerset(string)
a
b
c
ab
ac
bc
abc
Method 4:
We can use backtrack here, we have two choices first consider that element then don’t consider that element.
Below is the implementation of the above approach.
C++
Java
Python3
C#
#include <bits/stdc++.h>using namespace std; void findPowerSet(char* s, vector<char> &res, int n){ if (n == 0) { for (auto i: res) cout << i; cout << "\n"; return; } res.push_back(s[n - 1]); findPowerSet(s, res, n - 1); res.pop_back(); findPowerSet(s, res, n - 1); } void printPowerSet(char* s, int n){ vector<char> ans; findPowerSet(s, ans, n);} int main(){ char set[] = { 'a', 'b', 'c' }; printPowerSet(set, 3); return 0;}
import java.util.*; class Main{ public static void findPowerSet(char []s, Deque<Character> res,int n){ if (n == 0){ for (Character element : res) System.out.print(element); System.out.println(); return; } res.addLast(s[n - 1]); findPowerSet(s, res, n - 1); res.removeLast(); findPowerSet(s, res, n - 1); } public static void main(String[] args) { char []set = {'a', 'b', 'c'}; Deque<Character> res = new ArrayDeque<>(); findPowerSet(set, res, 3); }}
# Python3 program to implement the approach # Function to build the power setsdef findPowerSet(s, res, n): if (n == 0): for i in res: print(i, end="") print() return # append the subset to result res.append(s[n - 1]) findPowerSet(s, res, n - 1) res.pop() findPowerSet(s, res, n - 1) # Function to print the power setdef printPowerSet(s, n): ans = [] findPowerSet(s, ans, n) # Driver codeset = ['a', 'b', 'c']printPowerSet(set, 3) # This code is contributed by phasing17
// C# code to implement the approach using System;using System.Collections.Generic; class GFG{ // function to build the power set public static void findPowerSet(char[] s, List<char> res, int n) { // if the end is reached // display all elements of res if (n == 0) { foreach(var element in res) Console.Write(element); Console.WriteLine(); return; } // append the subset to res res.Add(s[n - 1]); findPowerSet(s, res, n - 1); res.RemoveAt(res.Count - 1); findPowerSet(s, res, n - 1); } // Driver code public static void Main(string[] args) { char[] set = { 'a', 'b', 'c' }; List<char> res = new List<char>(); // Function call findPowerSet(set, res, 3); }} // This code is contributed by phasing17
cba
cb
ca
c
ba
b
a
Time Complexity: O(n2^n)
Space Complexity: O(n)
Recursive program to generate power setRefer Power Set in Java for implementation in Java and more methods to print power set.References: http://en.wikipedia.org/wiki/Power_set
vt_m
Mithun Kumar
Aaditya Kulkarni
SoumikMondal
avsadityavardhan
shikhasingrajput
khushboogoyal499
subhammahato348
zlatkodamijanic
gautamgoel962
isha307
phasing17
Snapdeal
Mathematical
Snapdeal
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 273,
"s": 54,
"text": "Power Set: Power set P(S) of a set S is the set of all subsets of S. For example S = {a, b, c} then P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}.If S has n elements in it then P(s) will have 2n elements"
},
{
"code": null,
"e": 283,
"s": 273,
"text": "Example: "
},
{
"code": null,
"e": 363,
"s": 283,
"text": "Set = [a,b,c]power_set_size = pow(2, 3) = 8Run for binary counter = 000 to 111"
},
{
"code": null,
"e": 651,
"s": 363,
"text": "Value of Counter Subset 000 -> Empty set 001 -> a 010 -> b 011 -> ab 100 -> c 101 -> ac 110 -> bc 111 -> abc"
},
{
"code": null,
"e": 663,
"s": 651,
"text": "Algorithm: "
},
{
"code": null,
"e": 976,
"s": 663,
"text": "Input: Set[], set_size1. Get the size of power set powet_set_size = pow(2, set_size)2 Loop for counter from 0 to pow_set_size (a) Loop for i = 0 to set_size (i) If ith bit in counter is set Print ith element from set for this subset (b) Print separator for subsets i.e., newline"
},
{
"code": null,
"e": 1304,
"s": 976,
"text": "Method 1:For a given set[] S, the power set can be found by generating all binary numbers between 0 and 2n-1, where n is the size of the set. For example, for the set S {x, y, z}, generate all binary numbers from 0 to 23-1 and for each generated number, the corresponding set can be found by considering set bits in the number."
},
{
"code": null,
"e": 1355,
"s": 1304,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 1359,
"s": 1355,
"text": "C++"
},
{
"code": null,
"e": 1361,
"s": 1359,
"text": "C"
},
{
"code": null,
"e": 1366,
"s": 1361,
"text": "Java"
},
{
"code": null,
"e": 1374,
"s": 1366,
"text": "Python3"
},
{
"code": null,
"e": 1377,
"s": 1374,
"text": "C#"
},
{
"code": null,
"e": 1381,
"s": 1377,
"text": "PHP"
},
{
"code": null,
"e": 1392,
"s": 1381,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print all the power setvoid printPowerSet(char* set, int set_size){ // Set_size of power set of a set with set_size // n is (2^n-1) unsigned int pow_set_size = pow(2, set_size); int counter, j; // Run from counter 000..0 to 111..1 for (counter = 0; counter < pow_set_size; counter++) { for (j = 0; j < set_size; j++) { // Check if jth bit in the counter is set // If set then print jth element from set if (counter & (1 << j)) cout << set[j]; } cout << endl; }} /*Driver code*/int main(){ char set[] = { 'a', 'b', 'c' }; printPowerSet(set, 3); return 0;} // This code is contributed by SoM15242",
"e": 2184,
"s": 1392,
"text": null
},
{
"code": "#include <stdio.h>#include <math.h> void printPowerSet(char *set, int set_size){ /*set_size of power set of a set with set_size n is (2**n -1)*/ unsigned int pow_set_size = pow(2, set_size); int counter, j; /*Run from counter 000..0 to 111..1*/ for(counter = 0; counter < pow_set_size; counter++) { for(j = 0; j < set_size; j++) { /* Check if jth bit in the counter is set If set then print jth element from set */ if(counter & (1<<j)) printf(\"%c\", set[j]); } printf(\"\\n\"); }} /*Driver program to test printPowerSet*/int main(){ char set[] = {'a','b','c'}; printPowerSet(set, 3); return 0;}",
"e": 2875,
"s": 2184,
"text": null
},
{
"code": "// Java program for power setimport java .io.*; public class GFG { static void printPowerSet(char []set, int set_size) { /*set_size of power set of a set with set_size n is (2**n -1)*/ long pow_set_size = (long)Math.pow(2, set_size); int counter, j; /*Run from counter 000..0 to 111..1*/ for(counter = 0; counter < pow_set_size; counter++) { for(j = 0; j < set_size; j++) { /* Check if jth bit in the counter is set If set then print jth element from set */ if((counter & (1 << j)) > 0) System.out.print(set[j]); } System.out.println(); } } // Driver program to test printPowerSet public static void main (String[] args) { char []set = {'a', 'b', 'c'}; printPowerSet(set, 3); }} // This code is contributed by anuj_67.",
"e": 3905,
"s": 2875,
"text": null
},
{
"code": "# python3 program for power set import math; def printPowerSet(set,set_size): # set_size of power set of a set # with set_size n is (2**n -1) pow_set_size = (int) (math.pow(2, set_size)); counter = 0; j = 0; # Run from counter 000..0 to 111..1 for counter in range(0, pow_set_size): for j in range(0, set_size): # Check if jth bit in the # counter is set If set then # print jth element from set if((counter & (1 << j)) > 0): print(set[j], end = \"\"); print(\"\"); # Driver program to test printPowerSetset = ['a', 'b', 'c'];printPowerSet(set, 3); # This code is contributed by mits.",
"e": 4603,
"s": 3905,
"text": null
},
{
"code": "// C# program for power setusing System; class GFG { static void printPowerSet(char []set, int set_size) { /*set_size of power set of a set with set_size n is (2**n -1)*/ uint pow_set_size = (uint)Math.Pow(2, set_size); int counter, j; /*Run from counter 000..0 to 111..1*/ for(counter = 0; counter < pow_set_size; counter++) { for(j = 0; j < set_size; j++) { /* Check if jth bit in the counter is set If set then print jth element from set */ if((counter & (1 << j)) > 0) Console.Write(set[j]); } Console.WriteLine(); } } // Driver program to test printPowerSet public static void Main () { char []set = {'a', 'b', 'c'}; printPowerSet(set, 3); }} // This code is contributed by anuj_67.",
"e": 5598,
"s": 4603,
"text": null
},
{
"code": "<?php// PHP program for power set function printPowerSet($set, $set_size){ // set_size of power set of // a set with set_size // n is (2**n -1) $pow_set_size = pow(2, $set_size); $counter; $j; // Run from counter 000..0 to // 111..1 for($counter = 0; $counter < $pow_set_size; $counter++) { for($j = 0; $j < $set_size; $j++) { /* Check if jth bit in the counter is set If set then print jth element from set */ if($counter & (1 << $j)) echo $set[$j]; } echo \"\\n\"; }} // Driver Code $set = array('a','b','c'); printPowerSet($set, 3); // This code is contributed by Vishal Tripathi?>",
"e": 6382,
"s": 5598,
"text": null
},
{
"code": "<script>// javascript program for power setpublic function printPowerSet(set, set_size) { /* * set_size of power set of a set with set_size n is (2**n -1) */ var pow_set_size = parseInt(Math.pow(2, set_size)); var counter, j; /* * Run from counter 000..0 to 111..1 */ for (counter = 0; counter < pow_set_size; counter++) { for (j = 0; j < set_size; j++) { /* * Check if jth bit in the counter is set If set then print jth element from set */ if ((counter & (1 << j)) > 0) document.write(set[j]); } document.write(\"<br/>\"); } } // Driver program to test printPowerSet let set = [ 'a', 'b', 'c' ]; printPowerSet(set, 3); // This code is contributed by shikhasingrajput</script>",
"e": 7307,
"s": 6382,
"text": null
},
{
"code": null,
"e": 7326,
"s": 7307,
"text": "a\nb\nab\nc\nac\nbc\nabc"
},
{
"code": null,
"e": 7371,
"s": 7326,
"text": "Time Complexity: O(n2n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7405,
"s": 7371,
"text": "Method 2: (sorted by cardinality)"
},
{
"code": null,
"e": 7720,
"s": 7405,
"text": "In auxiliary array of bool set all elements to 0. That represent an empty set. Set first element of auxiliary array to 1 and generate all permutations to produce all subsets with one element. Then set the second element to 1 which will produce all subsets with two elements, repeat until all elements are included."
},
{
"code": null,
"e": 7771,
"s": 7720,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 7775,
"s": 7771,
"text": "C++"
},
{
"code": null,
"e": 7783,
"s": 7775,
"text": "Python3"
},
{
"code": null,
"e": 7794,
"s": 7783,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print all the power setvoid printPowerSet(char set[], int n){ bool *contain = new bool[n]{0}; // Empty subset cout << \"\" << endl; for(int i = 0; i < n; i++) { contain[i] = 1; // All permutation do { for(int j = 0; j < n; j++) if(contain[j]) cout << set[j]; cout << endl; } while(prev_permutation(contain, contain + n)); }} /*Driver code*/int main(){ char set[] = {'a','b','c'}; printPowerSet(set, 3); return 0;} // This code is contributed by zlatkodamijanic",
"e": 8473,
"s": 7794,
"text": null
},
{
"code": "# Python3 program for the above approach # A function which gives previous# permutation of the array# and returns true if a permutation# exists.def prev_permutation(str): # Find index of the last # element of the string n = len(str) - 1 # Find largest index i such # that str[i - 1] > str[i] i = n while (i > 0 and str[i - 1] <= str[i]): i -= 1 # If string is sorted in # ascending order we're # at the last permutation if (i <= 0): return False # Note - str[i..n] is sorted # in ascending order Find # rightmost element's index # that is less than str[i - 1] j = i - 1 while (j + 1 <= n and str[j + 1] < str[i - 1]): j += 1 # Swap character at i-1 with j temper = str[i - 1] str[i - 1] = str[j] str[j] = temper # Reverse the substring [i..n] size = n-i+1 for idx in range(int(size / 2)): temp = str[idx + i] str[idx + i] = str[n - idx] str[n - idx] = temp return True # Function to print all the power setdef printPowerSet(set, n): contain = [0 for _ in range(n)] # Empty subset print() for i in range(n): contain[i] = 1 # To avoid changing original 'contain' # array creating a copy of it i.e. # \"Contain\" Contain = contain.copy() # All permutation while True: for j in range(n): if (Contain[j]): print(set[j], end=\"\") print() if not prev_permutation(Contain): break # Driver codeset = ['a', 'b', 'c']printPowerSet(set, 3) # This code is contributed by phasing17",
"e": 10110,
"s": 8473,
"text": null
},
{
"code": "// JavaScript program for the above approach // A function which gives previous// permutation of the array// and returns true if a permutation// exists.function prev_permutation(str){ // Find index of the last // element of the string let n = str.length - 1; // Find largest index i such // that str[i - 1] > str[i] let i = n; while (i > 0 && str[i - 1] <= str[i]){ i--; } // If string is sorted in // ascending order we're // at the last permutation if (i <= 0){ return false; } // Note - str[i..n] is sorted // in ascending order Find // rightmost element's index // that is less than str[i - 1] let j = i - 1; while (j + 1 <= n && str[j + 1] < str[i - 1]){ j++; } // Swap character at i-1 with j const temper = str[i - 1]; str[i - 1] = str[j]; str[j] = temper; // Reverse the substring [i..n] let size = n-i+1; for (let idx = 0; idx < Math.floor(size / 2); idx++) { let temp = str[idx + i]; str[idx + i] = str[n - idx]; str[n - idx] = temp; } return true;} // Function to print all the power setfunction printPowerSet(set, n){ let contain = new Array(n).fill(0); // Empty subset document.write(\"<br>\"); for(let i = 0; i < n; i++){ contain[i] = 1; // To avoid changing original 'contain' // array creating a copy of it i.e. // \"Contain\" let Contain = new Array(n); for(let indx = 0; indx < n; indx++){ Contain[indx] = contain[indx]; } // All permutation do{ for(let j = 0; j < n; j++){ if(Contain[j]){ document.write(set[j]); } } document.write(\"<br>\"); } while(prev_permutation(Contain)); }} /*Driver code*/const set = ['a','b','c'];printPowerSet(set, 3); // This code is contributed by Gautam goel (gautamgoel962)",
"e": 12109,
"s": 10110,
"text": null
},
{
"code": null,
"e": 12128,
"s": 12109,
"text": "a\nb\nc\nab\nac\nbc\nabc"
},
{
"code": null,
"e": 12173,
"s": 12128,
"text": "Time Complexity: O(n2n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 12455,
"s": 12173,
"text": "Method 3: This method is specific to the python programming language. We can iterate a loop over 0 to the length of the set to obtain and generate all possible combinations of that string with the iterable length. The program below will give the implementation of the above idea. "
},
{
"code": null,
"e": 12506,
"s": 12455,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 12514,
"s": 12506,
"text": "Python3"
},
{
"code": "#Python program to find powersetfrom itertools import combinationsdef print_powerset(string): for i in range(0,len(string)+1): for element in combinations(string,i): print(''.join(element))string=['a','b','c']print_powerset(string)",
"e": 12767,
"s": 12514,
"text": null
},
{
"code": null,
"e": 12786,
"s": 12767,
"text": "a\nb\nc\nab\nac\nbc\nabc"
},
{
"code": null,
"e": 12796,
"s": 12786,
"text": "Method 4:"
},
{
"code": null,
"e": 12906,
"s": 12796,
"text": "We can use backtrack here, we have two choices first consider that element then don’t consider that element. "
},
{
"code": null,
"e": 12957,
"s": 12906,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 12961,
"s": 12957,
"text": "C++"
},
{
"code": null,
"e": 12966,
"s": 12961,
"text": "Java"
},
{
"code": null,
"e": 12974,
"s": 12966,
"text": "Python3"
},
{
"code": null,
"e": 12977,
"s": 12974,
"text": "C#"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void findPowerSet(char* s, vector<char> &res, int n){ if (n == 0) { for (auto i: res) cout << i; cout << \"\\n\"; return; } res.push_back(s[n - 1]); findPowerSet(s, res, n - 1); res.pop_back(); findPowerSet(s, res, n - 1); } void printPowerSet(char* s, int n){ vector<char> ans; findPowerSet(s, ans, n);} int main(){ char set[] = { 'a', 'b', 'c' }; printPowerSet(set, 3); return 0;}",
"e": 13549,
"s": 12977,
"text": null
},
{
"code": "import java.util.*; class Main{ public static void findPowerSet(char []s, Deque<Character> res,int n){ if (n == 0){ for (Character element : res) System.out.print(element); System.out.println(); return; } res.addLast(s[n - 1]); findPowerSet(s, res, n - 1); res.removeLast(); findPowerSet(s, res, n - 1); } public static void main(String[] args) { char []set = {'a', 'b', 'c'}; Deque<Character> res = new ArrayDeque<>(); findPowerSet(set, res, 3); }}",
"e": 14140,
"s": 13549,
"text": null
},
{
"code": "# Python3 program to implement the approach # Function to build the power setsdef findPowerSet(s, res, n): if (n == 0): for i in res: print(i, end=\"\") print() return # append the subset to result res.append(s[n - 1]) findPowerSet(s, res, n - 1) res.pop() findPowerSet(s, res, n - 1) # Function to print the power setdef printPowerSet(s, n): ans = [] findPowerSet(s, ans, n) # Driver codeset = ['a', 'b', 'c']printPowerSet(set, 3) # This code is contributed by phasing17",
"e": 14667,
"s": 14140,
"text": null
},
{
"code": "// C# code to implement the approach using System;using System.Collections.Generic; class GFG{ // function to build the power set public static void findPowerSet(char[] s, List<char> res, int n) { // if the end is reached // display all elements of res if (n == 0) { foreach(var element in res) Console.Write(element); Console.WriteLine(); return; } // append the subset to res res.Add(s[n - 1]); findPowerSet(s, res, n - 1); res.RemoveAt(res.Count - 1); findPowerSet(s, res, n - 1); } // Driver code public static void Main(string[] args) { char[] set = { 'a', 'b', 'c' }; List<char> res = new List<char>(); // Function call findPowerSet(set, res, 3); }} // This code is contributed by phasing17",
"e": 15566,
"s": 14667,
"text": null
},
{
"code": null,
"e": 15585,
"s": 15566,
"text": "cba\ncb\nca\nc\nba\nb\na"
},
{
"code": null,
"e": 15610,
"s": 15585,
"text": "Time Complexity: O(n2^n)"
},
{
"code": null,
"e": 15633,
"s": 15610,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 15811,
"s": 15633,
"text": "Recursive program to generate power setRefer Power Set in Java for implementation in Java and more methods to print power set.References: http://en.wikipedia.org/wiki/Power_set "
},
{
"code": null,
"e": 15818,
"s": 15813,
"text": "vt_m"
},
{
"code": null,
"e": 15831,
"s": 15818,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 15848,
"s": 15831,
"text": "Aaditya Kulkarni"
},
{
"code": null,
"e": 15861,
"s": 15848,
"text": "SoumikMondal"
},
{
"code": null,
"e": 15878,
"s": 15861,
"text": "avsadityavardhan"
},
{
"code": null,
"e": 15895,
"s": 15878,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 15912,
"s": 15895,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 15928,
"s": 15912,
"text": "subhammahato348"
},
{
"code": null,
"e": 15944,
"s": 15928,
"text": "zlatkodamijanic"
},
{
"code": null,
"e": 15958,
"s": 15944,
"text": "gautamgoel962"
},
{
"code": null,
"e": 15966,
"s": 15958,
"text": "isha307"
},
{
"code": null,
"e": 15976,
"s": 15966,
"text": "phasing17"
},
{
"code": null,
"e": 15985,
"s": 15976,
"text": "Snapdeal"
},
{
"code": null,
"e": 15998,
"s": 15985,
"text": "Mathematical"
},
{
"code": null,
"e": 16007,
"s": 15998,
"text": "Snapdeal"
},
{
"code": null,
"e": 16020,
"s": 16007,
"text": "Mathematical"
},
{
"code": null,
"e": 16118,
"s": 16020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16148,
"s": 16118,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 16191,
"s": 16148,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 16251,
"s": 16191,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 16266,
"s": 16251,
"text": "C++ Data Types"
},
{
"code": null,
"e": 16290,
"s": 16266,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 16309,
"s": 16290,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 16330,
"s": 16309,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 16344,
"s": 16330,
"text": "Prime Numbers"
},
{
"code": null,
"e": 16386,
"s": 16344,
"text": "Program to find GCD or HCF of two numbers"
}
] |
Computable and non-computable problems in TOC
|
20 Jun, 2022
Computable Problems – You are familiar with many problems (or functions) that are computable (or decidable), meaning there exists some algorithm that computes an answer (or output) to any instance of the problem (or for any input to the function) in a finite number of simple steps. A simple example is the integer increment operation:
f(x) = x + 1
It should be intuitive that given any integer x, we can compute x + 1 in a finite number of steps. Since x is finite, it may be represented by a finite string of digits. Using the addition method (or algorithm) we all learned in school, we can clearly compute another string of digits representing the integer equivalent to x + 1. Yet there are also problems and functions that are non-computable (or undecidable or uncomputable), meaning that there exists no algorithm that can compute an answer or output for all inputs in a finite number of simple steps. (Undecidable simply means non-computable in the context of a decision problem, whose answer (or output) is either “true” or “false”).
Non-Computable Problems – A non-computable is a problem for which there is no algorithm that can be used to solve it. The most famous example of a non-computability (or undecidability) is the Halting Problem. Given a description of a Turing machine and its initial input, determine whether the program, when executed on this input, ever halts (completes). The alternative is that it runs forever without halting. The halting problem is about seeing if a machine will ever come to a halt when a certain input is given to it or if it will finish running. This input itself can be something that keeps calling itself forever, which means that it will cause the program to run forever. Another example of an uncomputable problem is: determining whether a computer program loops forever on some input. You can replace “computer program” with “Turing machine or algorithm” if you know about the Turing machine.
Proving Computability or Non-Computability – We can show that a problem is computable by describing a procedure and proving that the procedure always terminates and always produces the correct answer. It is enough to provide a convincing argument that such a procedure exists. Finding the actual procedure is not necessary (but often helps to make the argument more convincing). To show that a problem is not computable, we need to show that no algorithm exists that solves the problem. Since there are an infinite number of possible procedures, we cannot just list all possible procedures and show why each one does not solve the problem. Instead, we need to construct an argument showing that if there were such an algorithm, it would lead to a contradiction. The core of our argument is based on knowing the Halting Problem is non-computable. If a solution to some new problem P could be used to solve the Halting Problem, then we know that P is also non-computable. That is, no algorithm exists that can solve P since if such an algorithm exists, it could be used to also solve the Halting Problem, which we already know is impossible. The proof technique where we show that a solution for some problem P can be used to solve a different problem Q is known as a reduction.A problem Q is reducible to a problem P if a solution to P could be used to solve Q. This means that problem Q is no harder than problem P since a solution to problem Q leads to a solution to problem P.
Some Examples Of Computable Problems – These are four simple examples of the computable problem:
Computing the greatest common divisor of a pair of integers.Computing the least common multiple of a pair of integers.Finding the shortest path between a pair of nodes in a finite graph.Determining whether a propositional formula is a tautology.
Computing the greatest common divisor of a pair of integers.
Computing the least common multiple of a pair of integers.
Finding the shortest path between a pair of nodes in a finite graph.
Determining whether a propositional formula is a tautology.
Some Examples Of Computable Problems – State Entry Problem. Consider the problem of determining if a string ‘w’ is given to some Turing machine ‘M’ will it enter some state ‘q'(where q belongs to a set of all states in Turing machine M and string w is not equal to an empty string). Is it computable or non-computable?
Explanation – We show the State Entry Problem is non-computable by showing that it is as hard as The Halting Problem, which we already know is non-computable. State Entry Problem is asking us on given string w if we start from initial state of Turing machine will it reach to a state q. Now this state entry problem can be converted to a halting problem. Halting problem is whether our Turing machine ever halts, and the state entry problem is asking the same thing whether this Turing machine halts at some state q if we give string w as input to the Turing machine M. So the state entry problem is non-computable as we converted it to the halting problem which we already know is non-computable problem. So in this way, we can prove non-computability.
chhabradhanvi
sweetyty
sahithya3chow
simmytarika5
Picked
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Difference between DFA and NFA
Boyer-Moore Majority Voting Algorithm
Variation of Turing Machine
Design 101 sequence detector (Mealy machine)
Post Correspondence Problem
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 364,
"s": 28,
"text": "Computable Problems – You are familiar with many problems (or functions) that are computable (or decidable), meaning there exists some algorithm that computes an answer (or output) to any instance of the problem (or for any input to the function) in a finite number of simple steps. A simple example is the integer increment operation:"
},
{
"code": null,
"e": 378,
"s": 364,
"text": "f(x) = x + 1 "
},
{
"code": null,
"e": 1071,
"s": 378,
"text": "It should be intuitive that given any integer x, we can compute x + 1 in a finite number of steps. Since x is finite, it may be represented by a finite string of digits. Using the addition method (or algorithm) we all learned in school, we can clearly compute another string of digits representing the integer equivalent to x + 1. Yet there are also problems and functions that are non-computable (or undecidable or uncomputable), meaning that there exists no algorithm that can compute an answer or output for all inputs in a finite number of simple steps. (Undecidable simply means non-computable in the context of a decision problem, whose answer (or output) is either “true” or “false”). "
},
{
"code": null,
"e": 1977,
"s": 1071,
"text": "Non-Computable Problems – A non-computable is a problem for which there is no algorithm that can be used to solve it. The most famous example of a non-computability (or undecidability) is the Halting Problem. Given a description of a Turing machine and its initial input, determine whether the program, when executed on this input, ever halts (completes). The alternative is that it runs forever without halting. The halting problem is about seeing if a machine will ever come to a halt when a certain input is given to it or if it will finish running. This input itself can be something that keeps calling itself forever, which means that it will cause the program to run forever. Another example of an uncomputable problem is: determining whether a computer program loops forever on some input. You can replace “computer program” with “Turing machine or algorithm” if you know about the Turing machine. "
},
{
"code": null,
"e": 3457,
"s": 1977,
"text": "Proving Computability or Non-Computability – We can show that a problem is computable by describing a procedure and proving that the procedure always terminates and always produces the correct answer. It is enough to provide a convincing argument that such a procedure exists. Finding the actual procedure is not necessary (but often helps to make the argument more convincing). To show that a problem is not computable, we need to show that no algorithm exists that solves the problem. Since there are an infinite number of possible procedures, we cannot just list all possible procedures and show why each one does not solve the problem. Instead, we need to construct an argument showing that if there were such an algorithm, it would lead to a contradiction. The core of our argument is based on knowing the Halting Problem is non-computable. If a solution to some new problem P could be used to solve the Halting Problem, then we know that P is also non-computable. That is, no algorithm exists that can solve P since if such an algorithm exists, it could be used to also solve the Halting Problem, which we already know is impossible. The proof technique where we show that a solution for some problem P can be used to solve a different problem Q is known as a reduction.A problem Q is reducible to a problem P if a solution to P could be used to solve Q. This means that problem Q is no harder than problem P since a solution to problem Q leads to a solution to problem P. "
},
{
"code": null,
"e": 3554,
"s": 3457,
"text": "Some Examples Of Computable Problems – These are four simple examples of the computable problem:"
},
{
"code": null,
"e": 3800,
"s": 3554,
"text": "Computing the greatest common divisor of a pair of integers.Computing the least common multiple of a pair of integers.Finding the shortest path between a pair of nodes in a finite graph.Determining whether a propositional formula is a tautology."
},
{
"code": null,
"e": 3861,
"s": 3800,
"text": "Computing the greatest common divisor of a pair of integers."
},
{
"code": null,
"e": 3920,
"s": 3861,
"text": "Computing the least common multiple of a pair of integers."
},
{
"code": null,
"e": 3989,
"s": 3920,
"text": "Finding the shortest path between a pair of nodes in a finite graph."
},
{
"code": null,
"e": 4049,
"s": 3989,
"text": "Determining whether a propositional formula is a tautology."
},
{
"code": null,
"e": 4369,
"s": 4049,
"text": "Some Examples Of Computable Problems – State Entry Problem. Consider the problem of determining if a string ‘w’ is given to some Turing machine ‘M’ will it enter some state ‘q'(where q belongs to a set of all states in Turing machine M and string w is not equal to an empty string). Is it computable or non-computable? "
},
{
"code": null,
"e": 5124,
"s": 4369,
"text": "Explanation – We show the State Entry Problem is non-computable by showing that it is as hard as The Halting Problem, which we already know is non-computable. State Entry Problem is asking us on given string w if we start from initial state of Turing machine will it reach to a state q. Now this state entry problem can be converted to a halting problem. Halting problem is whether our Turing machine ever halts, and the state entry problem is asking the same thing whether this Turing machine halts at some state q if we give string w as input to the Turing machine M. So the state entry problem is non-computable as we converted it to the halting problem which we already know is non-computable problem. So in this way, we can prove non-computability."
},
{
"code": null,
"e": 5138,
"s": 5124,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 5147,
"s": 5138,
"text": "sweetyty"
},
{
"code": null,
"e": 5161,
"s": 5147,
"text": "sahithya3chow"
},
{
"code": null,
"e": 5174,
"s": 5161,
"text": "simmytarika5"
},
{
"code": null,
"e": 5181,
"s": 5174,
"text": "Picked"
},
{
"code": null,
"e": 5189,
"s": 5181,
"text": "GATE CS"
},
{
"code": null,
"e": 5222,
"s": 5189,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 5320,
"s": 5222,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5340,
"s": 5320,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 5364,
"s": 5340,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 5377,
"s": 5364,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 5404,
"s": 5377,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 5425,
"s": 5404,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 5456,
"s": 5425,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 5494,
"s": 5456,
"text": "Boyer-Moore Majority Voting Algorithm"
},
{
"code": null,
"e": 5522,
"s": 5494,
"text": "Variation of Turing Machine"
},
{
"code": null,
"e": 5567,
"s": 5522,
"text": "Design 101 sequence detector (Mealy machine)"
}
] |
Traveling Salesman Problem using Genetic Algorithm
|
23 Dec, 2021
Prerequisites: Genetic Algorithm, Travelling Salesman ProblemIn this article, a genetic algorithm is proposed to solve the travelling salesman problem. Genetic algorithms are heuristic search algorithms inspired by the process that supports the evolution of life. The algorithm is designed to replicate the natural selection process to carry generation, i.e. survival of the fittest of beings. Standard genetic algorithms are divided into five phases which are:
Creating initial population.Calculating fitness.Selecting the best genes.Crossing over.Mutating to introduce variations.
Creating initial population.
Calculating fitness.
Selecting the best genes.
Crossing over.
Mutating to introduce variations.
These algorithms can be implemented to find a solution to the optimization problems of various types. One such problem is the Traveling Salesman Problem. The problem says that a salesman is given a set of cities, he has to find the shortest route to as to visit each city exactly once and return to the starting city. Approach: In the following implementation, cities are taken as genes, string generated using these characters is called a chromosome, while a fitness score which is equal to the path length of all the cities mentioned, is used to target a population.Fitness Score is defined as the length of the path described by the gene. Lesser the path length fitter is the gene. The fittest of all the genes in the gene pool survive the population test and move to the next iteration. The number of iterations depends upon the value of a cooling variable. The value of the cooling variable keeps on decreasing with each iteration and reaches a threshold after a certain number of iterations.Algorithm:
1. Initialize the population randomly.
2. Determine the fitness of the chromosome.
3. Until done repeat:
1. Select parents.
2. Perform crossover and mutation.
3. Calculate the fitness of the new population.
4. Append it to the gene pool.
Pseudo-code
Initialize procedure GA{
Set cooling parameter = 0;
Evaluate population P(t);
While( Not Done ){
Parents(t) = Select_Parents(P(t));
Offspring(t) = Procreate(P(t));
p(t+1) = Select_Survivors(P(t), Offspring(t));
t = t + 1;
}
}
How the mutation works?Suppose there are 5 cities: 0, 1, 2, 3, 4. The salesman is in city 0 and he has to find the shortest route to travel through all the cities back to the city 0. A chromosome representing the path chosen can be represented as:
This chromosome undergoes mutation. During mutation, the position of two cities in the chromosome is swapped to form a new configuration, except the first and the last cell, as they represent the start and endpoint.
Original chromosome had a path length equal to INT_MAX, according to the input defined below, since the path between city 1 and city 4 didn’t exist. After mutation, the new child formed has a path length equal to 21, which is a much-optimized answer than the original assumption. This is how the genetic algorithm optimizes solutions to hard problems.
Below is the implementation of the above approach:
C++
Python3
// C++ implementation of the above approach#include <bits/stdc++.h>#include <limits.h>using namespace std; // Number of cities in TSP#define V 5 // Names of the cities#define GENES ABCDE // Starting Node Value#define START 0 // Initial population size for the algorithm#define POP_SIZE 10 // Structure of a GNOME// string defines the path traversed// by the salesman while the fitness value// of the path is stored in an integer struct individual { string gnome; int fitness;}; // Function to return a random number// from start and endint rand_num(int start, int end){ int r = end - start; int rnum = start + rand() % r; return rnum;} // Function to check if the character// has already occurred in the stringbool repeat(string s, char ch){ for (int i = 0; i < s.size(); i++) { if (s[i] == ch) return true; } return false;} // Function to return a mutated GNOME// Mutated GNOME is a string// with a random interchange// of two genes to create variation in speciesstring mutatedGene(string gnome){ while (true) { int r = rand_num(1, V); int r1 = rand_num(1, V); if (r1 != r) { char temp = gnome[r]; gnome[r] = gnome[r1]; gnome[r1] = temp; break; } } return gnome;} // Function to return a valid GNOME string// required to create the populationstring create_gnome(){ string gnome = "0"; while (true) { if (gnome.size() == V) { gnome += gnome[0]; break; } int temp = rand_num(1, V); if (!repeat(gnome, (char)(temp + 48))) gnome += (char)(temp + 48); } return gnome;} // Function to return the fitness value of a gnome.// The fitness value is the path length// of the path represented by the GNOME.int cal_fitness(string gnome){ int map[V][V] = { { 0, 2, INT_MAX, 12, 5 }, { 2, 0, 4, 8, INT_MAX }, { INT_MAX, 4, 0, 3, 3 }, { 12, 8, 3, 0, 10 }, { 5, INT_MAX, 3, 10, 0 } }; int f = 0; for (int i = 0; i < gnome.size() - 1; i++) { if (map[gnome[i] - 48][gnome[i + 1] - 48] == INT_MAX) return INT_MAX; f += map[gnome[i] - 48][gnome[i + 1] - 48]; } return f;} // Function to return the updated value// of the cooling element.int cooldown(int temp){ return (90 * temp) / 100;} // Comparator for GNOME struct.bool lessthan(struct individual t1, struct individual t2){ return t1.fitness < t2.fitness;} // Utility function for TSP problem.void TSPUtil(int map[V][V]){ // Generation Number int gen = 1; // Number of Gene Iterations int gen_thres = 5; vector<struct individual> population; struct individual temp; // Populating the GNOME pool. for (int i = 0; i < POP_SIZE; i++) { temp.gnome = create_gnome(); temp.fitness = cal_fitness(temp.gnome); population.push_back(temp); } cout << "\nInitial population: " << endl << "GNOME FITNESS VALUE\n"; for (int i = 0; i < POP_SIZE; i++) cout << population[i].gnome << " " << population[i].fitness << endl; cout << "\n"; bool found = false; int temperature = 10000; // Iteration to perform // population crossing and gene mutation. while (temperature > 1000 && gen <= gen_thres) { sort(population.begin(), population.end(), lessthan); cout << "\nCurrent temp: " << temperature << "\n"; vector<struct individual> new_population; for (int i = 0; i < POP_SIZE; i++) { struct individual p1 = population[i]; while (true) { string new_g = mutatedGene(p1.gnome); struct individual new_gnome; new_gnome.gnome = new_g; new_gnome.fitness = cal_fitness(new_gnome.gnome); if (new_gnome.fitness <= population[i].fitness) { new_population.push_back(new_gnome); break; } else { // Accepting the rejected children at // a possible probability above threshold. float prob = pow(2.7, -1 * ((float)(new_gnome.fitness - population[i].fitness) / temperature)); if (prob > 0.5) { new_population.push_back(new_gnome); break; } } } } temperature = cooldown(temperature); population = new_population; cout << "Generation " << gen << " \n"; cout << "GNOME FITNESS VALUE\n"; for (int i = 0; i < POP_SIZE; i++) cout << population[i].gnome << " " << population[i].fitness << endl; gen++; }} int main(){ int map[V][V] = { { 0, 2, INT_MAX, 12, 5 }, { 2, 0, 4, 8, INT_MAX }, { INT_MAX, 4, 0, 3, 3 }, { 12, 8, 3, 0, 10 }, { 5, INT_MAX, 3, 10, 0 } }; TSPUtil(map);}
# Python3 implementation of the above approachfrom random import randint INT_MAX = 2147483647# Number of cities in TSPV = 5 # Names of the citiesGENES = "ABCDE" # Starting Node ValueSTART = 0 # Initial population size for the algorithmPOP_SIZE = 10 # Structure of a GNOME# defines the path traversed# by the salesman while the fitness value# of the path is stored in an integer class individual: def __init__(self) -> None: self.gnome = "" self.fitness = 0 def __lt__(self, other): return self.fitness < other.fitness def __gt__(self, other): return self.fitness > other.fitness # Function to return a random number# from start and enddef rand_num(start, end): return randint(start, end-1) # Function to check if the character# has already occurred in the stringdef repeat(s, ch): for i in range(len(s)): if s[i] == ch: return True return False # Function to return a mutated GNOME# Mutated GNOME is a string# with a random interchange# of two genes to create variation in speciesdef mutatedGene(gnome): gnome = list(gnome) while True: r = rand_num(1, V) r1 = rand_num(1, V) if r1 != r: temp = gnome[r] gnome[r] = gnome[r1] gnome[r1] = temp break return ''.join(gnome) # Function to return a valid GNOME string# required to create the populationdef create_gnome(): gnome = "0" while True: if len(gnome) == V: gnome += gnome[0] break temp = rand_num(1, V) if not repeat(gnome, chr(temp + 48)): gnome += chr(temp + 48) return gnome # Function to return the fitness value of a gnome.# The fitness value is the path length# of the path represented by the GNOME.def cal_fitness(gnome): mp = [ [0, 2, INT_MAX, 12, 5], [2, 0, 4, 8, INT_MAX], [INT_MAX, 4, 0, 3, 3], [12, 8, 3, 0, 10], [5, INT_MAX, 3, 10, 0], ] f = 0 for i in range(len(gnome) - 1): if mp[ord(gnome[i]) - 48][ord(gnome[i + 1]) - 48] == INT_MAX: return INT_MAX f += mp[ord(gnome[i]) - 48][ord(gnome[i + 1]) - 48] return f # Function to return the updated value# of the cooling element.def cooldown(temp): return (90 * temp) / 100 # Comparator for GNOME struct.# def lessthan(individual t1,# individual t2)# :# return t1.fitness < t2.fitness # Utility function for TSP problem.def TSPUtil(mp): # Generation Number gen = 1 # Number of Gene Iterations gen_thres = 5 population = [] temp = individual() # Populating the GNOME pool. for i in range(POP_SIZE): temp.gnome = create_gnome() temp.fitness = cal_fitness(temp.gnome) population.append(temp) print("\nInitial population: \nGNOME FITNESS VALUE\n") for i in range(POP_SIZE): print(population[i].gnome, population[i].fitness) print() found = False temperature = 10000 # Iteration to perform # population crossing and gene mutation. while temperature > 1000 and gen <= gen_thres: population.sort() print("\nCurrent temp: ", temperature) new_population = [] for i in range(POP_SIZE): p1 = population[i] while True: new_g = mutatedGene(p1.gnome) new_gnome = individual() new_gnome.gnome = new_g new_gnome.fitness = cal_fitness(new_gnome.gnome) if new_gnome.fitness <= population[i].fitness: new_population.append(new_gnome) break else: # Accepting the rejected children at # a possible probability above threshold. prob = pow( 2.7, -1 * ( (float)(new_gnome.fitness - population[i].fitness) / temperature ), ) if prob > 0.5: new_population.append(new_gnome) break temperature = cooldown(temperature) population = new_population print("Generation", gen) print("GNOME FITNESS VALUE") for i in range(POP_SIZE): print(population[i].gnome, population[i].fitness) gen += 1 if __name__ == "__main__": mp = [ [0, 2, INT_MAX, 12, 5], [2, 0, 4, 8, INT_MAX], [INT_MAX, 4, 0, 3, 3], [12, 8, 3, 0, 10], [5, INT_MAX, 3, 10, 0], ] TSPUtil(mp)
Initial population:
GNOME FITNESS VALUE
043210 24
023410 2147483647
031420 2147483647
034210 31
043210 24
023140 2147483647
032410 2147483647
012340 24
012340 24
032410 2147483647
Current temp: 10000
Generation 1
GNOME FITNESS VALUE
013240 21
013240 21
012430 31
012430 31
031240 32
024310 2147483647
013420 2147483647
032140 2147483647
034210 31
012430 31
Current temp: 9000
Generation 2
GNOME FITNESS VALUE
031240 32
043210 24
012340 24
042130 32
043210 24
012340 24
034210 31
014320 2147483647
014320 2147483647
023140 2147483647
Current temp: 8100
Generation 3
GNOME FITNESS VALUE
013240 21
042310 21
013240 21
013240 21
031240 32
013240 21
012430 31
034120 2147483647
041320 2147483647
043120 2147483647
Current temp: 7290
Generation 4
GNOME FITNESS VALUE
031240 32
043210 24
043210 24
043210 24
012340 24
042130 32
013240 21
014320 2147483647
021340 2147483647
043210 24
Current temp: 6561
Generation 5
GNOME FITNESS VALUE
043210 24
042310 21
042310 21
013240 21
042310 21
034210 31
013240 21
042310 21
024310 2147483647
024310 2147483647
abhishek0719kadiyan
amartyaghoshgfg
Algorithms
Graph
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 518,
"s": 54,
"text": "Prerequisites: Genetic Algorithm, Travelling Salesman ProblemIn this article, a genetic algorithm is proposed to solve the travelling salesman problem. Genetic algorithms are heuristic search algorithms inspired by the process that supports the evolution of life. The algorithm is designed to replicate the natural selection process to carry generation, i.e. survival of the fittest of beings. Standard genetic algorithms are divided into five phases which are: "
},
{
"code": null,
"e": 639,
"s": 518,
"text": "Creating initial population.Calculating fitness.Selecting the best genes.Crossing over.Mutating to introduce variations."
},
{
"code": null,
"e": 668,
"s": 639,
"text": "Creating initial population."
},
{
"code": null,
"e": 689,
"s": 668,
"text": "Calculating fitness."
},
{
"code": null,
"e": 715,
"s": 689,
"text": "Selecting the best genes."
},
{
"code": null,
"e": 730,
"s": 715,
"text": "Crossing over."
},
{
"code": null,
"e": 764,
"s": 730,
"text": "Mutating to introduce variations."
},
{
"code": null,
"e": 1774,
"s": 764,
"text": "These algorithms can be implemented to find a solution to the optimization problems of various types. One such problem is the Traveling Salesman Problem. The problem says that a salesman is given a set of cities, he has to find the shortest route to as to visit each city exactly once and return to the starting city. Approach: In the following implementation, cities are taken as genes, string generated using these characters is called a chromosome, while a fitness score which is equal to the path length of all the cities mentioned, is used to target a population.Fitness Score is defined as the length of the path described by the gene. Lesser the path length fitter is the gene. The fittest of all the genes in the gene pool survive the population test and move to the next iteration. The number of iterations depends upon the value of a cooling variable. The value of the cooling variable keeps on decreasing with each iteration and reaches a threshold after a certain number of iterations.Algorithm: "
},
{
"code": null,
"e": 2028,
"s": 1774,
"text": "1. Initialize the population randomly.\n2. Determine the fitness of the chromosome.\n3. Until done repeat:\n 1. Select parents.\n 2. Perform crossover and mutation.\n 3. Calculate the fitness of the new population.\n 4. Append it to the gene pool."
},
{
"code": null,
"e": 2044,
"s": 2030,
"text": "Pseudo-code "
},
{
"code": null,
"e": 2319,
"s": 2044,
"text": "Initialize procedure GA{\n Set cooling parameter = 0;\n Evaluate population P(t);\n While( Not Done ){\n Parents(t) = Select_Parents(P(t));\n Offspring(t) = Procreate(P(t));\n p(t+1) = Select_Survivors(P(t), Offspring(t));\n t = t + 1; \n }\n}"
},
{
"code": null,
"e": 2569,
"s": 2319,
"text": "How the mutation works?Suppose there are 5 cities: 0, 1, 2, 3, 4. The salesman is in city 0 and he has to find the shortest route to travel through all the cities back to the city 0. A chromosome representing the path chosen can be represented as: "
},
{
"code": null,
"e": 2787,
"s": 2569,
"text": "This chromosome undergoes mutation. During mutation, the position of two cities in the chromosome is swapped to form a new configuration, except the first and the last cell, as they represent the start and endpoint. "
},
{
"code": null,
"e": 3140,
"s": 2787,
"text": "Original chromosome had a path length equal to INT_MAX, according to the input defined below, since the path between city 1 and city 4 didn’t exist. After mutation, the new child formed has a path length equal to 21, which is a much-optimized answer than the original assumption. This is how the genetic algorithm optimizes solutions to hard problems. "
},
{
"code": null,
"e": 3192,
"s": 3140,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 3196,
"s": 3192,
"text": "C++"
},
{
"code": null,
"e": 3204,
"s": 3196,
"text": "Python3"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>#include <limits.h>using namespace std; // Number of cities in TSP#define V 5 // Names of the cities#define GENES ABCDE // Starting Node Value#define START 0 // Initial population size for the algorithm#define POP_SIZE 10 // Structure of a GNOME// string defines the path traversed// by the salesman while the fitness value// of the path is stored in an integer struct individual { string gnome; int fitness;}; // Function to return a random number// from start and endint rand_num(int start, int end){ int r = end - start; int rnum = start + rand() % r; return rnum;} // Function to check if the character// has already occurred in the stringbool repeat(string s, char ch){ for (int i = 0; i < s.size(); i++) { if (s[i] == ch) return true; } return false;} // Function to return a mutated GNOME// Mutated GNOME is a string// with a random interchange// of two genes to create variation in speciesstring mutatedGene(string gnome){ while (true) { int r = rand_num(1, V); int r1 = rand_num(1, V); if (r1 != r) { char temp = gnome[r]; gnome[r] = gnome[r1]; gnome[r1] = temp; break; } } return gnome;} // Function to return a valid GNOME string// required to create the populationstring create_gnome(){ string gnome = \"0\"; while (true) { if (gnome.size() == V) { gnome += gnome[0]; break; } int temp = rand_num(1, V); if (!repeat(gnome, (char)(temp + 48))) gnome += (char)(temp + 48); } return gnome;} // Function to return the fitness value of a gnome.// The fitness value is the path length// of the path represented by the GNOME.int cal_fitness(string gnome){ int map[V][V] = { { 0, 2, INT_MAX, 12, 5 }, { 2, 0, 4, 8, INT_MAX }, { INT_MAX, 4, 0, 3, 3 }, { 12, 8, 3, 0, 10 }, { 5, INT_MAX, 3, 10, 0 } }; int f = 0; for (int i = 0; i < gnome.size() - 1; i++) { if (map[gnome[i] - 48][gnome[i + 1] - 48] == INT_MAX) return INT_MAX; f += map[gnome[i] - 48][gnome[i + 1] - 48]; } return f;} // Function to return the updated value// of the cooling element.int cooldown(int temp){ return (90 * temp) / 100;} // Comparator for GNOME struct.bool lessthan(struct individual t1, struct individual t2){ return t1.fitness < t2.fitness;} // Utility function for TSP problem.void TSPUtil(int map[V][V]){ // Generation Number int gen = 1; // Number of Gene Iterations int gen_thres = 5; vector<struct individual> population; struct individual temp; // Populating the GNOME pool. for (int i = 0; i < POP_SIZE; i++) { temp.gnome = create_gnome(); temp.fitness = cal_fitness(temp.gnome); population.push_back(temp); } cout << \"\\nInitial population: \" << endl << \"GNOME FITNESS VALUE\\n\"; for (int i = 0; i < POP_SIZE; i++) cout << population[i].gnome << \" \" << population[i].fitness << endl; cout << \"\\n\"; bool found = false; int temperature = 10000; // Iteration to perform // population crossing and gene mutation. while (temperature > 1000 && gen <= gen_thres) { sort(population.begin(), population.end(), lessthan); cout << \"\\nCurrent temp: \" << temperature << \"\\n\"; vector<struct individual> new_population; for (int i = 0; i < POP_SIZE; i++) { struct individual p1 = population[i]; while (true) { string new_g = mutatedGene(p1.gnome); struct individual new_gnome; new_gnome.gnome = new_g; new_gnome.fitness = cal_fitness(new_gnome.gnome); if (new_gnome.fitness <= population[i].fitness) { new_population.push_back(new_gnome); break; } else { // Accepting the rejected children at // a possible probability above threshold. float prob = pow(2.7, -1 * ((float)(new_gnome.fitness - population[i].fitness) / temperature)); if (prob > 0.5) { new_population.push_back(new_gnome); break; } } } } temperature = cooldown(temperature); population = new_population; cout << \"Generation \" << gen << \" \\n\"; cout << \"GNOME FITNESS VALUE\\n\"; for (int i = 0; i < POP_SIZE; i++) cout << population[i].gnome << \" \" << population[i].fitness << endl; gen++; }} int main(){ int map[V][V] = { { 0, 2, INT_MAX, 12, 5 }, { 2, 0, 4, 8, INT_MAX }, { INT_MAX, 4, 0, 3, 3 }, { 12, 8, 3, 0, 10 }, { 5, INT_MAX, 3, 10, 0 } }; TSPUtil(map);}",
"e": 8355,
"s": 3204,
"text": null
},
{
"code": "# Python3 implementation of the above approachfrom random import randint INT_MAX = 2147483647# Number of cities in TSPV = 5 # Names of the citiesGENES = \"ABCDE\" # Starting Node ValueSTART = 0 # Initial population size for the algorithmPOP_SIZE = 10 # Structure of a GNOME# defines the path traversed# by the salesman while the fitness value# of the path is stored in an integer class individual: def __init__(self) -> None: self.gnome = \"\" self.fitness = 0 def __lt__(self, other): return self.fitness < other.fitness def __gt__(self, other): return self.fitness > other.fitness # Function to return a random number# from start and enddef rand_num(start, end): return randint(start, end-1) # Function to check if the character# has already occurred in the stringdef repeat(s, ch): for i in range(len(s)): if s[i] == ch: return True return False # Function to return a mutated GNOME# Mutated GNOME is a string# with a random interchange# of two genes to create variation in speciesdef mutatedGene(gnome): gnome = list(gnome) while True: r = rand_num(1, V) r1 = rand_num(1, V) if r1 != r: temp = gnome[r] gnome[r] = gnome[r1] gnome[r1] = temp break return ''.join(gnome) # Function to return a valid GNOME string# required to create the populationdef create_gnome(): gnome = \"0\" while True: if len(gnome) == V: gnome += gnome[0] break temp = rand_num(1, V) if not repeat(gnome, chr(temp + 48)): gnome += chr(temp + 48) return gnome # Function to return the fitness value of a gnome.# The fitness value is the path length# of the path represented by the GNOME.def cal_fitness(gnome): mp = [ [0, 2, INT_MAX, 12, 5], [2, 0, 4, 8, INT_MAX], [INT_MAX, 4, 0, 3, 3], [12, 8, 3, 0, 10], [5, INT_MAX, 3, 10, 0], ] f = 0 for i in range(len(gnome) - 1): if mp[ord(gnome[i]) - 48][ord(gnome[i + 1]) - 48] == INT_MAX: return INT_MAX f += mp[ord(gnome[i]) - 48][ord(gnome[i + 1]) - 48] return f # Function to return the updated value# of the cooling element.def cooldown(temp): return (90 * temp) / 100 # Comparator for GNOME struct.# def lessthan(individual t1,# individual t2)# :# return t1.fitness < t2.fitness # Utility function for TSP problem.def TSPUtil(mp): # Generation Number gen = 1 # Number of Gene Iterations gen_thres = 5 population = [] temp = individual() # Populating the GNOME pool. for i in range(POP_SIZE): temp.gnome = create_gnome() temp.fitness = cal_fitness(temp.gnome) population.append(temp) print(\"\\nInitial population: \\nGNOME FITNESS VALUE\\n\") for i in range(POP_SIZE): print(population[i].gnome, population[i].fitness) print() found = False temperature = 10000 # Iteration to perform # population crossing and gene mutation. while temperature > 1000 and gen <= gen_thres: population.sort() print(\"\\nCurrent temp: \", temperature) new_population = [] for i in range(POP_SIZE): p1 = population[i] while True: new_g = mutatedGene(p1.gnome) new_gnome = individual() new_gnome.gnome = new_g new_gnome.fitness = cal_fitness(new_gnome.gnome) if new_gnome.fitness <= population[i].fitness: new_population.append(new_gnome) break else: # Accepting the rejected children at # a possible probability above threshold. prob = pow( 2.7, -1 * ( (float)(new_gnome.fitness - population[i].fitness) / temperature ), ) if prob > 0.5: new_population.append(new_gnome) break temperature = cooldown(temperature) population = new_population print(\"Generation\", gen) print(\"GNOME FITNESS VALUE\") for i in range(POP_SIZE): print(population[i].gnome, population[i].fitness) gen += 1 if __name__ == \"__main__\": mp = [ [0, 2, INT_MAX, 12, 5], [2, 0, 4, 8, INT_MAX], [INT_MAX, 4, 0, 3, 3], [12, 8, 3, 0, 10], [5, INT_MAX, 3, 10, 0], ] TSPUtil(mp)",
"e": 12958,
"s": 8355,
"text": null
},
{
"code": null,
"e": 14159,
"s": 12958,
"text": "Initial population: \nGNOME FITNESS VALUE\n043210 24\n023410 2147483647\n031420 2147483647\n034210 31\n043210 24\n023140 2147483647\n032410 2147483647\n012340 24\n012340 24\n032410 2147483647\n\n\nCurrent temp: 10000\nGeneration 1 \nGNOME FITNESS VALUE\n013240 21\n013240 21\n012430 31\n012430 31\n031240 32\n024310 2147483647\n013420 2147483647\n032140 2147483647\n034210 31\n012430 31\n\nCurrent temp: 9000\nGeneration 2 \nGNOME FITNESS VALUE\n031240 32\n043210 24\n012340 24\n042130 32\n043210 24\n012340 24\n034210 31\n014320 2147483647\n014320 2147483647\n023140 2147483647\n\nCurrent temp: 8100\nGeneration 3 \nGNOME FITNESS VALUE\n013240 21\n042310 21\n013240 21\n013240 21\n031240 32\n013240 21\n012430 31\n034120 2147483647\n041320 2147483647\n043120 2147483647\n\nCurrent temp: 7290\nGeneration 4 \nGNOME FITNESS VALUE\n031240 32\n043210 24\n043210 24\n043210 24\n012340 24\n042130 32\n013240 21\n014320 2147483647\n021340 2147483647\n043210 24\n\nCurrent temp: 6561\nGeneration 5 \nGNOME FITNESS VALUE\n043210 24\n042310 21\n042310 21\n013240 21\n042310 21\n034210 31\n013240 21\n042310 21\n024310 2147483647\n024310 2147483647"
},
{
"code": null,
"e": 14181,
"s": 14161,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 14197,
"s": 14181,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 14208,
"s": 14197,
"text": "Algorithms"
},
{
"code": null,
"e": 14214,
"s": 14208,
"text": "Graph"
},
{
"code": null,
"e": 14220,
"s": 14214,
"text": "Graph"
},
{
"code": null,
"e": 14231,
"s": 14220,
"text": "Algorithms"
}
] |
Fill array with 1's using minimum iterations of filling neighbors - GeeksforGeeks
|
28 Apr, 2021
Given an array of 0s and 1s, in how many iterations the whole array can be filled with 1s if in a single iteration immediate neighbors of 1s can be filled.NOTE: If we cannot fill array with 1s, then print “-1” .Examples :
Input : arr[] = {1, 0, 1, 0, 0, 1, 0, 1,
1, 0, 1, 1, 0, 0, 1}
Output : 1
To convert the whole array into 1s, one iteration
is required. Between indexes i=2 and i=5, the zero
at i=3 would be converted to '1' due to its neighbours
at i=2 similarly the zero at i=4 would be converted
into '1' due to its neighbor at i=5, all this can
be done in a single iteration. Similarly all 0's can
be converted to 1 in single iteration.
Input : arr[] = {0, 0, 1, 1, 0, 0, 1, 1, 0,
1, 1, 1, 1, 0, 0, 0, 1}
Output : 2
Asked in : Amazon
It is given that a single 1 can convert both its 0 neighbours to 1. This problem boils down to three cases :
Case 1 : A block of 0s has 1s on both sides
Let count_zero be the count of zeros in the block.
Number of iterations are always equal to :
count_zero/2 if (count_zero is even)
count_zero+1)/2 if(count_zero is odd).
Case 2 : Either single 1 at the end or in
the starting. For example 0 0 0 0 1 and
1 0 0 0 0
In this case the number of iterations required will
always be equal to number of zeros.
Case 3 : There are no 1s (Array has only 0s)
In this case array can't be filled with all 1's.
So print -1.
Algorithm :
1-Start traversing the array.
(a) Traverse until a 0 is found.
while (i < n && a[i] == 1)
{
i++;
flag=true;
}
Flag is set to true just to check at
the last if array contains any 1 or not.
(b) Traverse until a 1 is found and Count
contiguous 0 .
while (i < n && a[i] == 0)
{
count_zero++;
i++;
}
(c) Now check which case is satisfied by
current subarray. And update iterations
using count and update max iterations.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find number of iterations// to fill with all 1s#include<bits/stdc++.h>using namespace std; // Returns count of iterations to fill arr[]// with 1s.int countIterations(int arr[], int n){ bool oneFound = false; int res = 0; // Start traversing the array for (int i=0; i<n; ) { if (arr[i] == 1) oneFound = true; // Traverse until a 0 is found while (i<n && arr[i]==1) i++; // Count contiguous 0s int count_zero = 0; while (i<n && arr[i]==0) { count_zero++; i++; } // Condition for Case 3 if (oneFound == false && i == n) return -1; // Condition to check if Case 1 satisfies: int curr_count; if (i < n && oneFound == true) { // If count_zero is even if (count_zero & 1 == 0) curr_count = count_zero/2; // If count_zero is odd else curr_count = (count_zero+1)/2; // Reset count_zero count_zero = 0; } // Case 2 else { curr_count = count_zero; count_zero = 0; } // Update res res = max(res, curr_count); } return res;} // Driver codeint main(){ int arr[] = {0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0}; int n = sizeof(arr) / sizeof(arr[0]); cout << countIterations(arr, n); return 0;}
// Java program to find number of iterations// to fill with all 1s class Test{ // Returns count of iterations to fill arr[] // with 1s. static int countIterations(int arr[], int n) { boolean oneFound = false; int res = 0; // Start traversing the array for (int i=0; i<n; ) { if (arr[i] == 1) oneFound = true; // Traverse until a 0 is found while (i<n && arr[i]==1) i++; // Count contiguous 0s int count_zero = 0; while (i<n && arr[i]==0) { count_zero++; i++; } // Condition for Case 3 if (oneFound == false && i == n) return -1; // Condition to check if Case 1 satisfies: int curr_count; if (i < n && oneFound == true) { // If count_zero is even if ((count_zero & 1) == 0) curr_count = count_zero/2; // If count_zero is odd else curr_count = (count_zero+1)/2; // Reset count_zero count_zero = 0; } // Case 2 else { curr_count = count_zero; count_zero = 0; } // Update res res = Math.max(res, curr_count); } return res; } // Driver method public static void main(String[] args) { int arr[] = {0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0}; System.out.println(countIterations(arr, arr.length)); }}
# Python3 program to find number# of iterations to fill with all 1s # Returns count of iterations# to fill arr[] with 1s.def countIterations(arr, n): oneFound = False; res = 0; i = 0; # Start traversing the array while (i < n): if (arr[i] == 1): oneFound = True; # Traverse until a 0 is found while (i < n and arr[i] == 1): i += 1; # Count contiguous 0s count_zero = 0; while (i < n and arr[i] == 0): count_zero += 1; i += 1; # Condition for Case 3 if (oneFound == False and i == n): return -1; # Condition to check # if Case 1 satisfies: curr_count = 0; if (i < n and oneFound == True): # If count_zero is even if ((count_zero & 1) == 0): curr_count = count_zero // 2; # If count_zero is odd else: curr_count = (count_zero + 1) // 2; # Reset count_zero count_zero = 0; # Case 2 else: curr_count = count_zero; count_zero = 0; # Update res res = max(res, curr_count); return res; # Driver codearr = [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0];n = len(arr);print(countIterations(arr, n)); # This code is contributed by mits
// C# program to find number of// iterations to fill with all 1susing System; class Test { // Returns count of iterations // to fill arr[] with 1s. static int countIterations(int []arr, int n) { bool oneFound = false; int res = 0; // Start traversing the array for (int i = 0; i < n; ) { if (arr[i] == 1) oneFound = true; // Traverse until a 0 is found while (i < n && arr[i] == 1) i++; // Count contiguous 0s int count_zero = 0; while (i < n && arr[i] == 0) { count_zero++; i++; } // Condition for Case 3 if (oneFound == false && i == n) return -1; // Condition to check if // Case 1 satisfies: int curr_count; if (i < n && oneFound == true) { // If count_zero is even if ((count_zero & 1) == 0) curr_count = count_zero / 2; // If count_zero is odd else curr_count = (count_zero + 1) / 2; // Reset count_zero count_zero = 0; } // Case 2 else { curr_count = count_zero; count_zero = 0; } // Update res res = Math.Max(res, curr_count); } return res; } // Driver code public static void Main() { int []arr = {0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0}; Console.Write(countIterations(arr, arr.Length)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find number// of iterations to fill with all 1s // Returns count of iterations// to fill arr[] with 1s.function countIterations($arr, $n){ $oneFound = false; $res = 0; // Start traversing the array for ( $i = 0; $i < $n; ) { if ($arr[$i] == 1) $oneFound = true; // Traverse until a 0 is found while ($i < $n && $arr[$i] == 1) $i++; // Count contiguous 0s $count_zero = 0; while ($i < $n && $arr[$i] == 0) { $count_zero++; $i++; } // Condition for Case 3 if ($oneFound == false && $i == $n) return -1; // Condition to check // if Case 1 satisfies: $curr_count; if ($i < $n && $oneFound == true) { // If count_zero is even if ($count_zero & 1 == 0) $curr_count = $count_zero / 2; // If count_zero is odd else $curr_count = ($count_zero + 1) / 2; // Reset count_zero $count_zero = 0; } // Case 2 else { $curr_count = $count_zero; $count_zero = 0; } // Update res $res = max($res, $curr_count); } return $res;} // Driver code$arr = array(0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0);$n = sizeof($arr) / sizeof($arr[0]);echo countIterations($arr, $n); // This code is contributed by nitin mittal.?>
<script> // Javascript program to find number of// iterations to fill with all 1s // Returns count of iterations to fill arr[]// with 1s.function countIterations(arr, n){ var oneFound = false; var res = 0; // Start traversing the array for(var i = 0; i < n; ) { if (arr[i] == 1) oneFound = true; // Traverse until a 0 is found while (i < n && arr[i] == 1) i++; // Count contiguous 0s var count_zero = 0; while (i < n && arr[i] == 0) { count_zero++; i++; } // Condition for Case 3 if (oneFound == false && i == n) return -1; // Condition to check if Case 1 satisfies: var curr_count; if (i < n && oneFound == true) { // If count_zero is even if ((count_zero & 1) == 0) curr_count = count_zero / 2; // If count_zero is odd else curr_count = (count_zero + 1) / 2; // Reset count_zero count_zero = 0; } // Case 2 else { curr_count = count_zero; count_zero = 0; } // Update res res = Math.max(res, curr_count); } return res;} // Driver Codevar arr = [ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]; document.write(countIterations(arr, arr.length)); // This code is contributed by Ankita saini </script>
Output :
4
Time Complexity : O(n)This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
Mithun Kumar
ankita_saini
Amazon
binary-string
Arrays
Mathematical
Amazon
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24915,
"s": 24887,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 25139,
"s": 24915,
"text": "Given an array of 0s and 1s, in how many iterations the whole array can be filled with 1s if in a single iteration immediate neighbors of 1s can be filled.NOTE: If we cannot fill array with 1s, then print “-1” .Examples : "
},
{
"code": null,
"e": 25688,
"s": 25139,
"text": "Input : arr[] = {1, 0, 1, 0, 0, 1, 0, 1, \n 1, 0, 1, 1, 0, 0, 1}\nOutput : 1\nTo convert the whole array into 1s, one iteration\nis required. Between indexes i=2 and i=5, the zero \nat i=3 would be converted to '1' due to its neighbours\nat i=2 similarly the zero at i=4 would be converted \ninto '1' due to its neighbor at i=5, all this can \nbe done in a single iteration. Similarly all 0's can\nbe converted to 1 in single iteration.\n\nInput : arr[] = {0, 0, 1, 1, 0, 0, 1, 1, 0, \n 1, 1, 1, 1, 0, 0, 0, 1}\nOutput : 2"
},
{
"code": null,
"e": 25707,
"s": 25688,
"text": "Asked in : Amazon "
},
{
"code": null,
"e": 25818,
"s": 25707,
"text": "It is given that a single 1 can convert both its 0 neighbours to 1. This problem boils down to three cases : "
},
{
"code": null,
"e": 26379,
"s": 25818,
"text": "Case 1 : A block of 0s has 1s on both sides\n\nLet count_zero be the count of zeros in the block.\n\nNumber of iterations are always equal to : \n count_zero/2 if (count_zero is even)\n count_zero+1)/2 if(count_zero is odd).\n\nCase 2 : Either single 1 at the end or in \n the starting. For example 0 0 0 0 1 and \n 1 0 0 0 0\nIn this case the number of iterations required will \nalways be equal to number of zeros.\n\nCase 3 : There are no 1s (Array has only 0s)\nIn this case array can't be filled with all 1's. \nSo print -1."
},
{
"code": null,
"e": 26393,
"s": 26379,
"text": "Algorithm : "
},
{
"code": null,
"e": 26909,
"s": 26393,
"text": "1-Start traversing the array.\n (a) Traverse until a 0 is found.\n while (i < n && a[i] == 1)\n {\n i++;\n flag=true;\n }\n Flag is set to true just to check at \n the last if array contains any 1 or not.\n\n (b) Traverse until a 1 is found and Count \n contiguous 0 .\n while (i < n && a[i] == 0)\n {\n count_zero++;\n i++;\n }\n\n (c) Now check which case is satisfied by \n current subarray. And update iterations \n using count and update max iterations. "
},
{
"code": null,
"e": 26915,
"s": 26911,
"text": "C++"
},
{
"code": null,
"e": 26920,
"s": 26915,
"text": "Java"
},
{
"code": null,
"e": 26928,
"s": 26920,
"text": "Python3"
},
{
"code": null,
"e": 26931,
"s": 26928,
"text": "C#"
},
{
"code": null,
"e": 26935,
"s": 26931,
"text": "PHP"
},
{
"code": null,
"e": 26946,
"s": 26935,
"text": "Javascript"
},
{
"code": "// C++ program to find number of iterations// to fill with all 1s#include<bits/stdc++.h>using namespace std; // Returns count of iterations to fill arr[]// with 1s.int countIterations(int arr[], int n){ bool oneFound = false; int res = 0; // Start traversing the array for (int i=0; i<n; ) { if (arr[i] == 1) oneFound = true; // Traverse until a 0 is found while (i<n && arr[i]==1) i++; // Count contiguous 0s int count_zero = 0; while (i<n && arr[i]==0) { count_zero++; i++; } // Condition for Case 3 if (oneFound == false && i == n) return -1; // Condition to check if Case 1 satisfies: int curr_count; if (i < n && oneFound == true) { // If count_zero is even if (count_zero & 1 == 0) curr_count = count_zero/2; // If count_zero is odd else curr_count = (count_zero+1)/2; // Reset count_zero count_zero = 0; } // Case 2 else { curr_count = count_zero; count_zero = 0; } // Update res res = max(res, curr_count); } return res;} // Driver codeint main(){ int arr[] = {0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0}; int n = sizeof(arr) / sizeof(arr[0]); cout << countIterations(arr, n); return 0;}",
"e": 28416,
"s": 26946,
"text": null
},
{
"code": "// Java program to find number of iterations// to fill with all 1s class Test{ // Returns count of iterations to fill arr[] // with 1s. static int countIterations(int arr[], int n) { boolean oneFound = false; int res = 0; // Start traversing the array for (int i=0; i<n; ) { if (arr[i] == 1) oneFound = true; // Traverse until a 0 is found while (i<n && arr[i]==1) i++; // Count contiguous 0s int count_zero = 0; while (i<n && arr[i]==0) { count_zero++; i++; } // Condition for Case 3 if (oneFound == false && i == n) return -1; // Condition to check if Case 1 satisfies: int curr_count; if (i < n && oneFound == true) { // If count_zero is even if ((count_zero & 1) == 0) curr_count = count_zero/2; // If count_zero is odd else curr_count = (count_zero+1)/2; // Reset count_zero count_zero = 0; } // Case 2 else { curr_count = count_zero; count_zero = 0; } // Update res res = Math.max(res, curr_count); } return res; } // Driver method public static void main(String[] args) { int arr[] = {0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0}; System.out.println(countIterations(arr, arr.length)); }}",
"e": 30161,
"s": 28416,
"text": null
},
{
"code": "# Python3 program to find number# of iterations to fill with all 1s # Returns count of iterations# to fill arr[] with 1s.def countIterations(arr, n): oneFound = False; res = 0; i = 0; # Start traversing the array while (i < n): if (arr[i] == 1): oneFound = True; # Traverse until a 0 is found while (i < n and arr[i] == 1): i += 1; # Count contiguous 0s count_zero = 0; while (i < n and arr[i] == 0): count_zero += 1; i += 1; # Condition for Case 3 if (oneFound == False and i == n): return -1; # Condition to check # if Case 1 satisfies: curr_count = 0; if (i < n and oneFound == True): # If count_zero is even if ((count_zero & 1) == 0): curr_count = count_zero // 2; # If count_zero is odd else: curr_count = (count_zero + 1) // 2; # Reset count_zero count_zero = 0; # Case 2 else: curr_count = count_zero; count_zero = 0; # Update res res = max(res, curr_count); return res; # Driver codearr = [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0];n = len(arr);print(countIterations(arr, n)); # This code is contributed by mits",
"e": 31519,
"s": 30161,
"text": null
},
{
"code": "// C# program to find number of// iterations to fill with all 1susing System; class Test { // Returns count of iterations // to fill arr[] with 1s. static int countIterations(int []arr, int n) { bool oneFound = false; int res = 0; // Start traversing the array for (int i = 0; i < n; ) { if (arr[i] == 1) oneFound = true; // Traverse until a 0 is found while (i < n && arr[i] == 1) i++; // Count contiguous 0s int count_zero = 0; while (i < n && arr[i] == 0) { count_zero++; i++; } // Condition for Case 3 if (oneFound == false && i == n) return -1; // Condition to check if // Case 1 satisfies: int curr_count; if (i < n && oneFound == true) { // If count_zero is even if ((count_zero & 1) == 0) curr_count = count_zero / 2; // If count_zero is odd else curr_count = (count_zero + 1) / 2; // Reset count_zero count_zero = 0; } // Case 2 else { curr_count = count_zero; count_zero = 0; } // Update res res = Math.Max(res, curr_count); } return res; } // Driver code public static void Main() { int []arr = {0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0}; Console.Write(countIterations(arr, arr.Length)); }} // This code is contributed by nitin mittal.",
"e": 33341,
"s": 31519,
"text": null
},
{
"code": "<?php// PHP program to find number// of iterations to fill with all 1s // Returns count of iterations// to fill arr[] with 1s.function countIterations($arr, $n){ $oneFound = false; $res = 0; // Start traversing the array for ( $i = 0; $i < $n; ) { if ($arr[$i] == 1) $oneFound = true; // Traverse until a 0 is found while ($i < $n && $arr[$i] == 1) $i++; // Count contiguous 0s $count_zero = 0; while ($i < $n && $arr[$i] == 0) { $count_zero++; $i++; } // Condition for Case 3 if ($oneFound == false && $i == $n) return -1; // Condition to check // if Case 1 satisfies: $curr_count; if ($i < $n && $oneFound == true) { // If count_zero is even if ($count_zero & 1 == 0) $curr_count = $count_zero / 2; // If count_zero is odd else $curr_count = ($count_zero + 1) / 2; // Reset count_zero $count_zero = 0; } // Case 2 else { $curr_count = $count_zero; $count_zero = 0; } // Update res $res = max($res, $curr_count); } return $res;} // Driver code$arr = array(0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0);$n = sizeof($arr) / sizeof($arr[0]);echo countIterations($arr, $n); // This code is contributed by nitin mittal.?>",
"e": 34819,
"s": 33341,
"text": null
},
{
"code": "<script> // Javascript program to find number of// iterations to fill with all 1s // Returns count of iterations to fill arr[]// with 1s.function countIterations(arr, n){ var oneFound = false; var res = 0; // Start traversing the array for(var i = 0; i < n; ) { if (arr[i] == 1) oneFound = true; // Traverse until a 0 is found while (i < n && arr[i] == 1) i++; // Count contiguous 0s var count_zero = 0; while (i < n && arr[i] == 0) { count_zero++; i++; } // Condition for Case 3 if (oneFound == false && i == n) return -1; // Condition to check if Case 1 satisfies: var curr_count; if (i < n && oneFound == true) { // If count_zero is even if ((count_zero & 1) == 0) curr_count = count_zero / 2; // If count_zero is odd else curr_count = (count_zero + 1) / 2; // Reset count_zero count_zero = 0; } // Case 2 else { curr_count = count_zero; count_zero = 0; } // Update res res = Math.max(res, curr_count); } return res;} // Driver Codevar arr = [ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]; document.write(countIterations(arr, arr.length)); // This code is contributed by Ankita saini </script>",
"e": 36316,
"s": 34819,
"text": null
},
{
"code": null,
"e": 36327,
"s": 36316,
"text": "Output : "
},
{
"code": null,
"e": 36329,
"s": 36327,
"text": "4"
},
{
"code": null,
"e": 36773,
"s": 36329,
"text": "Time Complexity : O(n)This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36786,
"s": 36773,
"text": "nitin mittal"
},
{
"code": null,
"e": 36799,
"s": 36786,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 36812,
"s": 36799,
"text": "ankita_saini"
},
{
"code": null,
"e": 36819,
"s": 36812,
"text": "Amazon"
},
{
"code": null,
"e": 36833,
"s": 36819,
"text": "binary-string"
},
{
"code": null,
"e": 36840,
"s": 36833,
"text": "Arrays"
},
{
"code": null,
"e": 36853,
"s": 36840,
"text": "Mathematical"
},
{
"code": null,
"e": 36860,
"s": 36853,
"text": "Amazon"
},
{
"code": null,
"e": 36867,
"s": 36860,
"text": "Arrays"
},
{
"code": null,
"e": 36880,
"s": 36867,
"text": "Mathematical"
},
{
"code": null,
"e": 36978,
"s": 36880,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36987,
"s": 36978,
"text": "Comments"
},
{
"code": null,
"e": 37000,
"s": 36987,
"text": "Old Comments"
},
{
"code": null,
"e": 37048,
"s": 37000,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 37092,
"s": 37048,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 37115,
"s": 37092,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 37147,
"s": 37115,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37161,
"s": 37147,
"text": "Linear Search"
},
{
"code": null,
"e": 37191,
"s": 37161,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 37251,
"s": 37191,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37266,
"s": 37251,
"text": "C++ Data Types"
},
{
"code": null,
"e": 37309,
"s": 37266,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Method overriding in Java
|
Overriding is the ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.
In object-oriented terms, overriding means to override the functionality of an existing method.
Let us look at an example.
Live Demo
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}
This will produce the following result −
Animals can move
Dogs can walk and run
In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: At compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object.
|
[
{
"code": null,
"e": 1232,
"s": 1062,
"text": "Overriding is the ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement."
},
{
"code": null,
"e": 1328,
"s": 1232,
"text": "In object-oriented terms, overriding means to override the functionality of an existing method."
},
{
"code": null,
"e": 1355,
"s": 1328,
"text": "Let us look at an example."
},
{
"code": null,
"e": 1365,
"s": 1355,
"text": "Live Demo"
},
{
"code": null,
"e": 1866,
"s": 1365,
"text": "class Animal {\n public void move() {\n System.out.println(\"Animals can move\");\n }\n}\nclass Dog extends Animal {\n public void move() {\n System.out.println(\"Dogs can walk and run\");\n }\n}\npublic class TestDog {\n public static void main(String args[]) {\n Animal a = new Animal(); // Animal reference and object\n Animal b = new Dog(); // Animal reference but Dog object\n a.move(); // runs the method in Animal class\n b.move(); // runs the method in Dog class\n }\n}"
},
{
"code": null,
"e": 1907,
"s": 1866,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 1946,
"s": 1907,
"text": "Animals can move\nDogs can walk and run"
},
{
"code": null,
"e": 2438,
"s": 1946,
"text": "In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: At compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object."
}
] |
C library macro - offsetof()
|
The C library macro offsetof(type, member-designator) results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type.
Following is the declaration for offsetof() Macro.
offsetof(type, member-designator)
type − This is the class type in which member-designator is a valid member designator.
type − This is the class type in which member-designator is a valid member designator.
member-designator − This is the member designator of class type.
member-designator − This is the member designator of class type.
This macro returns the value of type size_t which is the offset value of member in type.
The following example shows the usage of offsetof() Macro.
#include <stddef.h>
#include <stdio.h>
struct address {
char name[50];
char street[50];
int phone;
};
int main () {
printf("name offset = %d byte in address structure.\n",
offsetof(struct address, name));
printf("street offset = %d byte in address structure.\n",
offsetof(struct address, street));
printf("phone offset = %d byte in address structure.\n",
offsetof(struct address, phone));
return(0);
}
Let us compile and run the above program, this will produce the following result −
name offset = 0 byte in address structure.
street offset = 50 byte in address structure.
phone offset = 100 byte in address structure.
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": 2284,
"s": 2007,
"text": "The C library macro offsetof(type, member-designator) results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type."
},
{
"code": null,
"e": 2335,
"s": 2284,
"text": "Following is the declaration for offsetof() Macro."
},
{
"code": null,
"e": 2369,
"s": 2335,
"text": "offsetof(type, member-designator)"
},
{
"code": null,
"e": 2456,
"s": 2369,
"text": "type − This is the class type in which member-designator is a valid member designator."
},
{
"code": null,
"e": 2543,
"s": 2456,
"text": "type − This is the class type in which member-designator is a valid member designator."
},
{
"code": null,
"e": 2608,
"s": 2543,
"text": "member-designator − This is the member designator of class type."
},
{
"code": null,
"e": 2673,
"s": 2608,
"text": "member-designator − This is the member designator of class type."
},
{
"code": null,
"e": 2762,
"s": 2673,
"text": "This macro returns the value of type size_t which is the offset value of member in type."
},
{
"code": null,
"e": 2821,
"s": 2762,
"text": "The following example shows the usage of offsetof() Macro."
},
{
"code": null,
"e": 3262,
"s": 2821,
"text": "#include <stddef.h>\n#include <stdio.h>\n\nstruct address {\n char name[50];\n char street[50];\n int phone;\n};\n \nint main () {\n printf(\"name offset = %d byte in address structure.\\n\",\n offsetof(struct address, name));\n\n printf(\"street offset = %d byte in address structure.\\n\",\n offsetof(struct address, street));\n\n printf(\"phone offset = %d byte in address structure.\\n\",\n offsetof(struct address, phone));\n\n return(0);\n} "
},
{
"code": null,
"e": 3345,
"s": 3262,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3481,
"s": 3345,
"text": "name offset = 0 byte in address structure.\nstreet offset = 50 byte in address structure.\nphone offset = 100 byte in address structure.\n"
},
{
"code": null,
"e": 3514,
"s": 3481,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3529,
"s": 3514,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3564,
"s": 3529,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3579,
"s": 3564,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3614,
"s": 3579,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3628,
"s": 3614,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3661,
"s": 3628,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3679,
"s": 3661,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3714,
"s": 3679,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3733,
"s": 3714,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3766,
"s": 3733,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3778,
"s": 3766,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3785,
"s": 3778,
"text": " Print"
},
{
"code": null,
"e": 3796,
"s": 3785,
"text": " Add Notes"
}
] |
How to retrieve the content of the file in PowerShell?
|
To retrieve the content of the file in PowerShell, you need to use Get-Content cmdlet. For example, we are going to retrieve the content of the text file called Aliases.txt from a specific location.
Get-Content D:\Temp\aliases.txt
PS C:\WINDOWS\system32> Get-Content D:\Temp\aliases.txt
# Alias File
# Exported by : admin
# Date/Time : 26 January 2020 19:20:24
# Computer : DESKTOP-9435KM9
"foreach","ForEach-Object","","ReadOnly, AllScope"
"%","ForEach-Object","","ReadOnly, AllScope"
"where","Where-Object","","ReadOnly, AllScope"
"?","Where-Object","","ReadOnly, AllScope"
"ac","Add-Content","","ReadOnly, AllScope"
"clc","Clear-Content","","ReadOnly, AllScope"
"cli","Clear-Item","","ReadOnly, AllScope"
"clp","Clear-ItemProperty","","ReadOnly, AllScope"
"clv","Clear-Variable","","ReadOnly, AllScope"
"compare","Compare-Object","","ReadOnly, AllScope"
"cpi","Copy-Item","","ReadOnly, AllScope"
"cpp","Copy-ItemProperty","","ReadOnly, AllScope"
"cvpa","Convert-Path","","ReadOnly, AllScope"
"dbp","Disable-PSBreakpoint","","ReadOnly, AllScope"
"diff","Compare-Object","","ReadOnly, AllScope"
"ebp","Enable-PSBreakpoint","","ReadOnly, AllScope"
"epal","Export-Alias","","ReadOnly, AllScope"
"epcsv","Export-Csv","","ReadOnly, AllScope"
"fc","Format-Custom","","ReadOnly, AllScope"
"fl","Format-List","","ReadOnly, AllScope"
"ft","Format-Table","","ReadOnly, AllScope"
"fw","Format-Wide","","ReadOnly, AllScope"
"gal","Get-Alias","","ReadOnly, AllScope"
"gbp","Get-PSBreakpoint","","ReadOnly, AllScope"
"gc","Get-Content","","ReadOnly, AllScope"
You can also retrieve the content of the file from the remote location.
For example,
Get-Content \\Test-PC\Shared\Powershellaliases.txt
|
[
{
"code": null,
"e": 1261,
"s": 1062,
"text": "To retrieve the content of the file in PowerShell, you need to use Get-Content cmdlet. For example, we are going to retrieve the content of the text file called Aliases.txt from a specific location."
},
{
"code": null,
"e": 1293,
"s": 1261,
"text": "Get-Content D:\\Temp\\aliases.txt"
},
{
"code": null,
"e": 2610,
"s": 1293,
"text": "PS C:\\WINDOWS\\system32> Get-Content D:\\Temp\\aliases.txt\n# Alias File\n# Exported by : admin\n# Date/Time : 26 January 2020 19:20:24\n# Computer : DESKTOP-9435KM9\n\"foreach\",\"ForEach-Object\",\"\",\"ReadOnly, AllScope\"\n\"%\",\"ForEach-Object\",\"\",\"ReadOnly, AllScope\"\n\"where\",\"Where-Object\",\"\",\"ReadOnly, AllScope\"\n\"?\",\"Where-Object\",\"\",\"ReadOnly, AllScope\"\n\"ac\",\"Add-Content\",\"\",\"ReadOnly, AllScope\"\n\"clc\",\"Clear-Content\",\"\",\"ReadOnly, AllScope\"\n\"cli\",\"Clear-Item\",\"\",\"ReadOnly, AllScope\"\n\"clp\",\"Clear-ItemProperty\",\"\",\"ReadOnly, AllScope\"\n\"clv\",\"Clear-Variable\",\"\",\"ReadOnly, AllScope\"\n\"compare\",\"Compare-Object\",\"\",\"ReadOnly, AllScope\"\n\"cpi\",\"Copy-Item\",\"\",\"ReadOnly, AllScope\"\n\"cpp\",\"Copy-ItemProperty\",\"\",\"ReadOnly, AllScope\"\n\"cvpa\",\"Convert-Path\",\"\",\"ReadOnly, AllScope\"\n\"dbp\",\"Disable-PSBreakpoint\",\"\",\"ReadOnly, AllScope\"\n\"diff\",\"Compare-Object\",\"\",\"ReadOnly, AllScope\"\n\"ebp\",\"Enable-PSBreakpoint\",\"\",\"ReadOnly, AllScope\"\n\"epal\",\"Export-Alias\",\"\",\"ReadOnly, AllScope\"\n\"epcsv\",\"Export-Csv\",\"\",\"ReadOnly, AllScope\"\n\"fc\",\"Format-Custom\",\"\",\"ReadOnly, AllScope\"\n\"fl\",\"Format-List\",\"\",\"ReadOnly, AllScope\"\n\"ft\",\"Format-Table\",\"\",\"ReadOnly, AllScope\"\n\"fw\",\"Format-Wide\",\"\",\"ReadOnly, AllScope\"\n\"gal\",\"Get-Alias\",\"\",\"ReadOnly, AllScope\"\n\"gbp\",\"Get-PSBreakpoint\",\"\",\"ReadOnly, AllScope\"\n\"gc\",\"Get-Content\",\"\",\"ReadOnly, AllScope\""
},
{
"code": null,
"e": 2682,
"s": 2610,
"text": "You can also retrieve the content of the file from the remote location."
},
{
"code": null,
"e": 2695,
"s": 2682,
"text": "For example,"
},
{
"code": null,
"e": 2746,
"s": 2695,
"text": "Get-Content \\\\Test-PC\\Shared\\Powershellaliases.txt"
}
] |
Do Not Abuse Try Except In Python | by Christopher Tao | Towards Data Science
|
Like most other programming languages, Python supports catching and handling exceptions during runtime. However, sometimes I found that it has been overused.
It turns out that some developers, especially those who are newbies in Python, tend to use try ... except ... a lot, once they found such a feature. However, I would say that we should try to avoid using that if possible, especially during the early stage of development. You will find that it is better to let the problem reveal, rather than hide it.
In this article, I will demonstrate some examples to show how “try ... except ...” can create problems and what is the better manner in Python programming.
Let’s start with a problematic example, which is a very typical scenario that I have seen.
def f1(num): try: return (num+1)*2 except Exception as e: print('Error: ', e)def f2(num): try: return (num+1)*3 except Exception as e: print('Error: ', e)def f3(num): try: return (num+1)*4 except Exception as e: print('Error: ', e)
We have three functions that do some simple numerical calculations. All of them are implemented with try ... except ... with everything. Then, we want to use them in our code as follows.
num1 = f1(5)num2 = f2('5')num3 = f3(5)
Please note that I deliberately pass a string “5” in the second function, because I just want to create an exception artificially. The result we have is as follows.
Well, here we have only a few lines of code. It is not too difficult to realise the problem, perhaps. However, imagine that you are doing a project that has a much larger scale, the error message must be str, not int will not be very helpful for you to locate the problem.
The error message we can get from the exception object e is sometimes very limited. I would say that it does not always make sense in Python. In fact, the previous one is not too bad because at least it tells you why the error happened. Let’s see this one.
def f4(key): try: d = {'a': 1, 'b': 2} return d[key] except Exception as e: print('Error: ', e)f4('c')
Of course, in this example we have only one line of code, we know what is the “c”. However, again, if this happens in a project, how could we troubleshoot the problem if we were only given an error message “c”?
Can you imagine that the case can be worse? Well, this one might not be 100% related to our topic, but I just want to present it because it can be potentially solved by the solutions in the later section.
Do you think it gonna be very safe if we put all of the code in the try block and catch all the generic exceptions in the except block? The answer is no. Otherwise, I will probably recommend using it everywhere :)
Let’s see this example.
def f5(num): try: return num*3 except Exception as e: print('Error: ', e)num = f5('5')print('Result is', num)
Again, we define a very simple numerical computing function and pass a string into it. We might expect that the “exception” will be caught, but there is no exception.
Python is too flexible to have an error :)
If you want to try all your code and catch the exceptions, you can use the traceback library which is built-in Python. Let’s use the same examples as above shown.
import tracebackdef f4(key): try: d = {'a': 1, 'b': 2} return d[key] except Exception as e: e = traceback.format_exc() print('Error: ', e)f4('c')
Using traceback helped us to print more information about the error, so it will be easier for us to troubleshoot the problem. However, we need to import an extra library and write more code to do this.
Just need to think twice about whether it is worth doing this? Let’s see some other good manners.
This section is added just in case someone will say something like:
why use raise or assert? The full traceback stack will be simply displayed if you don’t use try ... except ... at all!
Indeed, this is what I want to say in this article. It is exactly the solution to the title “Do not abuse try ... except ... in Python”. The reason that I provide the two “solutions” below is just want to demonstrate what is the good manner.
As I said earlier, we should avoid using too much try ... except ... which can hide the exceptions. In contrast, we would like to have the exception reveal as much as possible. Using raise to manually raise an exception is one of a good manner.
Let’s modify our f1, f2 and f3 functions.
INVALID_NUM_EXCEPTION = Exception('The parameter must be integer!')def f1(num): if type(num) != int: raise INVALID_NUM_EXCEPTION return (num+1)*2def f2(num): if type(num) != int: raise INVALID_NUM_EXCEPTION return (num+1)*2def f3(num): if type(num) != int: raise INVALID_NUM_EXCEPTION return (num+1)*2
Here, we defined an exception and raise it in the functions when the type of arguments passed in are not an integer.
Then, let’s run the same code to use these functions.
num1 = f1(5)num2 = f2('5')num3 = f3(5)
It is not too bad to meet an error if it tells you what is the error exactly and where did that happen.
Although assertion is more often used in testing, we can still use it during development to make sure that our code has fewer bugs. Also, it is usually kind of neat to use assertion than raising an exception, if we don’t care what’s the exact exception type.
INVALID_NUM_MSG = 'The parameter must be integer!'def f1(num): assert isinstance(num, int), INVALID_NUM_MSG return (num+1)*2def f2(num): assert isinstance(num, int), INVALID_NUM_MSG return (num+1)*2def f3(num): assert isinstance(num, int), INVALID_NUM_MSG return (num+1)*2
It is good to know more tricks in a programming language. I have to say that whenever I know something cool, I would also tend to use it. However, it also needs to think twice whether we need to do this and if that trick gives us more benefit than barriers.
Therefore, do not put all your code in the try ... except ... block in Python. Let the error reveal and make our life easier!
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
|
[
{
"code": null,
"e": 330,
"s": 172,
"text": "Like most other programming languages, Python supports catching and handling exceptions during runtime. However, sometimes I found that it has been overused."
},
{
"code": null,
"e": 682,
"s": 330,
"text": "It turns out that some developers, especially those who are newbies in Python, tend to use try ... except ... a lot, once they found such a feature. However, I would say that we should try to avoid using that if possible, especially during the early stage of development. You will find that it is better to let the problem reveal, rather than hide it."
},
{
"code": null,
"e": 838,
"s": 682,
"text": "In this article, I will demonstrate some examples to show how “try ... except ...” can create problems and what is the better manner in Python programming."
},
{
"code": null,
"e": 929,
"s": 838,
"text": "Let’s start with a problematic example, which is a very typical scenario that I have seen."
},
{
"code": null,
"e": 1221,
"s": 929,
"text": "def f1(num): try: return (num+1)*2 except Exception as e: print('Error: ', e)def f2(num): try: return (num+1)*3 except Exception as e: print('Error: ', e)def f3(num): try: return (num+1)*4 except Exception as e: print('Error: ', e)"
},
{
"code": null,
"e": 1408,
"s": 1221,
"text": "We have three functions that do some simple numerical calculations. All of them are implemented with try ... except ... with everything. Then, we want to use them in our code as follows."
},
{
"code": null,
"e": 1447,
"s": 1408,
"text": "num1 = f1(5)num2 = f2('5')num3 = f3(5)"
},
{
"code": null,
"e": 1612,
"s": 1447,
"text": "Please note that I deliberately pass a string “5” in the second function, because I just want to create an exception artificially. The result we have is as follows."
},
{
"code": null,
"e": 1885,
"s": 1612,
"text": "Well, here we have only a few lines of code. It is not too difficult to realise the problem, perhaps. However, imagine that you are doing a project that has a much larger scale, the error message must be str, not int will not be very helpful for you to locate the problem."
},
{
"code": null,
"e": 2142,
"s": 1885,
"text": "The error message we can get from the exception object e is sometimes very limited. I would say that it does not always make sense in Python. In fact, the previous one is not too bad because at least it tells you why the error happened. Let’s see this one."
},
{
"code": null,
"e": 2272,
"s": 2142,
"text": "def f4(key): try: d = {'a': 1, 'b': 2} return d[key] except Exception as e: print('Error: ', e)f4('c')"
},
{
"code": null,
"e": 2483,
"s": 2272,
"text": "Of course, in this example we have only one line of code, we know what is the “c”. However, again, if this happens in a project, how could we troubleshoot the problem if we were only given an error message “c”?"
},
{
"code": null,
"e": 2688,
"s": 2483,
"text": "Can you imagine that the case can be worse? Well, this one might not be 100% related to our topic, but I just want to present it because it can be potentially solved by the solutions in the later section."
},
{
"code": null,
"e": 2902,
"s": 2688,
"text": "Do you think it gonna be very safe if we put all of the code in the try block and catch all the generic exceptions in the except block? The answer is no. Otherwise, I will probably recommend using it everywhere :)"
},
{
"code": null,
"e": 2926,
"s": 2902,
"text": "Let’s see this example."
},
{
"code": null,
"e": 3056,
"s": 2926,
"text": "def f5(num): try: return num*3 except Exception as e: print('Error: ', e)num = f5('5')print('Result is', num)"
},
{
"code": null,
"e": 3223,
"s": 3056,
"text": "Again, we define a very simple numerical computing function and pass a string into it. We might expect that the “exception” will be caught, but there is no exception."
},
{
"code": null,
"e": 3266,
"s": 3223,
"text": "Python is too flexible to have an error :)"
},
{
"code": null,
"e": 3429,
"s": 3266,
"text": "If you want to try all your code and catch the exceptions, you can use the traceback library which is built-in Python. Let’s use the same examples as above shown."
},
{
"code": null,
"e": 3609,
"s": 3429,
"text": "import tracebackdef f4(key): try: d = {'a': 1, 'b': 2} return d[key] except Exception as e: e = traceback.format_exc() print('Error: ', e)f4('c')"
},
{
"code": null,
"e": 3811,
"s": 3609,
"text": "Using traceback helped us to print more information about the error, so it will be easier for us to troubleshoot the problem. However, we need to import an extra library and write more code to do this."
},
{
"code": null,
"e": 3909,
"s": 3811,
"text": "Just need to think twice about whether it is worth doing this? Let’s see some other good manners."
},
{
"code": null,
"e": 3977,
"s": 3909,
"text": "This section is added just in case someone will say something like:"
},
{
"code": null,
"e": 4096,
"s": 3977,
"text": "why use raise or assert? The full traceback stack will be simply displayed if you don’t use try ... except ... at all!"
},
{
"code": null,
"e": 4338,
"s": 4096,
"text": "Indeed, this is what I want to say in this article. It is exactly the solution to the title “Do not abuse try ... except ... in Python”. The reason that I provide the two “solutions” below is just want to demonstrate what is the good manner."
},
{
"code": null,
"e": 4583,
"s": 4338,
"text": "As I said earlier, we should avoid using too much try ... except ... which can hide the exceptions. In contrast, we would like to have the exception reveal as much as possible. Using raise to manually raise an exception is one of a good manner."
},
{
"code": null,
"e": 4625,
"s": 4583,
"text": "Let’s modify our f1, f2 and f3 functions."
},
{
"code": null,
"e": 4966,
"s": 4625,
"text": "INVALID_NUM_EXCEPTION = Exception('The parameter must be integer!')def f1(num): if type(num) != int: raise INVALID_NUM_EXCEPTION return (num+1)*2def f2(num): if type(num) != int: raise INVALID_NUM_EXCEPTION return (num+1)*2def f3(num): if type(num) != int: raise INVALID_NUM_EXCEPTION return (num+1)*2"
},
{
"code": null,
"e": 5083,
"s": 4966,
"text": "Here, we defined an exception and raise it in the functions when the type of arguments passed in are not an integer."
},
{
"code": null,
"e": 5137,
"s": 5083,
"text": "Then, let’s run the same code to use these functions."
},
{
"code": null,
"e": 5176,
"s": 5137,
"text": "num1 = f1(5)num2 = f2('5')num3 = f3(5)"
},
{
"code": null,
"e": 5280,
"s": 5176,
"text": "It is not too bad to meet an error if it tells you what is the error exactly and where did that happen."
},
{
"code": null,
"e": 5539,
"s": 5280,
"text": "Although assertion is more often used in testing, we can still use it during development to make sure that our code has fewer bugs. Also, it is usually kind of neat to use assertion than raising an exception, if we don’t care what’s the exact exception type."
},
{
"code": null,
"e": 5830,
"s": 5539,
"text": "INVALID_NUM_MSG = 'The parameter must be integer!'def f1(num): assert isinstance(num, int), INVALID_NUM_MSG return (num+1)*2def f2(num): assert isinstance(num, int), INVALID_NUM_MSG return (num+1)*2def f3(num): assert isinstance(num, int), INVALID_NUM_MSG return (num+1)*2"
},
{
"code": null,
"e": 6088,
"s": 5830,
"text": "It is good to know more tricks in a programming language. I have to say that whenever I know something cool, I would also tend to use it. However, it also needs to think twice whether we need to do this and if that trick gives us more benefit than barriers."
},
{
"code": null,
"e": 6214,
"s": 6088,
"text": "Therefore, do not put all your code in the try ... except ... block in Python. Let the error reveal and make our life easier!"
},
{
"code": null,
"e": 6225,
"s": 6214,
"text": "medium.com"
}
] |
Dimensionality Reduction Approaches | by Prerna Singh | Towards Data Science
|
The full explosion of big data has persuaded us that there is more to it. While it is true, of course, that a large amount of training data allows the machine learning model to learn more rules and generalize better to new data, it is also true that an indiscriminate introduction of low-quality data and input features may introduce too much noise and at the same time slow down the training considerably. And, in the presence of a dataset with a very large number of columns of data, it is good practice to look at how many of these data features are really useful for the model.
In machine learning, we tend to add as many features as possible at first, to grab useful indicators and get a more accurate result. Nevertheless, the model’s output will decrease after a certain level, with the rising number of elements. This phenomenon is often called the “Curse of Dimensionality.”
The curse of dimensionality exists because the density of the sample decreases exponentially as the dimensionality increases. If we continue to add features without also increasing the number of training samples, the dimensionality of the feature space will expand and become sparser and sparser. Because of this sparsity, it becomes much simpler for the machine learning model to find the right solution which is highly likely to lead to overfitting. Overfitting occurs when the model is too close to a particular set of data and is not generalizing well.
However, can we overcome the curse of dimensionality and avoid overfitting particularly when we have a lot of features and relatively few samples of training? One common approach is that of reducing dimensionality in feature space. Reduction of dimensionality is the method of reducing with consideration the dimensionality of the function space by obtaining a collection of principal features. Reduction of the dimensionality can be further divided into a collection of features and extraction of features.
The selection of features tries to pick a subset of the original features to be used in the machine learning model. In this way, we could delete redundant and obsolete characteristics without incurring much information loss. The extraction of a feature is also called the projection of a feature. Although the selection of features returns a subset of the original features, the extraction of features creates new features by projecting the data to a space of lesser dimensions in the high-dimensional space. Informative and non-redundant functionality can also be extracted from this method.
We can use the selection of features and extraction of features together. In addition to reducing overfitting and redundancy, the reduction in dimensionality also leads to better human interpretations and lower computational costs with model simplification.
It reduces the time and storage space required.The removal of multicollinearity improves the interpretation of the parameters of the machine learning model.It becomes easier to visualize the data when reduced to very low dimensions such as 2D or 3D.Reduce space complexity.More interpretable because it removes noise thus provides a simpler explanation.To mitigate “curse of dimensionality”.
It reduces the time and storage space required.
The removal of multicollinearity improves the interpretation of the parameters of the machine learning model.
It becomes easier to visualize the data when reduced to very low dimensions such as 2D or 3D.
Reduce space complexity.
More interpretable because it removes noise thus provides a simpler explanation.
To mitigate “curse of dimensionality”.
We discussed the benefits of dimension reduction and provided an overview of dimension reduction requirements. We will now discuss in detail the two key techniques for dimension reduction i.e.
PCA (Principal Component Analysis)LDA (Linear Discriminant Analysis)
PCA (Principal Component Analysis)
LDA (Linear Discriminant Analysis)
For example, references, Wine dataset from the UCI Machine Learning Repository would be used. This dataset, which is fairly small, has six target class and eleven-dimensional feature set (i.e. eleven different features like fixed acidity, pH value, alcohol content, and so on to predict the quality of wine).
Datasets can be downloaded following the link below.https://github.com/psi49/Revisiting_MachineLearning/blob/master/winequality_red.csv
Principal Component Analysis (PCA) is an unsupervised learning algorithm as it ignores the class labels (the so-called principal components) that maximize the variance in a dataset, to find the directions. In other words, PCA is basically a summarization of data. For example, to obtain quality/type of wine, we can use different features of wine such as its pH value, alcohol content, the color of the wine, acidity content and so on, however, many of these features will be redundant or dummy feature variables (can be derived from other features), therefore causing to train the model on unnecessary features. In short, we can get the type of wine with fewer feature variables and this is what actually PCA does inside the box.
Note that, PCA does not select a set of features and discard other features, but it infers some new features, which best describe the type of class (in our case — type of wine) from the existing features.
Previously, while deriving a formal definition, we came up with a phrase — maximize the variance in a dataset. Now the question arises — what the word ‘variance’ has to do with PCA? Remember, our main task is to define a feature set that distinguishes one type of wine from another. Imagine that you land up with a set of features that are unable to distinguish the types of wine, therefore, these sets of features are useless. This type of dimensionality reduction will deteriorate your model accuracy and, in cases will lead to under-fitting of data. Therefore, PCA looks for properties that show as much variation across datasets as possible.
PCA works on eigenvectors and eigenvalues of the covariance matrix, which is the equivalent of fitting those straight, principal-component lines to the variance of the data. Why? Because PCA determines the lines of variance in the dataset which are called principal components with the first principal component having the maximum variance, the second principal component having a second maximum variance, and so on.
Now let’s jump to the implementation of PCA using sklearn on the example of the wine dataset and understand how the data is transformed from a higher dimensionality to lower dimensionality.
Let’s perform the PCA on wine dataset and analyze by visual representation:
import numpy as npimport pandas as pddf=pd.read_csv(‘winequality_red.csv’)def isQuality(quality):if quality > 6: return 1if (quality >= 5) and (quality <= 6): return 2else: return 0
The given data has six different quality types. For the sake of understanding the dimensionality reduction concept. The quality of the wine is grouped into three target classes if you like you can work on six target classes as well.
Lets used the above function to convert into three wine quality classes.
df[‘isQuality’] = df[‘quality’].apply(isQuality)print(‘New classes are defined for the quality of wines:\n’,df[‘isQuality’].value_counts())
New classes are defined for the quality of wines:
Class 2:1319
Class 1: 217
Class 0: 63
Drop the quality column from the dataset as we have created a new column with three wine quality classes.
df=df.drop(‘quality’, axis=1)
Divide data into features and target class.
feature=df.iloc[:,0:11]target=df[‘isQuality’]print(feature.shape)print(target.shape)
The shape of the features and target column.
(1599, 11)
(1599,1)
Split the data into train and test using train_test_split function from sklearn.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(feature, target, test_size = 0.2, random_state = 42)
Scaling the Dataset
Scaling the dataset — Can use min-max normalization for scaling the dataset with mean zero and a unit standard deviation.
This estimator scales and translates each feature individually such that it is in the given range on the dataset set, e.g. between zero and one.
from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()X_train=scaler.fit(X_train).transform(X_train)X_test=scaler.fit(X_test).transform(X_test)
Apply PCA with inbuilt PCA function in sklearn:
from sklearn.decomposition import PCApca = PCA(n_components=2)X_train = pca.fit(X_train).transform(X_train)X_test= pca.fit(X_test).transform(X_test)
Here, the feature is the training dataset and n_component is the number of PCA components we want to derive from our existing feature set.
So using the sklearn, PCA is like a black box (explained above), you give a scaled feature set as an input to sklearn PCA and get PCA components as output which can be used as an input to data training algorithms. For the PCA algorithm, it is necessary to perform data scaling before we find principal components.
Training the Algorithm
Here we will train principal components using a simple Logistic Regression tool to solve this classification problem. To do so, execute the following code:
from sklearn.linear_model import LogisticRegressionclf = LogisticRegression(random_state = 0)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)# Predicting the test set result using. Predict function under Random Forest Classifiery_pred = clf.predict(X_test)
Evaluating the Algorithm
For classification problems, the metrics used to evaluate an algorithm are accuracy, confusion matrix, precision, recall, and F1 values. Execute the following script to find these values:
from sklearn.metrics import classification_report, confusion_matrix, accuracy_scoreprint(confusion_matrix(y_test,y_pred))print(classification_report(y_test,y_pred))print(accuracy_score(y_test, y_pred))
The output will look something like this:
84.06% of accuracy we have achieved only using two feature sets out of eleven features in the original dataset. I would not consider this too bad. Further model accuracy can be improved using hyperparameter optimization of the logistic regression model or using some other models from the sklearn library. Try training model for more than 2 and less than 6 principal components. That would be a fun exercise to play around with PCA.
Here we will plot two graphs one by considering only two columns out of eleven columns and the second graph we will plot for principal components to understand how PCA makes visualization easy for high dimensional data.
import seaborn as snsimport matplotlib.pyplot as pltsns.set(rc={‘figure.figsize’:(12,7)})sns.scatterplot(x=”free sulfur dioxide”, y=”total sulfur dioxide”, hue=”isQuality”,data=df,palette=”Set1")plt.show()
sns.scatterplot(pca_df[:,0],pca_df[:,1], hue=”isQuality”,data=df, palette=”Set1")plt.show()
The graph above shows the plotting of data points using two features vs. Plotting of data points using principal components (which is basically a summarization of all the features in our dataset) i.e. PCA_1 and PCA_. This helps us to identify one more use of PCA i.e. proper and separable visualization of our dataset along with their “Quality” class tags. If you look at the graph, you can visualize the whole dataset properly with only two feature variables as compared to having thirteen feature variables. Though they do not differentiate well among (As see between sulfur dioxide and total sulfur dioxide) the wine quality classes but helps in reducing the feature set with minimal loss of information.
So far, we have made a pretty good understanding of PCA with some hands-on examples. We have seen how few components are sufficient to train models and also PCA is a great tool to reduce data dimension and give us the power to visualize data properly.
Let’s move forward and dive into one more tool for dimension reduction “Linear Discriminant Analysis”. I will be using the same wine dataset to provide hands-on experience.
Linear Discriminants is a statistical method of dimensionality reduction that provides the highest possible discrimination among various classes, used in machine learning to find the linear combination of features, which can separate two or more classes of objects with the best performance. The method is based on discriminant functions that are estimated based on a set of data called a training set. These discriminant functions are linear with respect to the characteristic vector.
The aim of LDA is to maximize the between-class variance and minimize the within-class variance, through a linear discriminant function, under the assumption that data in every class are described by a Gaussian probability density function with the same covariance.
It is good to understand the mathematics behind the LDA but I would not like to overwhelm anyone. We will understand by keeping things simple so it will be easy to follow for anyone.
LDA helps you find the boundaries of class clusters. This projects your data points on a line in order to differentiate the clusters as much as possible, with each cluster having a relatively close distance to a centroid.
So, the question arises-how are these clusters identified and how do we get LDA’s reduced feature set?
Basically, LDA considers a centroid of data points for each class. For example, with eleven different features, LDA will use the eleven different feature datasets to find the centroid of each of its classes. Depending on this, it now defines a new dimension which is nothing more than an axis that should fulfill two requirements.
Maximize the distance between each class ‘Centroid.Minimize the variance within each group (which LDA calls scatter, and is represented by s2).
Maximize the distance between each class ‘Centroid.
Minimize the variance within each group (which LDA calls scatter, and is represented by s2).
Hence the essence is (mean_a — mean_b)/(S_a — S_b)
(mean_a — mean_b) = ideally large (S_a — S_b) = ideally small
Here mean is nothing more than the class centroid. Variance is nothing but the spread of data across the plane. So, if the data variance is small then there will be less overlapping between the classes and the overall distinction between the different classes will be preserved.
So whatever coordinate of the new axis meets these two conditions, they form the new dataset dimension.
Now let’s jump to implementing LDA using sklearn on wine dataset and see how the data transitions from a higher dimensionality to a lower dimensionality.
Let’s perform the LDA on wine dataset and analyze graphically:
All the necessary libraries are already imported let’s import LDA with inbuilt LDA function in sklearn.
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDAlda = LDA(n_components=2)lda_df = lda.fit(feature, target).transform(feature)sns.scatterplot(lda_df[:,0],lda_df[:,1], hue=”isQuality”,data=df, palette=”Set1")plt.show()
Note: I wanted to clarify that feature scaling such as (standardization) does not change the overall results of an LDA and thus may be optional.
In the PCA graph, you can visualize the whole dataset properly differentiate well among the classes. Whereas in the LDA graph the classes are not clearly separable due to the uneven distribution of classes. This is the major difference between PCA and LDA.
To summarize, PCA performs better in situations where there are fewer samples per class. In this wine dataset, we have high counts of class 2 (1319) followed by class 1 (217) and lastly class 0 (63).
Although LDA works better with a large multi-class dataset where class separability is an important factor while reducing dimensionality.
The general LDA approach is very similar to a Principal Component Analysis, but in addition to finding the component axes that maximize the variance of our data (PCA), we are additionally interested in the axes that maximize the separation between multiple classes (LDA).
Finally, let’s see how we can choose the number of n_components in dimensionality reduction methods within sklearn. The simple approach is to use explained_variance_ratio_ and plot the graph to see how many components we need to retain variance by the new feature set. Let’s understand by doing this
scaler_df=scaler.fit(df).transform(df)pca = PCA().fit(scaler_df)plt.figure()plt.plot(np.cumsum(pca.explained_variance_ratio_))plt.xlabel(‘Number of n_Components’)plt.ylabel(‘Variance (%)’) #for each component present in the datasetplt.title(‘Wine Dataset Explained Variance’)plt.show()plt.ylabel(‘Variance (%)’) #for each component present in the datasetplt.title(‘Wine Dataset Explained Variance’)plt.show()
This plot tells us that selecting 8 components we can preserve something more than 90 % of the total variance of the wine data. It makes sense, we’ll not use 100% of our variance, because it denotes all components, and we want only the principal ones.
Now by using n_components=8 we can perform the same analysis and train any model. It is worth playing around. Higher-level Python libraries for machine learning actually made learning pretty easy, unlike earlier days when we have to hard code everything from scratch.
|
[
{
"code": null,
"e": 754,
"s": 172,
"text": "The full explosion of big data has persuaded us that there is more to it. While it is true, of course, that a large amount of training data allows the machine learning model to learn more rules and generalize better to new data, it is also true that an indiscriminate introduction of low-quality data and input features may introduce too much noise and at the same time slow down the training considerably. And, in the presence of a dataset with a very large number of columns of data, it is good practice to look at how many of these data features are really useful for the model."
},
{
"code": null,
"e": 1056,
"s": 754,
"text": "In machine learning, we tend to add as many features as possible at first, to grab useful indicators and get a more accurate result. Nevertheless, the model’s output will decrease after a certain level, with the rising number of elements. This phenomenon is often called the “Curse of Dimensionality.”"
},
{
"code": null,
"e": 1613,
"s": 1056,
"text": "The curse of dimensionality exists because the density of the sample decreases exponentially as the dimensionality increases. If we continue to add features without also increasing the number of training samples, the dimensionality of the feature space will expand and become sparser and sparser. Because of this sparsity, it becomes much simpler for the machine learning model to find the right solution which is highly likely to lead to overfitting. Overfitting occurs when the model is too close to a particular set of data and is not generalizing well."
},
{
"code": null,
"e": 2121,
"s": 1613,
"text": "However, can we overcome the curse of dimensionality and avoid overfitting particularly when we have a lot of features and relatively few samples of training? One common approach is that of reducing dimensionality in feature space. Reduction of dimensionality is the method of reducing with consideration the dimensionality of the function space by obtaining a collection of principal features. Reduction of the dimensionality can be further divided into a collection of features and extraction of features."
},
{
"code": null,
"e": 2714,
"s": 2121,
"text": "The selection of features tries to pick a subset of the original features to be used in the machine learning model. In this way, we could delete redundant and obsolete characteristics without incurring much information loss. The extraction of a feature is also called the projection of a feature. Although the selection of features returns a subset of the original features, the extraction of features creates new features by projecting the data to a space of lesser dimensions in the high-dimensional space. Informative and non-redundant functionality can also be extracted from this method."
},
{
"code": null,
"e": 2972,
"s": 2714,
"text": "We can use the selection of features and extraction of features together. In addition to reducing overfitting and redundancy, the reduction in dimensionality also leads to better human interpretations and lower computational costs with model simplification."
},
{
"code": null,
"e": 3364,
"s": 2972,
"text": "It reduces the time and storage space required.The removal of multicollinearity improves the interpretation of the parameters of the machine learning model.It becomes easier to visualize the data when reduced to very low dimensions such as 2D or 3D.Reduce space complexity.More interpretable because it removes noise thus provides a simpler explanation.To mitigate “curse of dimensionality”."
},
{
"code": null,
"e": 3412,
"s": 3364,
"text": "It reduces the time and storage space required."
},
{
"code": null,
"e": 3522,
"s": 3412,
"text": "The removal of multicollinearity improves the interpretation of the parameters of the machine learning model."
},
{
"code": null,
"e": 3616,
"s": 3522,
"text": "It becomes easier to visualize the data when reduced to very low dimensions such as 2D or 3D."
},
{
"code": null,
"e": 3641,
"s": 3616,
"text": "Reduce space complexity."
},
{
"code": null,
"e": 3722,
"s": 3641,
"text": "More interpretable because it removes noise thus provides a simpler explanation."
},
{
"code": null,
"e": 3761,
"s": 3722,
"text": "To mitigate “curse of dimensionality”."
},
{
"code": null,
"e": 3954,
"s": 3761,
"text": "We discussed the benefits of dimension reduction and provided an overview of dimension reduction requirements. We will now discuss in detail the two key techniques for dimension reduction i.e."
},
{
"code": null,
"e": 4023,
"s": 3954,
"text": "PCA (Principal Component Analysis)LDA (Linear Discriminant Analysis)"
},
{
"code": null,
"e": 4058,
"s": 4023,
"text": "PCA (Principal Component Analysis)"
},
{
"code": null,
"e": 4093,
"s": 4058,
"text": "LDA (Linear Discriminant Analysis)"
},
{
"code": null,
"e": 4402,
"s": 4093,
"text": "For example, references, Wine dataset from the UCI Machine Learning Repository would be used. This dataset, which is fairly small, has six target class and eleven-dimensional feature set (i.e. eleven different features like fixed acidity, pH value, alcohol content, and so on to predict the quality of wine)."
},
{
"code": null,
"e": 4538,
"s": 4402,
"text": "Datasets can be downloaded following the link below.https://github.com/psi49/Revisiting_MachineLearning/blob/master/winequality_red.csv"
},
{
"code": null,
"e": 5269,
"s": 4538,
"text": "Principal Component Analysis (PCA) is an unsupervised learning algorithm as it ignores the class labels (the so-called principal components) that maximize the variance in a dataset, to find the directions. In other words, PCA is basically a summarization of data. For example, to obtain quality/type of wine, we can use different features of wine such as its pH value, alcohol content, the color of the wine, acidity content and so on, however, many of these features will be redundant or dummy feature variables (can be derived from other features), therefore causing to train the model on unnecessary features. In short, we can get the type of wine with fewer feature variables and this is what actually PCA does inside the box."
},
{
"code": null,
"e": 5474,
"s": 5269,
"text": "Note that, PCA does not select a set of features and discard other features, but it infers some new features, which best describe the type of class (in our case — type of wine) from the existing features."
},
{
"code": null,
"e": 6120,
"s": 5474,
"text": "Previously, while deriving a formal definition, we came up with a phrase — maximize the variance in a dataset. Now the question arises — what the word ‘variance’ has to do with PCA? Remember, our main task is to define a feature set that distinguishes one type of wine from another. Imagine that you land up with a set of features that are unable to distinguish the types of wine, therefore, these sets of features are useless. This type of dimensionality reduction will deteriorate your model accuracy and, in cases will lead to under-fitting of data. Therefore, PCA looks for properties that show as much variation across datasets as possible."
},
{
"code": null,
"e": 6537,
"s": 6120,
"text": "PCA works on eigenvectors and eigenvalues of the covariance matrix, which is the equivalent of fitting those straight, principal-component lines to the variance of the data. Why? Because PCA determines the lines of variance in the dataset which are called principal components with the first principal component having the maximum variance, the second principal component having a second maximum variance, and so on."
},
{
"code": null,
"e": 6727,
"s": 6537,
"text": "Now let’s jump to the implementation of PCA using sklearn on the example of the wine dataset and understand how the data is transformed from a higher dimensionality to lower dimensionality."
},
{
"code": null,
"e": 6803,
"s": 6727,
"text": "Let’s perform the PCA on wine dataset and analyze by visual representation:"
},
{
"code": null,
"e": 6995,
"s": 6803,
"text": "import numpy as npimport pandas as pddf=pd.read_csv(‘winequality_red.csv’)def isQuality(quality):if quality > 6: return 1if (quality >= 5) and (quality <= 6): return 2else: return 0"
},
{
"code": null,
"e": 7228,
"s": 6995,
"text": "The given data has six different quality types. For the sake of understanding the dimensionality reduction concept. The quality of the wine is grouped into three target classes if you like you can work on six target classes as well."
},
{
"code": null,
"e": 7301,
"s": 7228,
"text": "Lets used the above function to convert into three wine quality classes."
},
{
"code": null,
"e": 7441,
"s": 7301,
"text": "df[‘isQuality’] = df[‘quality’].apply(isQuality)print(‘New classes are defined for the quality of wines:\\n’,df[‘isQuality’].value_counts())"
},
{
"code": null,
"e": 7491,
"s": 7441,
"text": "New classes are defined for the quality of wines:"
},
{
"code": null,
"e": 7504,
"s": 7491,
"text": "Class 2:1319"
},
{
"code": null,
"e": 7517,
"s": 7504,
"text": "Class 1: 217"
},
{
"code": null,
"e": 7529,
"s": 7517,
"text": "Class 0: 63"
},
{
"code": null,
"e": 7635,
"s": 7529,
"text": "Drop the quality column from the dataset as we have created a new column with three wine quality classes."
},
{
"code": null,
"e": 7665,
"s": 7635,
"text": "df=df.drop(‘quality’, axis=1)"
},
{
"code": null,
"e": 7709,
"s": 7665,
"text": "Divide data into features and target class."
},
{
"code": null,
"e": 7794,
"s": 7709,
"text": "feature=df.iloc[:,0:11]target=df[‘isQuality’]print(feature.shape)print(target.shape)"
},
{
"code": null,
"e": 7839,
"s": 7794,
"text": "The shape of the features and target column."
},
{
"code": null,
"e": 7850,
"s": 7839,
"text": "(1599, 11)"
},
{
"code": null,
"e": 7859,
"s": 7850,
"text": "(1599,1)"
},
{
"code": null,
"e": 7940,
"s": 7859,
"text": "Split the data into train and test using train_test_split function from sklearn."
},
{
"code": null,
"e": 8097,
"s": 7940,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(feature, target, test_size = 0.2, random_state = 42)"
},
{
"code": null,
"e": 8117,
"s": 8097,
"text": "Scaling the Dataset"
},
{
"code": null,
"e": 8239,
"s": 8117,
"text": "Scaling the dataset — Can use min-max normalization for scaling the dataset with mean zero and a unit standard deviation."
},
{
"code": null,
"e": 8384,
"s": 8239,
"text": "This estimator scales and translates each feature individually such that it is in the given range on the dataset set, e.g. between zero and one."
},
{
"code": null,
"e": 8543,
"s": 8384,
"text": "from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()X_train=scaler.fit(X_train).transform(X_train)X_test=scaler.fit(X_test).transform(X_test)"
},
{
"code": null,
"e": 8591,
"s": 8543,
"text": "Apply PCA with inbuilt PCA function in sklearn:"
},
{
"code": null,
"e": 8740,
"s": 8591,
"text": "from sklearn.decomposition import PCApca = PCA(n_components=2)X_train = pca.fit(X_train).transform(X_train)X_test= pca.fit(X_test).transform(X_test)"
},
{
"code": null,
"e": 8879,
"s": 8740,
"text": "Here, the feature is the training dataset and n_component is the number of PCA components we want to derive from our existing feature set."
},
{
"code": null,
"e": 9193,
"s": 8879,
"text": "So using the sklearn, PCA is like a black box (explained above), you give a scaled feature set as an input to sklearn PCA and get PCA components as output which can be used as an input to data training algorithms. For the PCA algorithm, it is necessary to perform data scaling before we find principal components."
},
{
"code": null,
"e": 9216,
"s": 9193,
"text": "Training the Algorithm"
},
{
"code": null,
"e": 9372,
"s": 9216,
"text": "Here we will train principal components using a simple Logistic Regression tool to solve this classification problem. To do so, execute the following code:"
},
{
"code": null,
"e": 9634,
"s": 9372,
"text": "from sklearn.linear_model import LogisticRegressionclf = LogisticRegression(random_state = 0)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)# Predicting the test set result using. Predict function under Random Forest Classifiery_pred = clf.predict(X_test)"
},
{
"code": null,
"e": 9659,
"s": 9634,
"text": "Evaluating the Algorithm"
},
{
"code": null,
"e": 9847,
"s": 9659,
"text": "For classification problems, the metrics used to evaluate an algorithm are accuracy, confusion matrix, precision, recall, and F1 values. Execute the following script to find these values:"
},
{
"code": null,
"e": 10049,
"s": 9847,
"text": "from sklearn.metrics import classification_report, confusion_matrix, accuracy_scoreprint(confusion_matrix(y_test,y_pred))print(classification_report(y_test,y_pred))print(accuracy_score(y_test, y_pred))"
},
{
"code": null,
"e": 10091,
"s": 10049,
"text": "The output will look something like this:"
},
{
"code": null,
"e": 10524,
"s": 10091,
"text": "84.06% of accuracy we have achieved only using two feature sets out of eleven features in the original dataset. I would not consider this too bad. Further model accuracy can be improved using hyperparameter optimization of the logistic regression model or using some other models from the sklearn library. Try training model for more than 2 and less than 6 principal components. That would be a fun exercise to play around with PCA."
},
{
"code": null,
"e": 10744,
"s": 10524,
"text": "Here we will plot two graphs one by considering only two columns out of eleven columns and the second graph we will plot for principal components to understand how PCA makes visualization easy for high dimensional data."
},
{
"code": null,
"e": 10950,
"s": 10744,
"text": "import seaborn as snsimport matplotlib.pyplot as pltsns.set(rc={‘figure.figsize’:(12,7)})sns.scatterplot(x=”free sulfur dioxide”, y=”total sulfur dioxide”, hue=”isQuality”,data=df,palette=”Set1\")plt.show()"
},
{
"code": null,
"e": 11042,
"s": 10950,
"text": "sns.scatterplot(pca_df[:,0],pca_df[:,1], hue=”isQuality”,data=df, palette=”Set1\")plt.show()"
},
{
"code": null,
"e": 11750,
"s": 11042,
"text": "The graph above shows the plotting of data points using two features vs. Plotting of data points using principal components (which is basically a summarization of all the features in our dataset) i.e. PCA_1 and PCA_. This helps us to identify one more use of PCA i.e. proper and separable visualization of our dataset along with their “Quality” class tags. If you look at the graph, you can visualize the whole dataset properly with only two feature variables as compared to having thirteen feature variables. Though they do not differentiate well among (As see between sulfur dioxide and total sulfur dioxide) the wine quality classes but helps in reducing the feature set with minimal loss of information."
},
{
"code": null,
"e": 12002,
"s": 11750,
"text": "So far, we have made a pretty good understanding of PCA with some hands-on examples. We have seen how few components are sufficient to train models and also PCA is a great tool to reduce data dimension and give us the power to visualize data properly."
},
{
"code": null,
"e": 12175,
"s": 12002,
"text": "Let’s move forward and dive into one more tool for dimension reduction “Linear Discriminant Analysis”. I will be using the same wine dataset to provide hands-on experience."
},
{
"code": null,
"e": 12661,
"s": 12175,
"text": "Linear Discriminants is a statistical method of dimensionality reduction that provides the highest possible discrimination among various classes, used in machine learning to find the linear combination of features, which can separate two or more classes of objects with the best performance. The method is based on discriminant functions that are estimated based on a set of data called a training set. These discriminant functions are linear with respect to the characteristic vector."
},
{
"code": null,
"e": 12927,
"s": 12661,
"text": "The aim of LDA is to maximize the between-class variance and minimize the within-class variance, through a linear discriminant function, under the assumption that data in every class are described by a Gaussian probability density function with the same covariance."
},
{
"code": null,
"e": 13110,
"s": 12927,
"text": "It is good to understand the mathematics behind the LDA but I would not like to overwhelm anyone. We will understand by keeping things simple so it will be easy to follow for anyone."
},
{
"code": null,
"e": 13332,
"s": 13110,
"text": "LDA helps you find the boundaries of class clusters. This projects your data points on a line in order to differentiate the clusters as much as possible, with each cluster having a relatively close distance to a centroid."
},
{
"code": null,
"e": 13435,
"s": 13332,
"text": "So, the question arises-how are these clusters identified and how do we get LDA’s reduced feature set?"
},
{
"code": null,
"e": 13766,
"s": 13435,
"text": "Basically, LDA considers a centroid of data points for each class. For example, with eleven different features, LDA will use the eleven different feature datasets to find the centroid of each of its classes. Depending on this, it now defines a new dimension which is nothing more than an axis that should fulfill two requirements."
},
{
"code": null,
"e": 13910,
"s": 13766,
"text": "Maximize the distance between each class ‘Centroid.Minimize the variance within each group (which LDA calls scatter, and is represented by s2)."
},
{
"code": null,
"e": 13962,
"s": 13910,
"text": "Maximize the distance between each class ‘Centroid."
},
{
"code": null,
"e": 14055,
"s": 13962,
"text": "Minimize the variance within each group (which LDA calls scatter, and is represented by s2)."
},
{
"code": null,
"e": 14106,
"s": 14055,
"text": "Hence the essence is (mean_a — mean_b)/(S_a — S_b)"
},
{
"code": null,
"e": 14168,
"s": 14106,
"text": "(mean_a — mean_b) = ideally large (S_a — S_b) = ideally small"
},
{
"code": null,
"e": 14447,
"s": 14168,
"text": "Here mean is nothing more than the class centroid. Variance is nothing but the spread of data across the plane. So, if the data variance is small then there will be less overlapping between the classes and the overall distinction between the different classes will be preserved."
},
{
"code": null,
"e": 14551,
"s": 14447,
"text": "So whatever coordinate of the new axis meets these two conditions, they form the new dataset dimension."
},
{
"code": null,
"e": 14705,
"s": 14551,
"text": "Now let’s jump to implementing LDA using sklearn on wine dataset and see how the data transitions from a higher dimensionality to a lower dimensionality."
},
{
"code": null,
"e": 14768,
"s": 14705,
"text": "Let’s perform the LDA on wine dataset and analyze graphically:"
},
{
"code": null,
"e": 14872,
"s": 14768,
"text": "All the necessary libraries are already imported let’s import LDA with inbuilt LDA function in sklearn."
},
{
"code": null,
"e": 15116,
"s": 14872,
"text": "from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDAlda = LDA(n_components=2)lda_df = lda.fit(feature, target).transform(feature)sns.scatterplot(lda_df[:,0],lda_df[:,1], hue=”isQuality”,data=df, palette=”Set1\")plt.show()"
},
{
"code": null,
"e": 15261,
"s": 15116,
"text": "Note: I wanted to clarify that feature scaling such as (standardization) does not change the overall results of an LDA and thus may be optional."
},
{
"code": null,
"e": 15518,
"s": 15261,
"text": "In the PCA graph, you can visualize the whole dataset properly differentiate well among the classes. Whereas in the LDA graph the classes are not clearly separable due to the uneven distribution of classes. This is the major difference between PCA and LDA."
},
{
"code": null,
"e": 15718,
"s": 15518,
"text": "To summarize, PCA performs better in situations where there are fewer samples per class. In this wine dataset, we have high counts of class 2 (1319) followed by class 1 (217) and lastly class 0 (63)."
},
{
"code": null,
"e": 15856,
"s": 15718,
"text": "Although LDA works better with a large multi-class dataset where class separability is an important factor while reducing dimensionality."
},
{
"code": null,
"e": 16128,
"s": 15856,
"text": "The general LDA approach is very similar to a Principal Component Analysis, but in addition to finding the component axes that maximize the variance of our data (PCA), we are additionally interested in the axes that maximize the separation between multiple classes (LDA)."
},
{
"code": null,
"e": 16428,
"s": 16128,
"text": "Finally, let’s see how we can choose the number of n_components in dimensionality reduction methods within sklearn. The simple approach is to use explained_variance_ratio_ and plot the graph to see how many components we need to retain variance by the new feature set. Let’s understand by doing this"
},
{
"code": null,
"e": 16837,
"s": 16428,
"text": "scaler_df=scaler.fit(df).transform(df)pca = PCA().fit(scaler_df)plt.figure()plt.plot(np.cumsum(pca.explained_variance_ratio_))plt.xlabel(‘Number of n_Components’)plt.ylabel(‘Variance (%)’) #for each component present in the datasetplt.title(‘Wine Dataset Explained Variance’)plt.show()plt.ylabel(‘Variance (%)’) #for each component present in the datasetplt.title(‘Wine Dataset Explained Variance’)plt.show()"
},
{
"code": null,
"e": 17089,
"s": 16837,
"text": "This plot tells us that selecting 8 components we can preserve something more than 90 % of the total variance of the wine data. It makes sense, we’ll not use 100% of our variance, because it denotes all components, and we want only the principal ones."
}
] |
C# | Namespaces - GeeksforGeeks
|
01 Feb, 2019
Namespaces are used to organize the classes. It helps to control the scope of methods and classes in larger .Net programming projects. In simpler words you can say that it provides a way to keep one set of names(like class names) different from other sets of names. The biggest advantage of using namespace is that the class names which are declared in one namespace will not clash with the same class names declared in another namespace. It is also referred as named group of classes having common features. The members of a namespace can be namespaces, interfaces, structures, and delegates.
To define a namespace in C#, we will use the namespace keyword followed by the name of the namespace and curly braces containing the body of the namespace as follows:
Syntax:
namespace name_of_namespace {
// Namespace (Nested Namespaces)
// Classes
// Interfaces
// Structures
// Delegates
}
Example:
// defining the namespace name1
namespace name1
{
// C1 is the class in the namespace name1
class C1
{
// class code
}
}
The members of a namespace are accessed by using dot(.) operator. A class in C# is fully known by its respective namespace.
Syntax:
[namespace_name].[member_name]
Note:
Two classes with the same name can be created inside 2 different namespaces in a single program.
Inside a namespace, no two classes can have the same name.
In C#, the full name of the class starts from its namespace name followed by dot(.) operator and the class name, which is termed as the fully qualified name of the class.
Example:
// C# program to illustrate the // use of namespaces // namespace declarationnamespace first { // name_1 namespace members // i.e. class class Geeks_1 { // function of class Geeks_1 public static void display() { // Here System is the namespace // under which Console class is defined // You can avoid writing System with // the help of "using" keyword discussed // later in this article System.Console.WriteLine("Hello Geeks!"); } } /* Removing comment will give the error because no two classes can have the same name under a single namespace class Geeks_1 { } */ } // ending of first namespace // Class declarationclass Geeks_2{ // Main Method public static void Main(String []args) { // calling the display method of // class Geeks_1 by using two dot // operator as one is use to access // the class of first namespace and // another is use to access the // static method of class Geeks_1. // Termed as fully qualified name first.Geeks_1.display(); } }
Output:
Hello Geeks!
In the above example:
In System.Console.WriteLine()” “System” is a namespace in which we have a class named “Console” whose method is “WriteLine()“.
It is not necessary to keep each class in C# within Namespace but we do it to organize our code well.
Here “.” is the delimiter used to separate the class name from the namespace and function name from the classname.
It is not actually practical to call the function or class(or you can say members of a namespace) every time by using its fully qualified name. In the above example, System.Console.WriteLine(“Hello Geeks!”); and first.Geeks_1.display(); are the fully qualified name. So C# provides a keyword “using” which help the user to avoid writing fully qualified names again and again. The user just has to mention the namespace name at the starting of the program and then he can easily avoid the use of fully qualified names.
Syntax:
using [namespace_name][.][sub-namespace_name];
In the above syntax, dot(.) is used to include subnamespace names in the program.
Example:
// predefined namespace name
using System;
// user-defined namespace name
using name1
// namespace having subnamespace
using System.Collections.Generic;
Program:
// C# program to illustrate the // use of using keyword // predefined namespaceusing System; // user defined namespaceusing first; // namespace declarationnamespace first { // name_1 namespace members // i.e. class class Geeks_1 { // function of class Geeks_1 public static void display() { // No need to write fully qualified name // as we have used "using System" Console.WriteLine("Hello Geeks!"); } } } // ending of first namespace // Class declarationclass Geeks_2{ // Main Method public static void Main(String []args) { // calling the display method of // class Geeks_1 by using only one // dot operator as display is the // static method of class Geeks_1 Geeks_1.display(); } }
Output:
Hello Geeks!
You can also define a namespace into another namespace which is termed as the nested namespace. To access the members of nested namespace user has to use the dot(.) operator.
For example, Generic is the nested namespace in the collections namespace as System.Collections.Generic
Syntax:
namespace name_of_namespace_1
{
// Member declarations & definitions
namespace name_of_namespace_2
{
// Member declarations & definitions
.
.
}
}
Program:
// C# program to illustrate use of // nested namespaceusing System; // You can also use // using Main_name.Nest_name;// to avoid the use of fully // qualified name // main namespacenamespace Main_name{ // nested namespace namespace Nest_name { // class within nested namespace class Geeks_1 { // Constructor of nested // namespace class Geeks_1 public Geeks_1() { Console.WriteLine("Nested Namespace Constructor"); } } } } // Driver Classclass Driver { // Main Method public static void Main(string[] args) { // accessing the Nested Namespace by // using fully qualified name // "new" is used as Geeks_1() // is the Constructor new Main_name.Nest_name.Geeks_1(); } }
Output:
Nested Namespace Constructor
CSharp-Basics
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
Difference between Ref and Out keywords in C#
Introduction to .NET Framework
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
C# | Delegates
Top 50 C# Interview Questions & Answers
Different ways to sort an array in descending order in C#
C# | Replace() Method
|
[
{
"code": null,
"e": 23900,
"s": 23872,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24494,
"s": 23900,
"text": "Namespaces are used to organize the classes. It helps to control the scope of methods and classes in larger .Net programming projects. In simpler words you can say that it provides a way to keep one set of names(like class names) different from other sets of names. The biggest advantage of using namespace is that the class names which are declared in one namespace will not clash with the same class names declared in another namespace. It is also referred as named group of classes having common features. The members of a namespace can be namespaces, interfaces, structures, and delegates."
},
{
"code": null,
"e": 24661,
"s": 24494,
"text": "To define a namespace in C#, we will use the namespace keyword followed by the name of the namespace and curly braces containing the body of the namespace as follows:"
},
{
"code": null,
"e": 24669,
"s": 24661,
"text": "Syntax:"
},
{
"code": null,
"e": 24789,
"s": 24669,
"text": "namespace name_of_namespace {\n\n// Namespace (Nested Namespaces)\n// Classes\n// Interfaces\n// Structures\n// Delegates\n\n}\n"
},
{
"code": null,
"e": 24798,
"s": 24789,
"text": "Example:"
},
{
"code": null,
"e": 24947,
"s": 24798,
"text": "// defining the namespace name1\nnamespace name1 \n{\n\n // C1 is the class in the namespace name1\n class C1\n {\n // class code\n }\n}\n"
},
{
"code": null,
"e": 25071,
"s": 24947,
"text": "The members of a namespace are accessed by using dot(.) operator. A class in C# is fully known by its respective namespace."
},
{
"code": null,
"e": 25079,
"s": 25071,
"text": "Syntax:"
},
{
"code": null,
"e": 25111,
"s": 25079,
"text": "[namespace_name].[member_name]\n"
},
{
"code": null,
"e": 25117,
"s": 25111,
"text": "Note:"
},
{
"code": null,
"e": 25214,
"s": 25117,
"text": "Two classes with the same name can be created inside 2 different namespaces in a single program."
},
{
"code": null,
"e": 25273,
"s": 25214,
"text": "Inside a namespace, no two classes can have the same name."
},
{
"code": null,
"e": 25444,
"s": 25273,
"text": "In C#, the full name of the class starts from its namespace name followed by dot(.) operator and the class name, which is termed as the fully qualified name of the class."
},
{
"code": null,
"e": 25453,
"s": 25444,
"text": "Example:"
},
{
"code": "// C# program to illustrate the // use of namespaces // namespace declarationnamespace first { // name_1 namespace members // i.e. class class Geeks_1 { // function of class Geeks_1 public static void display() { // Here System is the namespace // under which Console class is defined // You can avoid writing System with // the help of \"using\" keyword discussed // later in this article System.Console.WriteLine(\"Hello Geeks!\"); } } /* Removing comment will give the error because no two classes can have the same name under a single namespace class Geeks_1 { } */ } // ending of first namespace // Class declarationclass Geeks_2{ // Main Method public static void Main(String []args) { // calling the display method of // class Geeks_1 by using two dot // operator as one is use to access // the class of first namespace and // another is use to access the // static method of class Geeks_1. // Termed as fully qualified name first.Geeks_1.display(); } }",
"e": 26720,
"s": 25453,
"text": null
},
{
"code": null,
"e": 26728,
"s": 26720,
"text": "Output:"
},
{
"code": null,
"e": 26741,
"s": 26728,
"text": "Hello Geeks!"
},
{
"code": null,
"e": 26763,
"s": 26741,
"text": "In the above example:"
},
{
"code": null,
"e": 26890,
"s": 26763,
"text": "In System.Console.WriteLine()” “System” is a namespace in which we have a class named “Console” whose method is “WriteLine()“."
},
{
"code": null,
"e": 26992,
"s": 26890,
"text": "It is not necessary to keep each class in C# within Namespace but we do it to organize our code well."
},
{
"code": null,
"e": 27107,
"s": 26992,
"text": "Here “.” is the delimiter used to separate the class name from the namespace and function name from the classname."
},
{
"code": null,
"e": 27625,
"s": 27107,
"text": "It is not actually practical to call the function or class(or you can say members of a namespace) every time by using its fully qualified name. In the above example, System.Console.WriteLine(“Hello Geeks!”); and first.Geeks_1.display(); are the fully qualified name. So C# provides a keyword “using” which help the user to avoid writing fully qualified names again and again. The user just has to mention the namespace name at the starting of the program and then he can easily avoid the use of fully qualified names."
},
{
"code": null,
"e": 27633,
"s": 27625,
"text": "Syntax:"
},
{
"code": null,
"e": 27681,
"s": 27633,
"text": "using [namespace_name][.][sub-namespace_name];\n"
},
{
"code": null,
"e": 27763,
"s": 27681,
"text": "In the above syntax, dot(.) is used to include subnamespace names in the program."
},
{
"code": null,
"e": 27772,
"s": 27763,
"text": "Example:"
},
{
"code": null,
"e": 27928,
"s": 27772,
"text": "// predefined namespace name\nusing System;\n\n// user-defined namespace name\nusing name1\n\n// namespace having subnamespace\nusing System.Collections.Generic;\n"
},
{
"code": null,
"e": 27937,
"s": 27928,
"text": "Program:"
},
{
"code": "// C# program to illustrate the // use of using keyword // predefined namespaceusing System; // user defined namespaceusing first; // namespace declarationnamespace first { // name_1 namespace members // i.e. class class Geeks_1 { // function of class Geeks_1 public static void display() { // No need to write fully qualified name // as we have used \"using System\" Console.WriteLine(\"Hello Geeks!\"); } } } // ending of first namespace // Class declarationclass Geeks_2{ // Main Method public static void Main(String []args) { // calling the display method of // class Geeks_1 by using only one // dot operator as display is the // static method of class Geeks_1 Geeks_1.display(); } }",
"e": 28826,
"s": 27937,
"text": null
},
{
"code": null,
"e": 28834,
"s": 28826,
"text": "Output:"
},
{
"code": null,
"e": 28847,
"s": 28834,
"text": "Hello Geeks!"
},
{
"code": null,
"e": 29022,
"s": 28847,
"text": "You can also define a namespace into another namespace which is termed as the nested namespace. To access the members of nested namespace user has to use the dot(.) operator."
},
{
"code": null,
"e": 29126,
"s": 29022,
"text": "For example, Generic is the nested namespace in the collections namespace as System.Collections.Generic"
},
{
"code": null,
"e": 29134,
"s": 29126,
"text": "Syntax:"
},
{
"code": null,
"e": 29325,
"s": 29134,
"text": "namespace name_of_namespace_1 \n{\n \n // Member declarations & definitions\n namespace name_of_namespace_2 \n {\n\n // Member declarations & definitions\n .\n .\n\n }\n}\n"
},
{
"code": null,
"e": 29334,
"s": 29325,
"text": "Program:"
},
{
"code": "// C# program to illustrate use of // nested namespaceusing System; // You can also use // using Main_name.Nest_name;// to avoid the use of fully // qualified name // main namespacenamespace Main_name{ // nested namespace namespace Nest_name { // class within nested namespace class Geeks_1 { // Constructor of nested // namespace class Geeks_1 public Geeks_1() { Console.WriteLine(\"Nested Namespace Constructor\"); } } } } // Driver Classclass Driver { // Main Method public static void Main(string[] args) { // accessing the Nested Namespace by // using fully qualified name // \"new\" is used as Geeks_1() // is the Constructor new Main_name.Nest_name.Geeks_1(); } }",
"e": 30338,
"s": 29334,
"text": null
},
{
"code": null,
"e": 30346,
"s": 30338,
"text": "Output:"
},
{
"code": null,
"e": 30376,
"s": 30346,
"text": "Nested Namespace Constructor\n"
},
{
"code": null,
"e": 30390,
"s": 30376,
"text": "CSharp-Basics"
},
{
"code": null,
"e": 30393,
"s": 30390,
"text": "C#"
},
{
"code": null,
"e": 30491,
"s": 30393,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30500,
"s": 30491,
"text": "Comments"
},
{
"code": null,
"e": 30513,
"s": 30500,
"text": "Old Comments"
},
{
"code": null,
"e": 30541,
"s": 30513,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 30587,
"s": 30541,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 30618,
"s": 30587,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 30641,
"s": 30618,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30681,
"s": 30641,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 30703,
"s": 30681,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 30718,
"s": 30703,
"text": "C# | Delegates"
},
{
"code": null,
"e": 30758,
"s": 30718,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 30816,
"s": 30758,
"text": "Different ways to sort an array in descending order in C#"
}
] |
How to encode a string in JavaScript?
|
Javascript has provided escape() function to encode a string. But since the escape()
function is now deprecated, it is better to use encodeURI() or encodeURIComponent().
escape(string);
encodeURIComponent(str);
In the following example, using the escape() method the string "Tutorix is the best e-learning platform!!!" is encoded and displayed the result in as shown in the output.
Live Demo
<html>
<body>
<script>
document.write(escape("Tutorix is the best e-learning platform!!!"));
</script>
</body>
</html>
Tutorix%20is%20the%20best%20e-learning%20platform%21%21%21
In the following example, using the encodeURIComponent() method the provide string is encoded and displayed the result as shown in the output.
Live Demo
<html>
<body>
<script>
document.write(encodeURIComponent("Tutorix is the best e-learning platform!!!"));
</script>
</body>
</html>
Tutorix%20is%20the%20best%20e-learning%20platform!!!
|
[
{
"code": null,
"e": 1233,
"s": 1062,
"text": "Javascript has provided escape() function to encode a string. But since the escape()\nfunction is now deprecated, it is better to use encodeURI() or encodeURIComponent(). "
},
{
"code": null,
"e": 1249,
"s": 1233,
"text": "escape(string);"
},
{
"code": null,
"e": 1274,
"s": 1249,
"text": "encodeURIComponent(str);"
},
{
"code": null,
"e": 1445,
"s": 1274,
"text": "In the following example, using the escape() method the string \"Tutorix is the best e-learning platform!!!\" is encoded and displayed the result in as shown in the output."
},
{
"code": null,
"e": 1455,
"s": 1445,
"text": "Live Demo"
},
{
"code": null,
"e": 1577,
"s": 1455,
"text": "<html>\n<body>\n<script>\n document.write(escape(\"Tutorix is the best e-learning platform!!!\"));\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1636,
"s": 1577,
"text": "Tutorix%20is%20the%20best%20e-learning%20platform%21%21%21"
},
{
"code": null,
"e": 1780,
"s": 1636,
"text": "In the following example, using the encodeURIComponent() method the provide string is encoded and displayed the result as shown in the output. "
},
{
"code": null,
"e": 1790,
"s": 1780,
"text": "Live Demo"
},
{
"code": null,
"e": 1924,
"s": 1790,
"text": "<html>\n<body>\n<script>\n document.write(encodeURIComponent(\"Tutorix is the best e-learning platform!!!\"));\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1977,
"s": 1924,
"text": "Tutorix%20is%20the%20best%20e-learning%20platform!!!"
}
] |
How to get the input from the Tkinter Text Widget?
|
In tkinter, we can create text widgets using Text attributes using packages. However, while creating a GUI application, sometimes we need to capture the input from a text widget.
We can get the input from the user in a text widget using the .get() method. We need to specify the input range which will be initially from 1.0 to END that shows the characters starting and ending till the END.
#Import tkinter library
from tkinter import *
#Create an instance of tkinter window or frame
win=Tk()
win.geometry("700x300")
def get_input():
value=my_text_box.get("1.0","end-1c")
print(value)
#Creating a text box widget
my_text_box=Text(win, height=5, width=40)
my_text_box.pack()
#Create a button for Comment
comment= Button(win, height=5, width=10, text="Comment", command=lambda: get_input())
#command=get_input() will wait for the key to press and displays the entered text
comment.pack()
win.mainloop()
Running the above code will display a textbox which will accept the input from the user and print the output on the console.
|
[
{
"code": null,
"e": 1241,
"s": 1062,
"text": "In tkinter, we can create text widgets using Text attributes using packages. However, while creating a GUI application, sometimes we need to capture the input from a text widget."
},
{
"code": null,
"e": 1453,
"s": 1241,
"text": "We can get the input from the user in a text widget using the .get() method. We need to specify the input range which will be initially from 1.0 to END that shows the characters starting and ending till the END."
},
{
"code": null,
"e": 1975,
"s": 1453,
"text": "#Import tkinter library\nfrom tkinter import *\n\n#Create an instance of tkinter window or frame\nwin=Tk()\nwin.geometry(\"700x300\")\n\ndef get_input():\n value=my_text_box.get(\"1.0\",\"end-1c\")\n print(value)\n\n#Creating a text box widget\nmy_text_box=Text(win, height=5, width=40)\nmy_text_box.pack()\n\n#Create a button for Comment\ncomment= Button(win, height=5, width=10, text=\"Comment\", command=lambda: get_input())\n\n#command=get_input() will wait for the key to press and displays the entered text\ncomment.pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 2100,
"s": 1975,
"text": "Running the above code will display a textbox which will accept the input from the user and print the output on the console."
}
] |
How to divide each column by a particular column in R?
|
To divide each column by a particular column, we can use division sign (/). For example, if we have a data frame called df that contains three columns say x, y, and z then we can divide all the columns by column z using the command df/df[,3].
Consider the below data frame −
Live Demo
x1<-rpois(20,5)
x2<-rpois(20,5)
x3<-rpois(20,5)
df1<-data.frame(x1,x2,x3)
df1
x1 x2 x3
1 7 7 5
2 7 6 5
3 7 3 7
4 2 4 5
5 3 8 1
6 2 3 2
7 4 5 4
8 3 4 8
9 6 7 4
10 5 8 7
11 5 6 3
12 6 6 4
13 6 2 5
14 6 4 2
15 4 2 2
16 7 6 7
17 5 8 5
18 4 4 3
19 0 2 4
20 6 5 6
Dividing all columns of df1 by column x3 −
df1/df1[,3]
x1 x2 x3
1 1.4000000 1.4000000 1
2 1.4000000 1.2000000 1
3 1.0000000 0.4285714 1
4 0.4000000 0.8000000 1
5 3.0000000 8.0000000 1
6 1.0000000 1.5000000 1
7 1.0000000 1.2500000 1
8 0.3750000 0.5000000 1
9 1.5000000 1.7500000 1
10 0.7142857 1.1428571 1
11 1.6666667 2.0000000 1
12 1.5000000 1.5000000 1
13 1.2000000 0.4000000 1
14 3.0000000 2.0000000 1
15 2.0000000 1.0000000 1
16 1.0000000 0.8571429 1
17 1.0000000 1.6000000 1
18 1.3333333 1.3333333 1
19 0.0000000 0.5000000 1
20 1.0000000 0.8333333 1
Live Demo
y1<-rpois(20,10)
y2<-rpois(20,10)
y3<-rpois(20,10)
df2<-data.frame(y1,y2,y3)
df2
y1 y2 y3
1 4 7 9
2 11 7 9
3 12 13 11
4 16 6 15
5 8 16 11
6 10 7 4
7 12 18 9
8 13 7 11
9 11 14 10
10 8 12 9
11 13 15 14
12 13 13 5
13 11 7 9
14 10 12 5
15 9 10 13
16 9 10 12
17 8 8 7
18 11 9 9
19 9 8 11
20 8 13 12
Dividing all columns of df2 by column y3 −
df2/df2[,3]
y1 y2 y3
1 0.4444444 0.7777778 1
2 1.2222222 0.7777778 1
3 1.0909091 1.1818182 1
4 1.0666667 0.4000000 1
5 0.7272727 1.4545455 1
6 2.5000000 1.7500000 1
7 1.3333333 2.0000000 1
8 1.1818182 0.6363636 1
9 1.1000000 1.4000000 1
10 0.8888889 1.3333333 1
11 0.9285714 1.0714286 1
12 2.6000000 2.6000000 1
13 1.2222222 0.7777778 1
14 2.0000000 2.4000000 1
15 0.6923077 0.7692308 1
16 0.7500000 0.8333333 1
17 1.1428571 1.1428571 1
18 1.2222222 1.0000000 1
19 0.8181818 0.7272727 1
20 0.6666667 1.0833333 1
|
[
{
"code": null,
"e": 1305,
"s": 1062,
"text": "To divide each column by a particular column, we can use division sign (/). For example, if we have a data frame called df that contains three columns say x, y, and z then we can divide all the columns by column z using the command df/df[,3]."
},
{
"code": null,
"e": 1337,
"s": 1305,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1348,
"s": 1337,
"text": " Live Demo"
},
{
"code": null,
"e": 1426,
"s": 1348,
"text": "x1<-rpois(20,5)\nx2<-rpois(20,5)\nx3<-rpois(20,5)\ndf1<-data.frame(x1,x2,x3)\ndf1"
},
{
"code": null,
"e": 1658,
"s": 1426,
"text": " x1 x2 x3\n1 7 7 5\n2 7 6 5\n3 7 3 7\n4 2 4 5\n5 3 8 1\n6 2 3 2\n7 4 5 4\n8 3 4 8\n9 6 7 4\n10 5 8 7\n11 5 6 3\n12 6 6 4\n13 6 2 5\n14 6 4 2\n15 4 2 2\n16 7 6 7\n17 5 8 5\n18 4 4 3\n19 0 2 4\n20 6 5 6"
},
{
"code": null,
"e": 1701,
"s": 1658,
"text": "Dividing all columns of df1 by column x3 −"
},
{
"code": null,
"e": 1713,
"s": 1701,
"text": "df1/df1[,3]"
},
{
"code": null,
"e": 2281,
"s": 1713,
"text": " x1 x2 x3\n1 1.4000000 1.4000000 1\n2 1.4000000 1.2000000 1\n3 1.0000000 0.4285714 1\n4 0.4000000 0.8000000 1\n5 3.0000000 8.0000000 1\n6 1.0000000 1.5000000 1\n7 1.0000000 1.2500000 1\n8 0.3750000 0.5000000 1\n9 1.5000000 1.7500000 1\n10 0.7142857 1.1428571 1\n11 1.6666667 2.0000000 1\n12 1.5000000 1.5000000 1\n13 1.2000000 0.4000000 1\n14 3.0000000 2.0000000 1\n15 2.0000000 1.0000000 1\n16 1.0000000 0.8571429 1\n17 1.0000000 1.6000000 1\n18 1.3333333 1.3333333 1\n19 0.0000000 0.5000000 1\n20 1.0000000 0.8333333 1"
},
{
"code": null,
"e": 2292,
"s": 2281,
"text": " Live Demo"
},
{
"code": null,
"e": 2373,
"s": 2292,
"text": "y1<-rpois(20,10)\ny2<-rpois(20,10)\ny3<-rpois(20,10)\ndf2<-data.frame(y1,y2,y3)\ndf2"
},
{
"code": null,
"e": 2668,
"s": 2373,
"text": " y1 y2 y3\n1 4 7 9\n2 11 7 9\n3 12 13 11\n4 16 6 15\n5 8 16 11\n6 10 7 4\n7 12 18 9\n8 13 7 11\n9 11 14 10\n10 8 12 9\n11 13 15 14\n12 13 13 5\n13 11 7 9\n14 10 12 5\n15 9 10 13\n16 9 10 12\n17 8 8 7\n18 11 9 9\n19 9 8 11\n20 8 13 12"
},
{
"code": null,
"e": 2711,
"s": 2668,
"text": "Dividing all columns of df2 by column y3 −"
},
{
"code": null,
"e": 2723,
"s": 2711,
"text": "df2/df2[,3]"
},
{
"code": null,
"e": 3291,
"s": 2723,
"text": " y1 y2 y3\n1 0.4444444 0.7777778 1\n2 1.2222222 0.7777778 1\n3 1.0909091 1.1818182 1\n4 1.0666667 0.4000000 1\n5 0.7272727 1.4545455 1\n6 2.5000000 1.7500000 1\n7 1.3333333 2.0000000 1\n8 1.1818182 0.6363636 1\n9 1.1000000 1.4000000 1\n10 0.8888889 1.3333333 1\n11 0.9285714 1.0714286 1\n12 2.6000000 2.6000000 1\n13 1.2222222 0.7777778 1\n14 2.0000000 2.4000000 1\n15 0.6923077 0.7692308 1\n16 0.7500000 0.8333333 1\n17 1.1428571 1.1428571 1\n18 1.2222222 1.0000000 1\n19 0.8181818 0.7272727 1\n20 0.6666667 1.0833333 1"
}
] |
WebCam Motion Detector program in Python ?
|
In this we are going to write python program which is going to analyse the images taken from the webcam and try to detect the movement and store the time-interval of the webcam video in a csv file.
We are going to use the OpenCV & pandas library for that. If it’s not already installed, you can install it using pip, with something like:
$pip install opencv2, pandas
#Import required libraries
import cv2
import pandas as pd
import time
from datetime import datetime
#Initialise variables
stillImage = None
motionImage = [ None, None ]
time = []
# Initializing the DataFrame with start and end time
df = pd.DataFrame(columns = ["start", "end"])
# Capturing video
video = cv2.VideoCapture(0)
while True:
# Start reading image from video
check, frame = video.read()
motion = 0
# Convert color image to gray_scale image
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
if stillImage is None:
stillImage = gray
continue
# Still Image and current image.
diff_frame = cv2.absdiff(stillImage, gray)
# change the image to white if static background and current frame is greater than 25.
thresh_frame = cv2.threshold(diff_frame, 25, 255, cv2.THRESH_BINARY)[1]
thresh_frame = cv2.dilate(thresh_frame, None, iterations = 2)
# Finding contour and hierarchy from a moving object.
contours,hierachy = cv2.findContours(thresh_frame.copy(),
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 10000:
continue
motion = 1
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
# Append current status of motion
motionImage.append(motion)
motionImage = motionImage[-2:]
# Append Start time of motion
if motionImage[-1] == 1 and motionImage[-2] == 0:
time.append(datetime.now())
# Append End time of motion
if motionImage[-1] == 0 and motionImage[-2] == 1:
time.append(datetime.now())
# Displaying image in gray_scale
cv2.imshow("Gray_Frame", gray)
# Display black and white frame & if the intensity difference is > 25, it turns white
cv2.imshow("Threshold Frame", thresh_frame)
# Display colored frame
cv2.imshow("Colored_Frame", frame)
key = cv2.waitKey(1)
# Press q to stop the process
if key == ord('q'):
if motion == 1:
time.append(datetime.now())
break
# Append time of motion
for i in range(0, len(time), 2):
df = df.append({"Start":time[i], "End":time[i + 1]}, ignore_index = True)
# Creating a csv file in which time of movements will be saved
df.to_csv("FrameInMotion_time.csv")
video.release()
# close window
cv2.destroyAllWindows()
We can see we’ll get 3 different Windows which are going to display our current movement from webcam in three different modes (grayscale, colored & black&White).
It will also store the datetime of our webcam Motion in a csv and our output from csv will be something like:
start end End Start
0 2019-02-21 18:10:59.718005 2019-02-21 18:08:35.791487
|
[
{
"code": null,
"e": 1260,
"s": 1062,
"text": "In this we are going to write python program which is going to analyse the images taken from the webcam and try to detect the movement and store the time-interval of the webcam video in a csv file."
},
{
"code": null,
"e": 1400,
"s": 1260,
"text": "We are going to use the OpenCV & pandas library for that. If it’s not already installed, you can install it using pip, with something like:"
},
{
"code": null,
"e": 1429,
"s": 1400,
"text": "$pip install opencv2, pandas"
},
{
"code": null,
"e": 3814,
"s": 1429,
"text": "#Import required libraries\nimport cv2\nimport pandas as pd\nimport time\nfrom datetime import datetime\n\n#Initialise variables\nstillImage = None\nmotionImage = [ None, None ]\ntime = []\n\n# Initializing the DataFrame with start and end time\ndf = pd.DataFrame(columns = [\"start\", \"end\"])\n\n# Capturing video\nvideo = cv2.VideoCapture(0)\n\nwhile True:\n # Start reading image from video\n check, frame = video.read()\n motion = 0\n\n # Convert color image to gray_scale image\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (21, 21), 0)\n if stillImage is None:\n stillImage = gray\n continue\n # Still Image and current image.\n diff_frame = cv2.absdiff(stillImage, gray)\n\n # change the image to white if static background and current frame is greater than 25.\n thresh_frame = cv2.threshold(diff_frame, 25, 255, cv2.THRESH_BINARY)[1]\n thresh_frame = cv2.dilate(thresh_frame, None, iterations = 2)\n # Finding contour and hierarchy from a moving object.\n contours,hierachy = cv2.findContours(thresh_frame.copy(),\n cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n for contour in contours:\n if cv2.contourArea(contour) < 10000:\n continue\n motion = 1\n (x, y, w, h) = cv2.boundingRect(contour)\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)\n # Append current status of motion\n motionImage.append(motion)\n motionImage = motionImage[-2:]\n # Append Start time of motion\n if motionImage[-1] == 1 and motionImage[-2] == 0:\n time.append(datetime.now())\n\n # Append End time of motion\n if motionImage[-1] == 0 and motionImage[-2] == 1:\n time.append(datetime.now())\n # Displaying image in gray_scale\n cv2.imshow(\"Gray_Frame\", gray)\n\n # Display black and white frame & if the intensity difference is > 25, it turns white\n cv2.imshow(\"Threshold Frame\", thresh_frame)\n # Display colored frame\n cv2.imshow(\"Colored_Frame\", frame)\n\n key = cv2.waitKey(1)\n # Press q to stop the process\n if key == ord('q'):\n if motion == 1:\n time.append(datetime.now())\n break\n\n# Append time of motion\nfor i in range(0, len(time), 2):\n df = df.append({\"Start\":time[i], \"End\":time[i + 1]}, ignore_index = True)\n\n# Creating a csv file in which time of movements will be saved\ndf.to_csv(\"FrameInMotion_time.csv\")\n\nvideo.release()\n\n# close window\ncv2.destroyAllWindows()"
},
{
"code": null,
"e": 3976,
"s": 3814,
"text": "We can see we’ll get 3 different Windows which are going to display our current movement from webcam in three different modes (grayscale, colored & black&White)."
},
{
"code": null,
"e": 4086,
"s": 3976,
"text": "It will also store the datetime of our webcam Motion in a csv and our output from csv will be something like:"
},
{
"code": null,
"e": 4219,
"s": 4086,
"text": "start end End Start\n0 2019-02-21 18:10:59.718005 2019-02-21 18:08:35.791487"
}
] |
BigInt in JavaScript
|
The BigInt is an inbuilt object that is used for representing whole numbers larger than 253 - 1.
Following is the code to implement BigInt in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>BigInt in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to display a BigInt number</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
BtnEle.addEventListener("click", () => {
resEle.innerHTML = BigInt(9007199254740991) + "<br>";
resEle.innerHTML += BigInt(Number.MAX_SAFE_INTEGER) + "<br>";
});
</script>
</body>
</html>
On clicking on ‘CLICK HERE’ button −
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "The BigInt is an inbuilt object that is used for representing whole numbers larger than 253 - 1."
},
{
"code": null,
"e": 1217,
"s": 1159,
"text": "Following is the code to implement BigInt in JavaScript −"
},
{
"code": null,
"e": 1228,
"s": 1217,
"text": " Live Demo"
},
{
"code": null,
"e": 2074,
"s": 1228,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>BigInt in JavaScript</h1>\n<div class=\"result\"></div>\n<br />\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to display a BigInt number</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n BtnEle.addEventListener(\"click\", () => {\n resEle.innerHTML = BigInt(9007199254740991) + \"<br>\";\n resEle.innerHTML += BigInt(Number.MAX_SAFE_INTEGER) + \"<br>\";\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2111,
"s": 2074,
"text": "On clicking on ‘CLICK HERE’ button −"
}
] |
Count the number of objects using Static member function in C++ Program
|
The goal here is to count the number of objects of a class that are being created using a static member function.
A static data member is shared by all objects of the class commonly. If no value is given, a static data member is always initialized with 0.
A static member function can only use static data members of that class.
We are using a class Student here. We will declare a static data member count which will store the count of objects. A static member function rollCall(void) which will display the count of objects as roll no.s of students in a class.
We declare a class Student which has public data members int rollno and static data member count.
We declare a class Student which has public data members int rollno and static data member count.
There is a constructor which calls rollcall() and initializes rollno with count.
There is a constructor which calls rollcall() and initializes rollno with count.
There is a destructor which decreases count.
There is a destructor which decreases count.
Static member function rollcall() displays the count of objects as Student count and increments the count.
Static member function rollcall() displays the count of objects as Student count and increments the count.
Each time the object of Student is created, constructor calls rollcall() and count is incremented. This count is assigned to rollno of that Student object.
Each time the object of Student is created, constructor calls rollcall() and count is incremented. This count is assigned to rollno of that Student object.
In the main we created 4 objects of class Student as stu1,stu2,stu3,stu4 and verified that count and rollno is the same as no. of objects.
In the main we created 4 objects of class Student as stu1,stu2,stu3,stu4 and verified that count and rollno is the same as no. of objects.
Live Demo
// C++ program to Count the number of objects
// using the Static member function
#include <iostream>
using namespace std;
class Student {
public:
int rollno;
static int count;
public:
Student(){
rollCall();
rollno=count;
}
~Student()
{ --count; }
static void rollCall(void){
cout <<endl<<"Student Count:" << ++count<< "\n"; //object count
}
};
int Student::count;
int main(){
Student stu1;
cout<<"Student 1: Roll No:"<<stu1.rollno;
Student stu2;
cout<<"Student 2: Roll No:"<<stu2.rollno;
Student stu3;
cout<<"Student 3: Roll No:"<<stu3.rollno;
Student stu4;
cout<<"Student 4: Roll No:"<<stu4.rollno;
return 0;
}
If we run the above code it will generate the following output −
Student Count:1
Student 1: Roll No:1
Student Count:2
Student 2: Roll No:2
Student Count:3
Student 3: Roll No:3
Student Count:4
Student 4: Roll No:4
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "The goal here is to count the number of objects of a class that are being created using a static member function."
},
{
"code": null,
"e": 1318,
"s": 1176,
"text": "A static data member is shared by all objects of the class commonly. If no value is given, a static data member is always initialized with 0."
},
{
"code": null,
"e": 1391,
"s": 1318,
"text": "A static member function can only use static data members of that class."
},
{
"code": null,
"e": 1625,
"s": 1391,
"text": "We are using a class Student here. We will declare a static data member count which will store the count of objects. A static member function rollCall(void) which will display the count of objects as roll no.s of students in a class."
},
{
"code": null,
"e": 1723,
"s": 1625,
"text": "We declare a class Student which has public data members int rollno and static data member count."
},
{
"code": null,
"e": 1821,
"s": 1723,
"text": "We declare a class Student which has public data members int rollno and static data member count."
},
{
"code": null,
"e": 1902,
"s": 1821,
"text": "There is a constructor which calls rollcall() and initializes rollno with count."
},
{
"code": null,
"e": 1983,
"s": 1902,
"text": "There is a constructor which calls rollcall() and initializes rollno with count."
},
{
"code": null,
"e": 2028,
"s": 1983,
"text": "There is a destructor which decreases count."
},
{
"code": null,
"e": 2073,
"s": 2028,
"text": "There is a destructor which decreases count."
},
{
"code": null,
"e": 2180,
"s": 2073,
"text": "Static member function rollcall() displays the count of objects as Student count and increments the count."
},
{
"code": null,
"e": 2287,
"s": 2180,
"text": "Static member function rollcall() displays the count of objects as Student count and increments the count."
},
{
"code": null,
"e": 2443,
"s": 2287,
"text": "Each time the object of Student is created, constructor calls rollcall() and count is incremented. This count is assigned to rollno of that Student object."
},
{
"code": null,
"e": 2599,
"s": 2443,
"text": "Each time the object of Student is created, constructor calls rollcall() and count is incremented. This count is assigned to rollno of that Student object."
},
{
"code": null,
"e": 2738,
"s": 2599,
"text": "In the main we created 4 objects of class Student as stu1,stu2,stu3,stu4 and verified that count and rollno is the same as no. of objects."
},
{
"code": null,
"e": 2877,
"s": 2738,
"text": "In the main we created 4 objects of class Student as stu1,stu2,stu3,stu4 and verified that count and rollno is the same as no. of objects."
},
{
"code": null,
"e": 2888,
"s": 2877,
"text": " Live Demo"
},
{
"code": null,
"e": 3570,
"s": 2888,
"text": "// C++ program to Count the number of objects\n// using the Static member function\n#include <iostream>\nusing namespace std;\nclass Student {\npublic:\n int rollno;\n static int count;\npublic:\n Student(){\n rollCall();\n rollno=count;\n }\n ~Student()\n { --count; }\n static void rollCall(void){\n cout <<endl<<\"Student Count:\" << ++count<< \"\\n\"; //object count\n }\n};\nint Student::count;\nint main(){\n Student stu1;\n cout<<\"Student 1: Roll No:\"<<stu1.rollno;\n Student stu2;\n cout<<\"Student 2: Roll No:\"<<stu2.rollno;\n Student stu3;\n cout<<\"Student 3: Roll No:\"<<stu3.rollno;\n Student stu4;\n cout<<\"Student 4: Roll No:\"<<stu4.rollno;\n return 0;\n}"
},
{
"code": null,
"e": 3635,
"s": 3570,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3783,
"s": 3635,
"text": "Student Count:1\nStudent 1: Roll No:1\nStudent Count:2\nStudent 2: Roll No:2\nStudent Count:3\nStudent 3: Roll No:3\nStudent Count:4\nStudent 4: Roll No:4"
}
] |
Find the first repeated word in a string in Java
|
To find the first repeated word in a string in Java, the code is as follows −
Live Demo
import java.util.*;
public class Demo{
static char repeat_first(char my_str[]){
HashSet<Character> my_hash = new HashSet<>();
for (int i=0; i<=my_str.length-1; i++){
char c = my_str[i];
if (my_hash.contains(c))
return c;
else
my_hash.add(c);
}
return '\0';
}
public static void main (String[] args){
String my_str = "thisisasampleonlysample";
char[] my_arr = my_str.toCharArray();
System.out.println("The first repeating character in the string is :");
System.out.println(repeat_first(my_arr));
}
}
The first repeating character in the string is :
I
A class named Demo contains a function named ‘repeat_first’, that takes a character string as a parameter. It creates a new hash set and iterates over the string and checks if the character in the string is equal to a specific character.
If yes, then the character is returned, otherwise, the character is added to the hash set. This way, the second time a word is found, it is added to the hash set, and this becomes the first word, that was in the string more than once. In the main function, the string is defined and a character array is defined. The function ‘repeat_first’ is called on this character array. The relevant array is displayed on the console.
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "To find the first repeated word in a string in Java, the code is as follows −"
},
{
"code": null,
"e": 1151,
"s": 1140,
"text": " Live Demo"
},
{
"code": null,
"e": 1755,
"s": 1151,
"text": "import java.util.*;\npublic class Demo{\n static char repeat_first(char my_str[]){\n HashSet<Character> my_hash = new HashSet<>();\n for (int i=0; i<=my_str.length-1; i++){\n char c = my_str[i];\n if (my_hash.contains(c))\n return c;\n else\n my_hash.add(c);\n }\n return '\\0';\n }\n public static void main (String[] args){\n String my_str = \"thisisasampleonlysample\";\n char[] my_arr = my_str.toCharArray();\n System.out.println(\"The first repeating character in the string is :\");\n System.out.println(repeat_first(my_arr));\n }\n}"
},
{
"code": null,
"e": 1806,
"s": 1755,
"text": "The first repeating character in the string is :\nI"
},
{
"code": null,
"e": 2044,
"s": 1806,
"text": "A class named Demo contains a function named ‘repeat_first’, that takes a character string as a parameter. It creates a new hash set and iterates over the string and checks if the character in the string is equal to a specific character."
},
{
"code": null,
"e": 2468,
"s": 2044,
"text": "If yes, then the character is returned, otherwise, the character is added to the hash set. This way, the second time a word is found, it is added to the hash set, and this becomes the first word, that was in the string more than once. In the main function, the string is defined and a character array is defined. The function ‘repeat_first’ is called on this character array. The relevant array is displayed on the console."
}
] |
K-Means vs. DBSCAN Clustering — For Beginners | by Ekta Sharma | Towards Data Science
|
Clustering is grouping of unlabeled data points in such a way that: The data points within the same group are similar to each other, and the data points in different groups are dissimilar to each other.The goal is to create clusters that have high intra-cluster similarity and low inter-cluster similarity.
K-Means cluster is one of the most commonly used unsupervised machine learning clustering techniques. It is a centroid based clustering technique that needs you decide the number of clusters (centroids) and randomly places the cluster centroids to begin the clustering process. The goal is to divide N observations into K clusters repeatedly until no more groups can be formed.
Easy to understand and implement.
Can handle large datasets well.
Sensitive to number of clusters/centroids chosen. Even after using techniques like Elbow method, it is sometimes hard to generate good clusters.
Does not work well with outliers. Centroids can get dragged by the outliers resulting in skewed clusters.
Gets difficult in high dimensional spaces as the distance between the points increases and Euclidean distance diverges (converges to a constant value).
Gets slow as the number of dimensions increases.
1. Decide the number of clusters. This number is called K and number of clusters is equal to the number of centroids. Based on the value of K, generate the coordinates for K random centroids.
2. For every point, calculate the Euclidean distance between the point and each of the centroids.
3. Assign the point to its nearest centroid. The points assigned to the same centroid form a cluster.
4. Once clusters are formed, calculate new centroid for each cluster by taking the cluster mean. Cluster mean is the mean of the x and y coordinates of all the points belonging to the cluster.
5. Repeat step 2, 3 and 4 until the centroids cannot move any further. In other words, repeat these steps until convergence.
import pandas as pdfrom sklearn import metricsfrom sklearn.cluster import KMeansimport matplotlib.pyplot as plt# reading the classic iris dataset into a dfiris_df = pd.read_csv(“iris_dataset.csv”)# Setting the independent features (input)X = iris_df.drop(“species”, axis=1).values# Creating the KMeans object and fitting it to the Iris datairis_kmeans = KMeans(n_clusters=3)iris_kmeans.fit(X)# Predicting the cluster labelslabels = iris_kmeans.predict(X)print(labels)# Finding the final centroidscentroids = iris_kmeans.cluster_centers_# Evaluating the quality of clusterss = metrics.silhouette_score(X, labels, metric=’euclidean’)print(f”Silhouette Coefficient for the Iris Dataset Clusters: {s:.2f}”)# plotting the clusters using sepal_length and sepal_widthplt.scatter(X[:, 0], X[:, 1], c=labels, cmap=”rainbow”)plt.show()
Label values represent the cluster number.
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 2 2 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 22 2 2 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 2 0 0 0 0 2 0 0 0 00 0 2 2 0 0 0 0 2 0 2 0 2 0 0 2 2 0 0 0 0 0 2 0 0 0 0 2 0 0 0 2 0 0 0 2 00 2]Silhouette Coefficient for the Iris Dataset Clusters: 0.55
The quality of clusters formed using K-Means largely depends on the selected value of K. A wrong choice of K can lead to poor clustering. So how to select K? Let’s take a look at the commonly used technique called “Elbow Method”. The goal is to select the K at which an elbow is formed.
Steps:
1. For different values of K, execute the following steps:
2. For each cluster, calculate the sum of squared distance of every point to its centroid.
3. Add the sum of squared distances of each cluster to get the total sum of squared distances for that value of K.
4. Keep adding the total sum of squared distances for each K to a list.
5. Plot the sum of squared distances (using the list created in the previous step) and their K values.
6. Select the K at which a sharp change occurs (looks like an elbow of the curve).
# Arbitrarily selecting a range of values for KK = range(1,10)sum_of_squared_distances = []# Using Scikit Learn’s KMeans Algorithm to find sum of squared distancesfor k in K: model = KMeans(n_clusters=k).fit(X) sum_of_squared_distances.append(model.inertia_)plt.plot(K, sum_of_squared_distances, “bx-”)plt.xlabel(“K values”)plt.ylabel(“Sum of Squared Distances”)plt.title(“Elbow Method”)plt.show()
Looking at this plot, we can see the elbow at K=3 and hence that is our optimal number of clusters for this dataset.
Sometimes we can end up with multiple values showing an elbow. In this case, to find the best K, an evaluation metric like Silhouette Coefficient can be used. The K that will return the highest positive value for the Silhouette Coefficient should be selected.
DBSCAN is a density-based clustering algorithm that forms clusters of dense regions of data points ignoring the low-density areas (considering them as noise).
Works well for noisy datasets.
Can identity Outliers easily.
Clusters can take any irregular shape unlike K-Means where clusters are more or less spherical.
Does not work very well for sparse datasets or datasets with varying density.
Sensitive to eps and minPts parameters.
Not partitionable for multiprocessor systems.
DBSCAN uses the following two user defined parameters for clustering:
Epsilon (eps): It is defined as the maximum distance between two points to be considered as neighboring points (belonging to the same cluster).
Minimum Points (min_samples or minPts): This defines the minimum number of neighboring points that a given point needs to be considered a core data point. This includes the point itself. For example, if minimum number of points is set to 4, then a given point needs to have 3 or more neighboring data points to be considered a core data point.
If minimum number of points meet the epsilon distance requirement then they are considered as a cluster.
Core Point: A data point is considered to be a core point if it has minimum number of neighboring data points (min_samples) at an epsilon distance from it. This minimum number of data points includes the original data point.Border Point: A data point that has less than minimum number of data points needed but has at least one core point in the neighborhood.Noise: A data point that is not a core point or a border point is considered noise or an outlier.
1. Decide the value of eps and minPts.
2. For each point:
Calculate its distance from all other points. If the distance is less than or equal to eps then mark that point as a neighbor of x.
If the point gets a neighboring count greater than or equal to minPts, then mark it as a core point or visited.
3. For each core point, if it not already assigned to a cluster than create a new cluster. Recursively find all its neighboring points and assign them the same cluster as the core point.
4. Continue these steps until all the unvisited points are covered.
import pandas as pdfrom sklearn import metricsfrom sklearn.cluster import DBSCANimport matplotlib.pyplot as plt# reading the classic iris dataset into a dfiris_df = pd.read_csv(“iris_dataset.csv”)X = iris_df.drop(“species”, axis=1).valuesiris_dbscan = DBSCAN(eps=0.5, min_samples=5)iris_dbscan.fit(X)labels = iris_dbscan.labels_# label=-1 means the point is an outlier. Rest of the values represent the label/cluster number starting from 0print(labels)# Creating a numpy array with all values set to false by defaultcore_samples_mask = np.zeros_like(labels, dtype=bool)# Setting core and border points (all points that are not -1) to Truecore_samples_mask[iris_dbscan.core_sample_indices_] = True# Finding the number of clusters in labels (ignoring noise if present)n_clusters_ = len(set(labels)) — (1 if -1 in labels else 0)n_noise_ = list(labels).count(-1)# Printing the number of clusters and number of noise points (outliers)print(“Estimated number of clusters: %d” % n_clusters_)print(“Estimated number of noise points: %d” % n_noise_)# Evaluating the quality of clusterss = metrics.silhouette_score(X, iris_dbscan.labels_)print(f”Silhouette Coefficient for the Iris Dataset Clusters: {s:.2f}”)
Label = -1 means it is a noise point (outlier).Label = 0 or more, indicates the cluster number.
[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 00 0 1 1 1 1 1 1 1 -1 1 1 -1 1 1 1 1 1 1 1 -1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 -1 1 11 1 -1 1 1 1 1 1 1 -1 -1 1 -1 -1 1 1 1 1 1 1 1 -1 -1 11 1 -1 1 1 1 1 1 1 1 1 -1 1 1 -1 -1 1 1 1 1 1 1 1 11 1 1 1 1 1]Estimated number of clusters: 2Estimated number of noise points: 17Silhouette Coefficient for the Iris Dataset Clusters: 0.49
unique_labels = set(labels)colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))for k, col in zip(unique_labels, colors): if k == -1: # Black used for noise col = “k” class_member_mask = (labels == k) xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], “o”, markerfacecolor=col, markeredgecolor=”k”, markersize=10) xy = X[class_member_mask & ~core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], “o”, markerfacecolor=col, markeredgecolor=”k”, markersize=5)plt.title(“Estimated number of clusters: %d” % n_clusters_)plt.show()
DBSCAN clustering algorithm is sensitive to the eps value we choose. So how can we know that we have selected the optimal eps value? Here is a commonly used technique called “Knee method”. The goal is to find the average of distances for every point to its K nearest neighbors and select the distance at which maximum curvature or a sharp change happens. The value of K is set to be equal to minPoints.
Here is an example to show optimal eps value selection using Scikit Learn’s NearestNeighbors module.
from sklearn.neighbors import NearestNeighborsnearest_neighbors = NearestNeighbors(n_neighbors=5)nearest_neighbors.fit(X)distances, indices = nearest_neighbors.kneighbors(X)distances = np.sort(distances, axis=0)[:, 1]print(distances)plt.plot(distances)plt.show()
[0. 0. 0. 0. 0. 0.10.1 0.1 0.1 0.1 0.1 0.10.1 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.14142136 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.14142136 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.14142136 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.14142136 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.14142136 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.17320508 0.17320508 0.17320508 0.17320508 0.17320508 0.173205080.17320508 0.2 0.2 0.2 0.2 0.20.2 0.2 0.2 0.2 0.2 0.20.2236068 0.2236068 0.2236068 0.2236068 0.2236068 0.22360680.2236068 0.2236068 0.2236068 0.2236068 0.24494897 0.244948970.24494897 0.24494897 0.24494897 0.24494897 0.24494897 0.244948970.24494897 0.24494897 0.24494897 0.24494897 0.26457513 0.264575130.26457513 0.26457513 0.26457513 0.26457513 0.26457513 0.264575130.26457513 0.26457513 0.26457513 0.26457513 0.28284271 0.282842710.28284271 0.28284271 0.3 0.3 0.3 0.30.3 0.3 0.3 0.31622777 0.31622777 0.316227770.33166248 0.33166248 0.33166248 0.33166248 0.33166248 0.346410160.34641016 0.34641016 0.34641016 0.34641016 0.34641016 0.346410160.36055513 0.36055513 0.36055513 0.36055513 0.37416574 0.387298330.38729833 0.38729833 0.41231056 0.41231056 0.41231056 0.412310560.42426407 0.42426407 0.43588989 0.45825757 0.48989795 0.489897950.53851648 0.53851648 0.55677644 0.6244998 0.63245553 0.73484692]
The optimal value should be the value at which we see maximum curvature which in this case seems to be near 0.5.
Sometimes we can end up with multiple values showing a sharp change. In this case, to find the best K, an evaluation metric like Silhouette Coefficient can be used. The K that will return the highest positive value for the Silhouette Coefficient should be selected.
When to use which of these two clustering techniques, depends on the problem. Even though K-Means is the most popular clustering technique, there are use cases where using DBSCAN results in better clusters.
|
[
{
"code": null,
"e": 479,
"s": 172,
"text": "Clustering is grouping of unlabeled data points in such a way that: The data points within the same group are similar to each other, and the data points in different groups are dissimilar to each other.The goal is to create clusters that have high intra-cluster similarity and low inter-cluster similarity."
},
{
"code": null,
"e": 857,
"s": 479,
"text": "K-Means cluster is one of the most commonly used unsupervised machine learning clustering techniques. It is a centroid based clustering technique that needs you decide the number of clusters (centroids) and randomly places the cluster centroids to begin the clustering process. The goal is to divide N observations into K clusters repeatedly until no more groups can be formed."
},
{
"code": null,
"e": 891,
"s": 857,
"text": "Easy to understand and implement."
},
{
"code": null,
"e": 923,
"s": 891,
"text": "Can handle large datasets well."
},
{
"code": null,
"e": 1068,
"s": 923,
"text": "Sensitive to number of clusters/centroids chosen. Even after using techniques like Elbow method, it is sometimes hard to generate good clusters."
},
{
"code": null,
"e": 1174,
"s": 1068,
"text": "Does not work well with outliers. Centroids can get dragged by the outliers resulting in skewed clusters."
},
{
"code": null,
"e": 1326,
"s": 1174,
"text": "Gets difficult in high dimensional spaces as the distance between the points increases and Euclidean distance diverges (converges to a constant value)."
},
{
"code": null,
"e": 1375,
"s": 1326,
"text": "Gets slow as the number of dimensions increases."
},
{
"code": null,
"e": 1567,
"s": 1375,
"text": "1. Decide the number of clusters. This number is called K and number of clusters is equal to the number of centroids. Based on the value of K, generate the coordinates for K random centroids."
},
{
"code": null,
"e": 1665,
"s": 1567,
"text": "2. For every point, calculate the Euclidean distance between the point and each of the centroids."
},
{
"code": null,
"e": 1767,
"s": 1665,
"text": "3. Assign the point to its nearest centroid. The points assigned to the same centroid form a cluster."
},
{
"code": null,
"e": 1960,
"s": 1767,
"text": "4. Once clusters are formed, calculate new centroid for each cluster by taking the cluster mean. Cluster mean is the mean of the x and y coordinates of all the points belonging to the cluster."
},
{
"code": null,
"e": 2085,
"s": 1960,
"text": "5. Repeat step 2, 3 and 4 until the centroids cannot move any further. In other words, repeat these steps until convergence."
},
{
"code": null,
"e": 2911,
"s": 2085,
"text": "import pandas as pdfrom sklearn import metricsfrom sklearn.cluster import KMeansimport matplotlib.pyplot as plt# reading the classic iris dataset into a dfiris_df = pd.read_csv(“iris_dataset.csv”)# Setting the independent features (input)X = iris_df.drop(“species”, axis=1).values# Creating the KMeans object and fitting it to the Iris datairis_kmeans = KMeans(n_clusters=3)iris_kmeans.fit(X)# Predicting the cluster labelslabels = iris_kmeans.predict(X)print(labels)# Finding the final centroidscentroids = iris_kmeans.cluster_centers_# Evaluating the quality of clusterss = metrics.silhouette_score(X, labels, metric=’euclidean’)print(f”Silhouette Coefficient for the Iris Dataset Clusters: {s:.2f}”)# plotting the clusters using sepal_length and sepal_widthplt.scatter(X[:, 0], X[:, 1], c=labels, cmap=”rainbow”)plt.show()"
},
{
"code": null,
"e": 2954,
"s": 2911,
"text": "Label values represent the cluster number."
},
{
"code": null,
"e": 3310,
"s": 2954,
"text": "[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 2 2 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 22 2 2 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 2 0 0 0 0 2 0 0 0 00 0 2 2 0 0 0 0 2 0 2 0 2 0 0 2 2 0 0 0 0 0 2 0 0 0 0 2 0 0 0 2 0 0 0 2 00 2]Silhouette Coefficient for the Iris Dataset Clusters: 0.55"
},
{
"code": null,
"e": 3597,
"s": 3310,
"text": "The quality of clusters formed using K-Means largely depends on the selected value of K. A wrong choice of K can lead to poor clustering. So how to select K? Let’s take a look at the commonly used technique called “Elbow Method”. The goal is to select the K at which an elbow is formed."
},
{
"code": null,
"e": 3604,
"s": 3597,
"text": "Steps:"
},
{
"code": null,
"e": 3663,
"s": 3604,
"text": "1. For different values of K, execute the following steps:"
},
{
"code": null,
"e": 3754,
"s": 3663,
"text": "2. For each cluster, calculate the sum of squared distance of every point to its centroid."
},
{
"code": null,
"e": 3869,
"s": 3754,
"text": "3. Add the sum of squared distances of each cluster to get the total sum of squared distances for that value of K."
},
{
"code": null,
"e": 3941,
"s": 3869,
"text": "4. Keep adding the total sum of squared distances for each K to a list."
},
{
"code": null,
"e": 4044,
"s": 3941,
"text": "5. Plot the sum of squared distances (using the list created in the previous step) and their K values."
},
{
"code": null,
"e": 4127,
"s": 4044,
"text": "6. Select the K at which a sharp change occurs (looks like an elbow of the curve)."
},
{
"code": null,
"e": 4531,
"s": 4127,
"text": "# Arbitrarily selecting a range of values for KK = range(1,10)sum_of_squared_distances = []# Using Scikit Learn’s KMeans Algorithm to find sum of squared distancesfor k in K: model = KMeans(n_clusters=k).fit(X) sum_of_squared_distances.append(model.inertia_)plt.plot(K, sum_of_squared_distances, “bx-”)plt.xlabel(“K values”)plt.ylabel(“Sum of Squared Distances”)plt.title(“Elbow Method”)plt.show()"
},
{
"code": null,
"e": 4648,
"s": 4531,
"text": "Looking at this plot, we can see the elbow at K=3 and hence that is our optimal number of clusters for this dataset."
},
{
"code": null,
"e": 4908,
"s": 4648,
"text": "Sometimes we can end up with multiple values showing an elbow. In this case, to find the best K, an evaluation metric like Silhouette Coefficient can be used. The K that will return the highest positive value for the Silhouette Coefficient should be selected."
},
{
"code": null,
"e": 5067,
"s": 4908,
"text": "DBSCAN is a density-based clustering algorithm that forms clusters of dense regions of data points ignoring the low-density areas (considering them as noise)."
},
{
"code": null,
"e": 5098,
"s": 5067,
"text": "Works well for noisy datasets."
},
{
"code": null,
"e": 5128,
"s": 5098,
"text": "Can identity Outliers easily."
},
{
"code": null,
"e": 5224,
"s": 5128,
"text": "Clusters can take any irregular shape unlike K-Means where clusters are more or less spherical."
},
{
"code": null,
"e": 5302,
"s": 5224,
"text": "Does not work very well for sparse datasets or datasets with varying density."
},
{
"code": null,
"e": 5342,
"s": 5302,
"text": "Sensitive to eps and minPts parameters."
},
{
"code": null,
"e": 5388,
"s": 5342,
"text": "Not partitionable for multiprocessor systems."
},
{
"code": null,
"e": 5458,
"s": 5388,
"text": "DBSCAN uses the following two user defined parameters for clustering:"
},
{
"code": null,
"e": 5602,
"s": 5458,
"text": "Epsilon (eps): It is defined as the maximum distance between two points to be considered as neighboring points (belonging to the same cluster)."
},
{
"code": null,
"e": 5946,
"s": 5602,
"text": "Minimum Points (min_samples or minPts): This defines the minimum number of neighboring points that a given point needs to be considered a core data point. This includes the point itself. For example, if minimum number of points is set to 4, then a given point needs to have 3 or more neighboring data points to be considered a core data point."
},
{
"code": null,
"e": 6051,
"s": 5946,
"text": "If minimum number of points meet the epsilon distance requirement then they are considered as a cluster."
},
{
"code": null,
"e": 6508,
"s": 6051,
"text": "Core Point: A data point is considered to be a core point if it has minimum number of neighboring data points (min_samples) at an epsilon distance from it. This minimum number of data points includes the original data point.Border Point: A data point that has less than minimum number of data points needed but has at least one core point in the neighborhood.Noise: A data point that is not a core point or a border point is considered noise or an outlier."
},
{
"code": null,
"e": 6547,
"s": 6508,
"text": "1. Decide the value of eps and minPts."
},
{
"code": null,
"e": 6566,
"s": 6547,
"text": "2. For each point:"
},
{
"code": null,
"e": 6698,
"s": 6566,
"text": "Calculate its distance from all other points. If the distance is less than or equal to eps then mark that point as a neighbor of x."
},
{
"code": null,
"e": 6810,
"s": 6698,
"text": "If the point gets a neighboring count greater than or equal to minPts, then mark it as a core point or visited."
},
{
"code": null,
"e": 6997,
"s": 6810,
"text": "3. For each core point, if it not already assigned to a cluster than create a new cluster. Recursively find all its neighboring points and assign them the same cluster as the core point."
},
{
"code": null,
"e": 7065,
"s": 6997,
"text": "4. Continue these steps until all the unvisited points are covered."
},
{
"code": null,
"e": 8265,
"s": 7065,
"text": "import pandas as pdfrom sklearn import metricsfrom sklearn.cluster import DBSCANimport matplotlib.pyplot as plt# reading the classic iris dataset into a dfiris_df = pd.read_csv(“iris_dataset.csv”)X = iris_df.drop(“species”, axis=1).valuesiris_dbscan = DBSCAN(eps=0.5, min_samples=5)iris_dbscan.fit(X)labels = iris_dbscan.labels_# label=-1 means the point is an outlier. Rest of the values represent the label/cluster number starting from 0print(labels)# Creating a numpy array with all values set to false by defaultcore_samples_mask = np.zeros_like(labels, dtype=bool)# Setting core and border points (all points that are not -1) to Truecore_samples_mask[iris_dbscan.core_sample_indices_] = True# Finding the number of clusters in labels (ignoring noise if present)n_clusters_ = len(set(labels)) — (1 if -1 in labels else 0)n_noise_ = list(labels).count(-1)# Printing the number of clusters and number of noise points (outliers)print(“Estimated number of clusters: %d” % n_clusters_)print(“Estimated number of noise points: %d” % n_noise_)# Evaluating the quality of clusterss = metrics.silhouette_score(X, iris_dbscan.labels_)print(f”Silhouette Coefficient for the Iris Dataset Clusters: {s:.2f}”)"
},
{
"code": null,
"e": 8361,
"s": 8265,
"text": "Label = -1 means it is a noise point (outlier).Label = 0 or more, indicates the cluster number."
},
{
"code": null,
"e": 8800,
"s": 8361,
"text": "[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 00 0 1 1 1 1 1 1 1 -1 1 1 -1 1 1 1 1 1 1 1 -1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 -1 1 11 1 -1 1 1 1 1 1 1 -1 -1 1 -1 -1 1 1 1 1 1 1 1 -1 -1 11 1 -1 1 1 1 1 1 1 1 1 -1 1 1 -1 -1 1 1 1 1 1 1 1 11 1 1 1 1 1]Estimated number of clusters: 2Estimated number of noise points: 17Silhouette Coefficient for the Iris Dataset Clusters: 0.49"
},
{
"code": null,
"e": 9396,
"s": 8800,
"text": "unique_labels = set(labels)colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))for k, col in zip(unique_labels, colors): if k == -1: # Black used for noise col = “k” class_member_mask = (labels == k) xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], “o”, markerfacecolor=col, markeredgecolor=”k”, markersize=10) xy = X[class_member_mask & ~core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], “o”, markerfacecolor=col, markeredgecolor=”k”, markersize=5)plt.title(“Estimated number of clusters: %d” % n_clusters_)plt.show()"
},
{
"code": null,
"e": 9799,
"s": 9396,
"text": "DBSCAN clustering algorithm is sensitive to the eps value we choose. So how can we know that we have selected the optimal eps value? Here is a commonly used technique called “Knee method”. The goal is to find the average of distances for every point to its K nearest neighbors and select the distance at which maximum curvature or a sharp change happens. The value of K is set to be equal to minPoints."
},
{
"code": null,
"e": 9900,
"s": 9799,
"text": "Here is an example to show optimal eps value selection using Scikit Learn’s NearestNeighbors module."
},
{
"code": null,
"e": 10163,
"s": 9900,
"text": "from sklearn.neighbors import NearestNeighborsnearest_neighbors = NearestNeighbors(n_neighbors=5)nearest_neighbors.fit(X)distances, indices = nearest_neighbors.kneighbors(X)distances = np.sort(distances, axis=0)[:, 1]print(distances)plt.plot(distances)plt.show()"
},
{
"code": null,
"e": 11558,
"s": 10163,
"text": "[0. 0. 0. 0. 0. 0.10.1 0.1 0.1 0.1 0.1 0.10.1 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.14142136 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.14142136 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.14142136 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.14142136 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.14142136 0.14142136 0.14142136 0.14142136 0.14142136 0.141421360.17320508 0.17320508 0.17320508 0.17320508 0.17320508 0.173205080.17320508 0.2 0.2 0.2 0.2 0.20.2 0.2 0.2 0.2 0.2 0.20.2236068 0.2236068 0.2236068 0.2236068 0.2236068 0.22360680.2236068 0.2236068 0.2236068 0.2236068 0.24494897 0.244948970.24494897 0.24494897 0.24494897 0.24494897 0.24494897 0.244948970.24494897 0.24494897 0.24494897 0.24494897 0.26457513 0.264575130.26457513 0.26457513 0.26457513 0.26457513 0.26457513 0.264575130.26457513 0.26457513 0.26457513 0.26457513 0.28284271 0.282842710.28284271 0.28284271 0.3 0.3 0.3 0.30.3 0.3 0.3 0.31622777 0.31622777 0.316227770.33166248 0.33166248 0.33166248 0.33166248 0.33166248 0.346410160.34641016 0.34641016 0.34641016 0.34641016 0.34641016 0.346410160.36055513 0.36055513 0.36055513 0.36055513 0.37416574 0.387298330.38729833 0.38729833 0.41231056 0.41231056 0.41231056 0.412310560.42426407 0.42426407 0.43588989 0.45825757 0.48989795 0.489897950.53851648 0.53851648 0.55677644 0.6244998 0.63245553 0.73484692]"
},
{
"code": null,
"e": 11671,
"s": 11558,
"text": "The optimal value should be the value at which we see maximum curvature which in this case seems to be near 0.5."
},
{
"code": null,
"e": 11937,
"s": 11671,
"text": "Sometimes we can end up with multiple values showing a sharp change. In this case, to find the best K, an evaluation metric like Silhouette Coefficient can be used. The K that will return the highest positive value for the Silhouette Coefficient should be selected."
}
] |
Knuth-Morris-Pratt Algorithm
|
Knuth Morris Pratt (KMP) is an algorithm, which checks the characters from left to right. When a pattern has a sub-pattern appears more than one in the sub-pattern, it uses that property to improve the time complexity, also for in the worst case.
The time complexity of KMP is O(n).
Input:
Main String: “AAAABAAAAABBBAAAAB”, The pattern “AAAB”
Output:
Pattern found at location: 1
Pattern found at location: 7
Pattern found at location: 14
findPrefix(pattern, m, prefArray)
Input − The pattern, the length of pattern and an array to store prefix location
Output − The array to store where prefixes are located
Begin
length := 0
prefArray[0] := 0
for all character index ‘i’ of pattern, do
if pattern[i] = pattern[length], then
increase length by 1
prefArray[i] := length
else
if length ≠ 0 then
length := prefArray[length - 1]
decrease i by 1
else
prefArray[i] := 0
done
End
kmpAlgorithm(text, pattern)
Input: The main text, and the pattern, which will be searched
Output − The location where patterns are found
Begin
n := size of text
m := size of pattern
call findPrefix(pattern, m, prefArray)
while i < n, do
if text[i] = pattern[j], then
increase i and j by 1
if j = m, then
print the location (i-j) as there is the pattern
j := prefArray[j-1]
else if i < n AND pattern[j] ≠ text[i] then
if j ≠ 0 then
j := prefArray[j - 1]
else
increase i by 1
done
End
#include<iostream>
using namespace std;
void findPrefix(string pattern, int m, int prefArray[]) {
int length = 0;
prefArray[0] = 0; //first place is always 0 as no prefix
for(int i = 1; i<m; i++) {
if(pattern[i] == pattern[length]) {
length++;
prefArray[i] = length;
}else {
if(length != 0) {
length = prefArray[length - 1];
i--; //decrease i to avoid effect of increasing after iteration
}else
prefArray[i] = 0;
}
}
}
void kmpPattSearch(string mainString, string pattern, int *locArray, int &loc) {
int n, m, i = 0, j = 0;
n = mainString.size();
m = pattern.size();
int prefixArray[m]; //prefix array as same size of pattern
findPrefix(pattern, m, prefixArray);
loc = 0;
while(i < n) {
if(mainString[i] == pattern[j]) {
i++; j++;
}
if(j == m) {
locArray[loc] = i-j; //item found at i-j position.
loc++;
j = prefixArray[j-1]; //get the prefix length from array
}else if(i < n && pattern[j] != mainString[i]) {
if(j != 0)
j = prefixArray[j-1];
else
i++;
}
}
}
int main() {
string str = "AAAABAAAAABBBAAAAB";
string patt = "AAAB";
int locationArray[str.size()];
int index;
kmpPattSearch(str, patt, locationArray, index);
for(int i = 0; i<index; i++) {
cout << "Pattern found at location: " <<locationArray[i] << endl;
}
}
Pattern found at location: 1
Pattern found at location: 7
Pattern found at location: 14
|
[
{
"code": null,
"e": 1309,
"s": 1062,
"text": "Knuth Morris Pratt (KMP) is an algorithm, which checks the characters from left to right. When a pattern has a sub-pattern appears more than one in the sub-pattern, it uses that property to improve the time complexity, also for in the worst case."
},
{
"code": null,
"e": 1345,
"s": 1309,
"text": "The time complexity of KMP is O(n)."
},
{
"code": null,
"e": 1502,
"s": 1345,
"text": "Input:\nMain String: “AAAABAAAAABBBAAAAB”, The pattern “AAAB”\nOutput:\nPattern found at location: 1\nPattern found at location: 7\nPattern found at location: 14"
},
{
"code": null,
"e": 1536,
"s": 1502,
"text": "findPrefix(pattern, m, prefArray)"
},
{
"code": null,
"e": 1617,
"s": 1536,
"text": "Input − The pattern, the length of pattern and an array to store prefix location"
},
{
"code": null,
"e": 1672,
"s": 1617,
"text": "Output − The array to store where prefixes are located"
},
{
"code": null,
"e": 2035,
"s": 1672,
"text": "Begin\n length := 0\n prefArray[0] := 0\n\n for all character index ‘i’ of pattern, do\n if pattern[i] = pattern[length], then\n increase length by 1\n prefArray[i] := length\n else\n if length ≠ 0 then\n length := prefArray[length - 1]\n decrease i by 1\n else\n prefArray[i] := 0\n done\nEnd"
},
{
"code": null,
"e": 2063,
"s": 2035,
"text": "kmpAlgorithm(text, pattern)"
},
{
"code": null,
"e": 2125,
"s": 2063,
"text": "Input: The main text, and the pattern, which will be searched"
},
{
"code": null,
"e": 2172,
"s": 2125,
"text": "Output − The location where patterns are found"
},
{
"code": null,
"e": 2623,
"s": 2172,
"text": "Begin\n n := size of text\n m := size of pattern\n call findPrefix(pattern, m, prefArray)\n\n while i < n, do\n if text[i] = pattern[j], then\n increase i and j by 1\n if j = m, then\n print the location (i-j) as there is the pattern\n j := prefArray[j-1]\n else if i < n AND pattern[j] ≠ text[i] then\n if j ≠ 0 then\n j := prefArray[j - 1]\n else\n increase i by 1\n done\nEnd"
},
{
"code": null,
"e": 4134,
"s": 2623,
"text": "#include<iostream>\nusing namespace std;\n\nvoid findPrefix(string pattern, int m, int prefArray[]) {\n int length = 0;\n prefArray[0] = 0; //first place is always 0 as no prefix\n\n for(int i = 1; i<m; i++) {\n if(pattern[i] == pattern[length]) {\n length++;\n prefArray[i] = length; \n }else {\n if(length != 0) {\n length = prefArray[length - 1];\n i--; //decrease i to avoid effect of increasing after iteration\n }else\n prefArray[i] = 0;\n }\n }\n}\n\nvoid kmpPattSearch(string mainString, string pattern, int *locArray, int &loc) {\n int n, m, i = 0, j = 0;\n n = mainString.size();\n m = pattern.size();\n int prefixArray[m]; //prefix array as same size of pattern\n findPrefix(pattern, m, prefixArray);\n loc = 0;\n\n while(i < n) {\n if(mainString[i] == pattern[j]) {\n i++; j++;\n }\n\n if(j == m) {\n locArray[loc] = i-j; //item found at i-j position.\n loc++;\n j = prefixArray[j-1]; //get the prefix length from array\n }else if(i < n && pattern[j] != mainString[i]) {\n if(j != 0)\n j = prefixArray[j-1];\n else\n i++;\n }\n }\n}\n\nint main() {\n string str = \"AAAABAAAAABBBAAAAB\";\n string patt = \"AAAB\";\n int locationArray[str.size()];\n int index;\n kmpPattSearch(str, patt, locationArray, index);\n\n for(int i = 0; i<index; i++) {\n cout << \"Pattern found at location: \" <<locationArray[i] << endl;\n }\n}"
},
{
"code": null,
"e": 4222,
"s": 4134,
"text": "Pattern found at location: 1\nPattern found at location: 7\nPattern found at location: 14"
}
] |
PHP - Date & Time
|
Dates are so much part of everyday life that it becomes easy to work with them without thinking. PHP also provides powerful tools for date arithmetic that make manipulating dates easy.
PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.
The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.
<?php
print time();
?>
This will produce the following result −
1480930103
This is something difficult to understand. But PHP offers excellent tools to convert a time stamp into a form that humans are comfortable with.
The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().
Following table lists the elements contained in the array returned by getdate().
seconds
Seconds past the minutes (0-59)
minutes
Minutes past the hour (0 - 59)
hours
Hours of the day (0 - 23)
mday
Day of the month (1 - 31)
wday
Day of the week (0 - 6)
mon
Month of the year (1 - 12)
year
Year (4 digits)
yday
Day of year ( 0 - 365 )
weekday
Day of the week
month
Month of the year
0
Timestamp
Now you have complete control over date and time. You can format this date and time in whatever format you wan.
Try out following example
<?php
$date_array = getdate();
foreach ( $date_array as $key => $val ){
print "$key = $val<br />";
}
$formated_date = "Today's date: ";
$formated_date .= $date_array['mday'] . "/";
$formated_date .= $date_array['mon'] . "/";
$formated_date .= $date_array['year'];
print $formated_date;
?>
This will produce following result −
seconds = 10
minutes = 29
hours = 9
mday = 5
wday = 1
mon = 12
year = 2016
yday = 339
weekday = Monday
month = December
0 = 1480930150
Today's date: 5/12/2016
The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.
date(format,timestamp)
The date() optionally accepts a time stamp if omitted then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.
Following table lists the codes that a format string can contain −
a
'am' or 'pm' lowercase
A
'AM' or 'PM' uppercase
d
Day of month, a number with leading zeroes
D
Day of week (three letters)
F
Month name
h
Hour (12-hour format - leading zeroes)
H
Hour (24-hour format - leading zeroes)
g
Hour (12-hour format - no leading zeroes)
G
Hour (24-hour format - no leading zeroes)
i
Minutes ( 0 - 59 )
j
Day of the month (no leading zeroes
l (Lower 'L')
Day of the week
L
Leap year ('1' for yes, '0' for no)
m
Month of year (number - leading zeroes)
M
Month of year (three letters)
r
The RFC 2822 formatted date
n
Month of year (number - no leading zeroes)
s
Seconds of hour
U
Time stamp
y
Year (two digits)
Y
Year (four digits)
z
Day of year (0 - 365)
Z
Offset in seconds from GMT
Try out following example
<?php
print date("m/d/y G.i:s<br>", time());
echo "<br>";
print "Today is ";
print date("j of F Y, \a\\t g.i a", time());
?>
This will produce following result −
12/05/16 9:29:47
Today is 5 2016f December 2016 at 9:29 am
Hope you have good understanding on how to format date and time according to your requirement. For your reference a complete list of all the date and time functions is given in PHP Date & Time Functions.
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2942,
"s": 2757,
"text": "Dates are so much part of everyday life that it becomes easy to work with them without thinking. PHP also provides powerful tools for date arithmetic that make manipulating dates easy."
},
{
"code": null,
"e": 3090,
"s": 2942,
"text": "PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer."
},
{
"code": null,
"e": 3328,
"s": 3090,
"text": "The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp."
},
{
"code": null,
"e": 3354,
"s": 3328,
"text": "<?php\n print time();\n?>"
},
{
"code": null,
"e": 3395,
"s": 3354,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3407,
"s": 3395,
"text": "1480930103\n"
},
{
"code": null,
"e": 3551,
"s": 3407,
"text": "This is something difficult to understand. But PHP offers excellent tools to convert a time stamp into a form that humans are comfortable with."
},
{
"code": null,
"e": 3766,
"s": 3551,
"text": "The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time()."
},
{
"code": null,
"e": 3847,
"s": 3766,
"text": "Following table lists the elements contained in the array returned by getdate()."
},
{
"code": null,
"e": 3855,
"s": 3847,
"text": "seconds"
},
{
"code": null,
"e": 3887,
"s": 3855,
"text": "Seconds past the minutes (0-59)"
},
{
"code": null,
"e": 3895,
"s": 3887,
"text": "minutes"
},
{
"code": null,
"e": 3926,
"s": 3895,
"text": "Minutes past the hour (0 - 59)"
},
{
"code": null,
"e": 3932,
"s": 3926,
"text": "hours"
},
{
"code": null,
"e": 3958,
"s": 3932,
"text": "Hours of the day (0 - 23)"
},
{
"code": null,
"e": 3963,
"s": 3958,
"text": "mday"
},
{
"code": null,
"e": 3989,
"s": 3963,
"text": "Day of the month (1 - 31)"
},
{
"code": null,
"e": 3994,
"s": 3989,
"text": "wday"
},
{
"code": null,
"e": 4018,
"s": 3994,
"text": "Day of the week (0 - 6)"
},
{
"code": null,
"e": 4022,
"s": 4018,
"text": "mon"
},
{
"code": null,
"e": 4049,
"s": 4022,
"text": "Month of the year (1 - 12)"
},
{
"code": null,
"e": 4054,
"s": 4049,
"text": "year"
},
{
"code": null,
"e": 4070,
"s": 4054,
"text": "Year (4 digits)"
},
{
"code": null,
"e": 4075,
"s": 4070,
"text": "yday"
},
{
"code": null,
"e": 4099,
"s": 4075,
"text": "Day of year ( 0 - 365 )"
},
{
"code": null,
"e": 4107,
"s": 4099,
"text": "weekday"
},
{
"code": null,
"e": 4123,
"s": 4107,
"text": "Day of the week"
},
{
"code": null,
"e": 4129,
"s": 4123,
"text": "month"
},
{
"code": null,
"e": 4147,
"s": 4129,
"text": "Month of the year"
},
{
"code": null,
"e": 4149,
"s": 4147,
"text": "0"
},
{
"code": null,
"e": 4159,
"s": 4149,
"text": "Timestamp"
},
{
"code": null,
"e": 4271,
"s": 4159,
"text": "Now you have complete control over date and time. You can format this date and time in whatever format you wan."
},
{
"code": null,
"e": 4297,
"s": 4271,
"text": "Try out following example"
},
{
"code": null,
"e": 4627,
"s": 4297,
"text": "<?php\n $date_array = getdate();\n \n foreach ( $date_array as $key => $val ){\n print \"$key = $val<br />\";\n }\n\t\n $formated_date = \"Today's date: \";\n $formated_date .= $date_array['mday'] . \"/\";\n $formated_date .= $date_array['mon'] . \"/\";\n $formated_date .= $date_array['year'];\n \n print $formated_date;\n?>"
},
{
"code": null,
"e": 4664,
"s": 4627,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4824,
"s": 4664,
"text": "seconds = 10\nminutes = 29\nhours = 9\nmday = 5\nwday = 1\nmon = 12\nyear = 2016\nyday = 339\nweekday = Monday\nmonth = December\n0 = 1480930150\nToday's date: 5/12/2016\n"
},
{
"code": null,
"e": 5024,
"s": 4824,
"text": "The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it."
},
{
"code": null,
"e": 5048,
"s": 5024,
"text": "date(format,timestamp)\n"
},
{
"code": null,
"e": 5246,
"s": 5048,
"text": "The date() optionally accepts a time stamp if omitted then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value."
},
{
"code": null,
"e": 5313,
"s": 5246,
"text": "Following table lists the codes that a format string can contain −"
},
{
"code": null,
"e": 5315,
"s": 5313,
"text": "a"
},
{
"code": null,
"e": 5338,
"s": 5315,
"text": "'am' or 'pm' lowercase"
},
{
"code": null,
"e": 5340,
"s": 5338,
"text": "A"
},
{
"code": null,
"e": 5363,
"s": 5340,
"text": "'AM' or 'PM' uppercase"
},
{
"code": null,
"e": 5365,
"s": 5363,
"text": "d"
},
{
"code": null,
"e": 5408,
"s": 5365,
"text": "Day of month, a number with leading zeroes"
},
{
"code": null,
"e": 5410,
"s": 5408,
"text": "D"
},
{
"code": null,
"e": 5438,
"s": 5410,
"text": "Day of week (three letters)"
},
{
"code": null,
"e": 5440,
"s": 5438,
"text": "F"
},
{
"code": null,
"e": 5451,
"s": 5440,
"text": "Month name"
},
{
"code": null,
"e": 5453,
"s": 5451,
"text": "h"
},
{
"code": null,
"e": 5492,
"s": 5453,
"text": "Hour (12-hour format - leading zeroes)"
},
{
"code": null,
"e": 5494,
"s": 5492,
"text": "H"
},
{
"code": null,
"e": 5533,
"s": 5494,
"text": "Hour (24-hour format - leading zeroes)"
},
{
"code": null,
"e": 5535,
"s": 5533,
"text": "g"
},
{
"code": null,
"e": 5577,
"s": 5535,
"text": "Hour (12-hour format - no leading zeroes)"
},
{
"code": null,
"e": 5579,
"s": 5577,
"text": "G"
},
{
"code": null,
"e": 5621,
"s": 5579,
"text": "Hour (24-hour format - no leading zeroes)"
},
{
"code": null,
"e": 5623,
"s": 5621,
"text": "i"
},
{
"code": null,
"e": 5642,
"s": 5623,
"text": "Minutes ( 0 - 59 )"
},
{
"code": null,
"e": 5644,
"s": 5642,
"text": "j"
},
{
"code": null,
"e": 5680,
"s": 5644,
"text": "Day of the month (no leading zeroes"
},
{
"code": null,
"e": 5694,
"s": 5680,
"text": "l (Lower 'L')"
},
{
"code": null,
"e": 5710,
"s": 5694,
"text": "Day of the week"
},
{
"code": null,
"e": 5712,
"s": 5710,
"text": "L"
},
{
"code": null,
"e": 5748,
"s": 5712,
"text": "Leap year ('1' for yes, '0' for no)"
},
{
"code": null,
"e": 5750,
"s": 5748,
"text": "m"
},
{
"code": null,
"e": 5790,
"s": 5750,
"text": "Month of year (number - leading zeroes)"
},
{
"code": null,
"e": 5792,
"s": 5790,
"text": "M"
},
{
"code": null,
"e": 5822,
"s": 5792,
"text": "Month of year (three letters)"
},
{
"code": null,
"e": 5824,
"s": 5822,
"text": "r"
},
{
"code": null,
"e": 5852,
"s": 5824,
"text": "The RFC 2822 formatted date"
},
{
"code": null,
"e": 5854,
"s": 5852,
"text": "n"
},
{
"code": null,
"e": 5897,
"s": 5854,
"text": "Month of year (number - no leading zeroes)"
},
{
"code": null,
"e": 5899,
"s": 5897,
"text": "s"
},
{
"code": null,
"e": 5915,
"s": 5899,
"text": "Seconds of hour"
},
{
"code": null,
"e": 5917,
"s": 5915,
"text": "U"
},
{
"code": null,
"e": 5928,
"s": 5917,
"text": "Time stamp"
},
{
"code": null,
"e": 5930,
"s": 5928,
"text": "y"
},
{
"code": null,
"e": 5948,
"s": 5930,
"text": "Year (two digits)"
},
{
"code": null,
"e": 5950,
"s": 5948,
"text": "Y"
},
{
"code": null,
"e": 5969,
"s": 5950,
"text": "Year (four digits)"
},
{
"code": null,
"e": 5971,
"s": 5969,
"text": "z"
},
{
"code": null,
"e": 5993,
"s": 5971,
"text": "Day of year (0 - 365)"
},
{
"code": null,
"e": 5995,
"s": 5993,
"text": "Z"
},
{
"code": null,
"e": 6022,
"s": 5995,
"text": "Offset in seconds from GMT"
},
{
"code": null,
"e": 6048,
"s": 6022,
"text": "Try out following example"
},
{
"code": null,
"e": 6185,
"s": 6048,
"text": "<?php\n print date(\"m/d/y G.i:s<br>\", time());\n echo \"<br>\";\n print \"Today is \";\n print date(\"j of F Y, \\a\\\\t g.i a\", time());\n?>"
},
{
"code": null,
"e": 6222,
"s": 6185,
"text": "This will produce following result −"
},
{
"code": null,
"e": 6282,
"s": 6222,
"text": "12/05/16 9:29:47\nToday is 5 2016f December 2016 at 9:29 am\n"
},
{
"code": null,
"e": 6486,
"s": 6282,
"text": "Hope you have good understanding on how to format date and time according to your requirement. For your reference a complete list of all the date and time functions is given in PHP Date & Time Functions."
},
{
"code": null,
"e": 6519,
"s": 6486,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6535,
"s": 6519,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6568,
"s": 6535,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6579,
"s": 6568,
"text": " Syed Raza"
},
{
"code": null,
"e": 6614,
"s": 6579,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6631,
"s": 6614,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6664,
"s": 6631,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6679,
"s": 6664,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 6714,
"s": 6679,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 6726,
"s": 6714,
"text": " Azaz Patel"
},
{
"code": null,
"e": 6761,
"s": 6726,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6789,
"s": 6761,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 6796,
"s": 6789,
"text": " Print"
},
{
"code": null,
"e": 6807,
"s": 6796,
"text": " Add Notes"
}
] |
Bootstrap .modal("toggle") method
|
Use the .modal(“toggle”) method in Bootstrap to toggle the modal.
As shown below, the modal generates on the click of a button −
$(document).ready(function(){
$("#button1").click(function(){
$("#newModal").modal("toggle");
});
});
Here is the button used above −
<button type="button" class="btn btn-default btn-lg" id="button1">
Modal One
</button>
You can try to run the following code to implement the modal(“toggle”) method −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Sample</h2>
<button type="button" class="btn btn-default btn-lg" id="button1">Modal One</button>
<div class="modal fade" id="newModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Sample Modal</h4>
</div>
<div class="modal-body">
<p>Click outside to close it.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#button1").click(function(){
$("#newModal").modal("toggle");
});
});
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1128,
"s": 1062,
"text": "Use the .modal(“toggle”) method in Bootstrap to toggle the modal."
},
{
"code": null,
"e": 1191,
"s": 1128,
"text": "As shown below, the modal generates on the click of a button −"
},
{
"code": null,
"e": 1301,
"s": 1191,
"text": "$(document).ready(function(){\n $(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"toggle\");\n });\n});"
},
{
"code": null,
"e": 1333,
"s": 1301,
"text": "Here is the button used above −"
},
{
"code": null,
"e": 1422,
"s": 1333,
"text": "<button type=\"button\" class=\"btn btn-default btn-lg\" id=\"button1\">\n Modal One\n</button>"
},
{
"code": null,
"e": 1502,
"s": 1422,
"text": "You can try to run the following code to implement the modal(“toggle”) method −"
},
{
"code": null,
"e": 1512,
"s": 1502,
"text": "Live Demo"
},
{
"code": null,
"e": 2900,
"s": 1512,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n<body>\n <div class=\"container\">\n <h2>Sample</h2>\n <button type=\"button\" class=\"btn btn-default btn-lg\" id=\"button1\">Modal One</button>\n <div class=\"modal fade\" id=\"newModal\" role=\"dialog\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n <h4 class=\"modal-title\">Sample Modal</h4>\n </div>\n <div class=\"modal-body\">\n <p>Click outside to close it.</p>\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-primary\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n </div>\n\n <script>\n $(document).ready(function(){\n $(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"toggle\");\n });\n });\n </script>\n\n</body>\n</html>"
}
] |
Angular Material 7 - Toggle Button
|
The <mat-button-toggle>, an Angular Directive, is used to create a toggle or on/off button with material styling and animations. mat-button-toggle buttons can be configured to behave as radio buttons or checkboxes. Typically they are part of <mat-button-toggle-group>.
In this chapter, we will showcase the configuration required to draw a button toggle control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatButtonToggleModule, MatIconModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatButtonToggleModule, MatIconModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified CSS file app.component.css.
.tp-selected-value {
margin: 15px 0;
}
Following is the content of the modified HTML host file app.component.html.
<mat-button-toggle-group #group = "matButtonToggleGroup">
<mat-button-toggle value = "left">
<mat-icon>format_align_left</mat-icon>
</mat-button-toggle>
<mat-button-toggle value = "center">
<mat-icon>format_align_center</mat-icon>
</mat-button-toggle>
<mat-button-toggle value = "right">
<mat-icon>format_align_right</mat-icon>
</mat-button-toggle>
<mat-button-toggle value = "justify" disabled>
<mat-icon>format_align_justify</mat-icon>
</mat-button-toggle>
</mat-button-toggle-group>
<div class = "tp-selected-value">Selected value: {{group.value}}</div>
Verify the result.
As first, we've created a toggle button group using mat-button-toggle-group.
Then, we've added toggle buttons to the group using mat-button-toggle.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3024,
"s": 2755,
"text": "The <mat-button-toggle>, an Angular Directive, is used to create a toggle or on/off button with material styling and animations. mat-button-toggle buttons can be configured to behave as radio buttons or checkboxes. Typically they are part of <mat-button-toggle-group>."
},
{
"code": null,
"e": 3141,
"s": 3024,
"text": "In this chapter, we will showcase the configuration required to draw a button toggle control using Angular Material."
},
{
"code": null,
"e": 3252,
"s": 3141,
"text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −"
},
{
"code": null,
"e": 3326,
"s": 3252,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 3983,
"s": 3326,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatButtonToggleModule, MatIconModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatButtonToggleModule, MatIconModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 4052,
"s": 3983,
"text": "Following is the content of the modified CSS file app.component.css."
},
{
"code": null,
"e": 4094,
"s": 4052,
"text": ".tp-selected-value {\n margin: 15px 0;\n}"
},
{
"code": null,
"e": 4170,
"s": 4094,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 4775,
"s": 4170,
"text": "<mat-button-toggle-group #group = \"matButtonToggleGroup\">\n <mat-button-toggle value = \"left\">\n <mat-icon>format_align_left</mat-icon>\n </mat-button-toggle>\n <mat-button-toggle value = \"center\">\n <mat-icon>format_align_center</mat-icon>\n </mat-button-toggle>\n <mat-button-toggle value = \"right\">\n <mat-icon>format_align_right</mat-icon>\n </mat-button-toggle>\n <mat-button-toggle value = \"justify\" disabled>\n <mat-icon>format_align_justify</mat-icon>\n </mat-button-toggle>\n</mat-button-toggle-group>\n<div class = \"tp-selected-value\">Selected value: {{group.value}}</div>"
},
{
"code": null,
"e": 4794,
"s": 4775,
"text": "Verify the result."
},
{
"code": null,
"e": 4871,
"s": 4794,
"text": "As first, we've created a toggle button group using mat-button-toggle-group."
},
{
"code": null,
"e": 4942,
"s": 4871,
"text": "Then, we've added toggle buttons to the group using mat-button-toggle."
},
{
"code": null,
"e": 4977,
"s": 4942,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4991,
"s": 4977,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5026,
"s": 4991,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5040,
"s": 5026,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5075,
"s": 5040,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5095,
"s": 5075,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5130,
"s": 5095,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5147,
"s": 5130,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5180,
"s": 5147,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5192,
"s": 5180,
"text": " Senol Atac"
},
{
"code": null,
"e": 5227,
"s": 5192,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5239,
"s": 5227,
"text": " Senol Atac"
},
{
"code": null,
"e": 5246,
"s": 5239,
"text": " Print"
},
{
"code": null,
"e": 5257,
"s": 5246,
"text": " Add Notes"
}
] |
Python Pandas – How to skip initial space from a DataFrame
|
To skip initial space from a Pandas DataFrame, use the skipinitialspace parameter of the read_csv() method. Set the parameter to True to remove extra space.
Let’s say the following is our csv file −
We should get the following output i.e. skipping initial whitespace and displaying the DataFrame from the CSV −
Following is the complete code −
import pandas as pd
# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
print("DataFrame...\n",dataFrame)
# reading csv file and removing initial space
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv", skipinitialspace = True)
print("DataFrame...\n",dataFrame)
At first, read the CSV. Our CSV file is on the Desktop −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
While reading, you can set the skipinitialspace parameter and remove whitespace −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv", skipinitialspace = True)
This will produce the following output −
DataFrame...
Car Place UnitsSold
0 Audi Bangalore 80
1 Porsche Mumbai 110
2 RollsRoyce Pune 100
3 BMW Delhi 200
4 Mercedes Hyderabad 80
5 Lamborghini Chandigarh 80
6 Audi Mumbai 60
7 Mercedes Pune 120
8 Lamborghini Delhi 100
DataFrame...
Car Place UnitsSold
0 Audi Bangalore 80
1 Porsche Mumbai 110
2 RollsRoyce Pune 100
3 BMW Delhi 200
4 Mercedes Hyderabad 80
5 Lamborghini Chandigarh 80
6 Audi Mumbai 60
7 Mercedes Pune 120
8 Lamborghini Delhi 100
|
[
{
"code": null,
"e": 1219,
"s": 1062,
"text": "To skip initial space from a Pandas DataFrame, use the skipinitialspace parameter of the read_csv() method. Set the parameter to True to remove extra space."
},
{
"code": null,
"e": 1261,
"s": 1219,
"text": "Let’s say the following is our csv file −"
},
{
"code": null,
"e": 1373,
"s": 1261,
"text": "We should get the following output i.e. skipping initial whitespace and displaying the DataFrame from the CSV −"
},
{
"code": null,
"e": 1406,
"s": 1373,
"text": "Following is the complete code −"
},
{
"code": null,
"e": 1724,
"s": 1406,
"text": "import pandas as pd\n\n# reading csv file\ndataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\CarRecords.csv\")\nprint(\"DataFrame...\\n\",dataFrame)\n\n# reading csv file and removing initial space\ndataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\CarRecords.csv\", skipinitialspace = True)\nprint(\"DataFrame...\\n\",dataFrame)"
},
{
"code": null,
"e": 1781,
"s": 1724,
"text": "At first, read the CSV. Our CSV file is on the Desktop −"
},
{
"code": null,
"e": 1850,
"s": 1781,
"text": "dataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\CarRecords.csv\")"
},
{
"code": null,
"e": 1932,
"s": 1850,
"text": "While reading, you can set the skipinitialspace parameter and remove whitespace −"
},
{
"code": null,
"e": 2026,
"s": 1932,
"text": "dataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\CarRecords.csv\", skipinitialspace = True)"
},
{
"code": null,
"e": 2067,
"s": 2026,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2873,
"s": 2067,
"text": "DataFrame...\n Car Place UnitsSold\n0 Audi Bangalore 80\n1 Porsche Mumbai 110\n2 RollsRoyce Pune 100\n3 BMW Delhi 200\n4 Mercedes Hyderabad 80\n5 Lamborghini Chandigarh 80\n6 Audi Mumbai 60\n7 Mercedes Pune 120\n8 Lamborghini Delhi 100\nDataFrame...\n Car Place UnitsSold\n0 Audi Bangalore 80\n1 Porsche Mumbai 110\n2 RollsRoyce Pune 100\n3 BMW Delhi 200\n4 Mercedes Hyderabad 80\n5 Lamborghini Chandigarh 80\n6 Audi Mumbai 60\n7 Mercedes Pune 120\n8 Lamborghini Delhi 100"
}
] |
JavaScript TypeError - Cyclic object value - GeeksforGeeks
|
23 Aug, 2020
This JavaScript exception cyclic object value occurs if the references of objects were found in JSON. JSON.stringify() fails to solve them.
Message:
TypeError: cyclic object value (Firefox)
TypeError: Converting circular structure to JSON
(Chrome and Opera)
TypeError: Circular reference in value argument
not supported (Edge)
Error Type:
TypeError
Cause of error: If in the code references are found then JSON.stringify() fails to solve them.
Example 1: In this example, the circObj has a reference to itself, So the error has occurred.
HTML
<script> var circObj = {1: "1"}; circObj.myself = circObj; JSON.stringify(circObj);</script>
Output:
TypeError: Converting circular structure to JSON
Example 2: In this example, the GFG_Obj has a reference to itself, and JSON.stringify() fails to solve it. So the error has occurred.
HTML
<script> var GFG_Obj = {property_1: "value_1"}; GFG_Obj.myself = GFG_Obj; JSON.stringify(GFG_Obj);</script>
Output:
TypeError: Converting circular structure to JSON
JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Express.js express.Router() Function
Installation of Node.js on Linux
How to set input type date in dd-mm-yyyy format using HTML ?
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n23 Aug, 2020"
},
{
"code": null,
"e": 25049,
"s": 24909,
"text": "This JavaScript exception cyclic object value occurs if the references of objects were found in JSON. JSON.stringify() fails to solve them."
},
{
"code": null,
"e": 25058,
"s": 25049,
"text": "Message:"
},
{
"code": null,
"e": 25261,
"s": 25058,
"text": "TypeError: cyclic object value (Firefox)\nTypeError: Converting circular structure to JSON \n (Chrome and Opera)\nTypeError: Circular reference in value argument \n not supported (Edge)\n"
},
{
"code": null,
"e": 25273,
"s": 25261,
"text": "Error Type:"
},
{
"code": null,
"e": 25284,
"s": 25273,
"text": "TypeError\n"
},
{
"code": null,
"e": 25379,
"s": 25284,
"text": "Cause of error: If in the code references are found then JSON.stringify() fails to solve them."
},
{
"code": null,
"e": 25473,
"s": 25379,
"text": "Example 1: In this example, the circObj has a reference to itself, So the error has occurred."
},
{
"code": null,
"e": 25478,
"s": 25473,
"text": "HTML"
},
{
"code": "<script> var circObj = {1: \"1\"}; circObj.myself = circObj; JSON.stringify(circObj);</script>",
"e": 25580,
"s": 25478,
"text": null
},
{
"code": null,
"e": 25588,
"s": 25580,
"text": "Output:"
},
{
"code": null,
"e": 25638,
"s": 25588,
"text": "TypeError: Converting circular structure to JSON\n"
},
{
"code": null,
"e": 25772,
"s": 25638,
"text": "Example 2: In this example, the GFG_Obj has a reference to itself, and JSON.stringify() fails to solve it. So the error has occurred."
},
{
"code": null,
"e": 25777,
"s": 25772,
"text": "HTML"
},
{
"code": "<script> var GFG_Obj = {property_1: \"value_1\"}; GFG_Obj.myself = GFG_Obj; JSON.stringify(GFG_Obj);</script>",
"e": 25894,
"s": 25777,
"text": null
},
{
"code": null,
"e": 25902,
"s": 25894,
"text": "Output:"
},
{
"code": null,
"e": 25952,
"s": 25902,
"text": "TypeError: Converting circular structure to JSON\n"
},
{
"code": null,
"e": 25970,
"s": 25952,
"text": "JavaScript-Errors"
},
{
"code": null,
"e": 25981,
"s": 25970,
"text": "JavaScript"
},
{
"code": null,
"e": 25998,
"s": 25981,
"text": "Web Technologies"
},
{
"code": null,
"e": 26096,
"s": 25998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26105,
"s": 26096,
"text": "Comments"
},
{
"code": null,
"e": 26118,
"s": 26105,
"text": "Old Comments"
},
{
"code": null,
"e": 26179,
"s": 26118,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26220,
"s": 26179,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26274,
"s": 26220,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 26314,
"s": 26274,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26376,
"s": 26314,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 26413,
"s": 26376,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 26446,
"s": 26413,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26507,
"s": 26446,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 26565,
"s": 26507,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
2D and 2.5D Memory organization - GeeksforGeeks
|
24 Jan, 2022
The internal structure of Memory either RAM or ROM is made up of memory cells that contain a memory bit. A group of 8 bits makes a byte. The memory is in the form of a multidimensional array of rows and columns. In which, each cell stores a bit and a complete row contains a word. A memory simply can be divided into this below form.
2n = N
where n is the no. of address lines and N is the total memory in bytes. There will be 2n words.
2D Memory organization – In 2D organization, memory is divided in the form of rows and columns(Matrix). Each row contains a word, now in this memory organization, there is a decoder. A decoder is a combinational circuit that contains n input lines and 2n output lines. One of the output lines selects the row by the address contained in the MAR and the word which is represented by that row gets selected and is either read or written through the data lines.
2.5D Memory organization – In 2.5D Organization the scenario is the same but we have two different decoders one is a column decoder and another is a row decoder. Column decoder is used to select the column and a row decoder is used to select the row. The address from the MAR goes as the decoders’ input. Decoders will select the respective cell through the bit outline, then the data from that location will be read or through the bit, inline data will be written at that memory location.
Read and Write Operations –
If the select line is in Reading mode then the Word/bit which is represented by the MAR will be available to the data lines and will get read.If the select line is in write mode then the data from the memory data register (MDR) will be sent to the respective cell which is addressed by the memory address register (MAR).With the help of the select line, we can select the desired data and we can perform read and write operations on it.
If the select line is in Reading mode then the Word/bit which is represented by the MAR will be available to the data lines and will get read.
If the select line is in write mode then the data from the memory data register (MDR) will be sent to the respective cell which is addressed by the memory address register (MAR).
With the help of the select line, we can select the desired data and we can perform read and write operations on it.
Comparison between 2D & 2.5D Organizations –
In 2D organization hardware is fixed but in 2.5D hardware changes.2D Organization requires more gates while 2.5D requires less.2D is more complex in comparison to the 2.5D organization.Error correction is not possible in the 2D organization but in 2.5D it could be done easily.2D is more difficult to fabricate in comparison to the 2.5D organization.
In 2D organization hardware is fixed but in 2.5D hardware changes.
2D Organization requires more gates while 2.5D requires less.
2D is more complex in comparison to the 2.5D organization.
Error correction is not possible in the 2D organization but in 2.5D it could be done easily.
2D is more difficult to fabricate in comparison to the 2.5D organization.
1716410060_ashutosh_verma
meshubhamsr
alokesh985
kharedevansh01
tanwarsinghvaibhav
memory-management
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Addressing modes in 8085 microprocessor
Program for Decimal to Binary Conversion
Logical and Physical Address in Operating System
Architecture of 8085 microprocessor
8085 program to add two 8 bit numbers
Program for Binary To Decimal Conversion
Pin diagram of 8086 microprocessor
Architecture of 8086
Difference between Von Neumann and Harvard Architecture
Flag register in 8085 microprocessor
|
[
{
"code": null,
"e": 27384,
"s": 27356,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 27720,
"s": 27384,
"text": "The internal structure of Memory either RAM or ROM is made up of memory cells that contain a memory bit. A group of 8 bits makes a byte. The memory is in the form of a multidimensional array of rows and columns. In which, each cell stores a bit and a complete row contains a word. A memory simply can be divided into this below form. "
},
{
"code": null,
"e": 27727,
"s": 27720,
"text": "2n = N"
},
{
"code": null,
"e": 27824,
"s": 27727,
"text": "where n is the no. of address lines and N is the total memory in bytes. There will be 2n words. "
},
{
"code": null,
"e": 28284,
"s": 27824,
"text": "2D Memory organization – In 2D organization, memory is divided in the form of rows and columns(Matrix). Each row contains a word, now in this memory organization, there is a decoder. A decoder is a combinational circuit that contains n input lines and 2n output lines. One of the output lines selects the row by the address contained in the MAR and the word which is represented by that row gets selected and is either read or written through the data lines. "
},
{
"code": null,
"e": 28777,
"s": 28286,
"text": "2.5D Memory organization – In 2.5D Organization the scenario is the same but we have two different decoders one is a column decoder and another is a row decoder. Column decoder is used to select the column and a row decoder is used to select the row. The address from the MAR goes as the decoders’ input. Decoders will select the respective cell through the bit outline, then the data from that location will be read or through the bit, inline data will be written at that memory location. "
},
{
"code": null,
"e": 28808,
"s": 28779,
"text": "Read and Write Operations – "
},
{
"code": null,
"e": 29247,
"s": 28808,
"text": "If the select line is in Reading mode then the Word/bit which is represented by the MAR will be available to the data lines and will get read.If the select line is in write mode then the data from the memory data register (MDR) will be sent to the respective cell which is addressed by the memory address register (MAR).With the help of the select line, we can select the desired data and we can perform read and write operations on it. "
},
{
"code": null,
"e": 29390,
"s": 29247,
"text": "If the select line is in Reading mode then the Word/bit which is represented by the MAR will be available to the data lines and will get read."
},
{
"code": null,
"e": 29569,
"s": 29390,
"text": "If the select line is in write mode then the data from the memory data register (MDR) will be sent to the respective cell which is addressed by the memory address register (MAR)."
},
{
"code": null,
"e": 29688,
"s": 29569,
"text": "With the help of the select line, we can select the desired data and we can perform read and write operations on it. "
},
{
"code": null,
"e": 29734,
"s": 29688,
"text": "Comparison between 2D & 2.5D Organizations – "
},
{
"code": null,
"e": 30087,
"s": 29734,
"text": "In 2D organization hardware is fixed but in 2.5D hardware changes.2D Organization requires more gates while 2.5D requires less.2D is more complex in comparison to the 2.5D organization.Error correction is not possible in the 2D organization but in 2.5D it could be done easily.2D is more difficult to fabricate in comparison to the 2.5D organization. "
},
{
"code": null,
"e": 30154,
"s": 30087,
"text": "In 2D organization hardware is fixed but in 2.5D hardware changes."
},
{
"code": null,
"e": 30216,
"s": 30154,
"text": "2D Organization requires more gates while 2.5D requires less."
},
{
"code": null,
"e": 30275,
"s": 30216,
"text": "2D is more complex in comparison to the 2.5D organization."
},
{
"code": null,
"e": 30368,
"s": 30275,
"text": "Error correction is not possible in the 2D organization but in 2.5D it could be done easily."
},
{
"code": null,
"e": 30444,
"s": 30368,
"text": "2D is more difficult to fabricate in comparison to the 2.5D organization. "
},
{
"code": null,
"e": 30472,
"s": 30446,
"text": "1716410060_ashutosh_verma"
},
{
"code": null,
"e": 30484,
"s": 30472,
"text": "meshubhamsr"
},
{
"code": null,
"e": 30495,
"s": 30484,
"text": "alokesh985"
},
{
"code": null,
"e": 30510,
"s": 30495,
"text": "kharedevansh01"
},
{
"code": null,
"e": 30529,
"s": 30510,
"text": "tanwarsinghvaibhav"
},
{
"code": null,
"e": 30547,
"s": 30529,
"text": "memory-management"
},
{
"code": null,
"e": 30584,
"s": 30547,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 30682,
"s": 30584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30691,
"s": 30682,
"text": "Comments"
},
{
"code": null,
"e": 30704,
"s": 30691,
"text": "Old Comments"
},
{
"code": null,
"e": 30744,
"s": 30704,
"text": "Addressing modes in 8085 microprocessor"
},
{
"code": null,
"e": 30785,
"s": 30744,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 30834,
"s": 30785,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 30870,
"s": 30834,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 30908,
"s": 30870,
"text": "8085 program to add two 8 bit numbers"
},
{
"code": null,
"e": 30949,
"s": 30908,
"text": "Program for Binary To Decimal Conversion"
},
{
"code": null,
"e": 30984,
"s": 30949,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 31005,
"s": 30984,
"text": "Architecture of 8086"
},
{
"code": null,
"e": 31061,
"s": 31005,
"text": "Difference between Von Neumann and Harvard Architecture"
}
] |
Running Apache Kafka on Windows 10 | by Bibhash Biswas | Towards Data Science
|
Kafka’s growth is exploding. More than one-third of all Fortune 500 companies use Kafka. These companies include the top travel companies, banks, eight of the top ten insurance companies, nine of the top ten telecom companies, and much more. LinkedIn, Microsoft, and Netflix process four-comma messages a day with Kafka (1,000,000,000,000).
Kafka is used for real-time streams of data, to collect big data, or to do real time analysis (or both). Kafka is used with in-memory microservices to provide durability and it can be used to feed events to CEP (complex event streaming systems) and IoT/IFTTT-style automation systems. — DZone
There are many articles on the internet on this topic but a lot of them are broken or just copy-paste from articles meant for Linux that doesn’t work on Windows. Though it's an easy installation there are some gotchas.
This article will help you to stay away from the pitfalls, and bring up Kafka on a Windows 10 platform.
Kafka depends on Zookeeper as its distributed messaging core. So the zookeeper server needs to be up and running first so Kafka server can connect to it.
Before you download Zookeeper and Kafka, make sure you have 7-zip installed on your system. (Great tool to work with tar and gz files.)
In this article, first, we’ll make sure we have some necessary tools. Then we’ll install, configure, and run Zookeeper. After that we’ll install, configure, and run Kafka.
So, let’s get to it.
Zookeeper and Kafka are written in Java so you’ll need JDK. Many sites will tell you to install JRE only. Don’t bother. Just install JDK. It comes with JRE. Then set your HOME and PATH variables. But first, 7-zip.
You can find 7-zip here —
www.7-zip.org
When you install 7-zip, make sure to add it to your right-click menu shortcuts. It’ll make your life easier.
It used to be free, and it still is except now you need to create an account with Oracle to be able to download this. Here’s the link-
www.oracle.com
JDK will first install itself and then it’ll ask you for the location where you want to install JRE.
The default install location is “C:\Program Files\...”
Normally it’s fine to put Java in there but best not to for your Kafka installation. Kafka was meant for Linux. I wouldn’t push it with Windows directory names containing spaces.
I put both my JDK and JRE in a path with no spaces. My install location is C:\Java
We’ll need to set PATHs for all of our installations. So we’ll be revisiting this a few times in this article. We’ll set two kinds of PATH variables — the User variable and the System variable. In the User variable, we’ll add the path to the install location, and in the system variable, we’ll set the path to the bin directory.
Type ‘Environment’ in your Windows search bar. It’ll come up with an option to Edit the Systems variable in the Control Panel. Click that and you’ll be in System Properties. Click on the button that says Environment Variables... on the lower right.
Under User variables which is the top box, click on New and add JAVA_HOME and JRE_HOME. For the value for JAVA_HOME, click on the Browse Directories button and navigate to where you installed JDK. I used C:\Java\jdk1.8.0_221\
For the value of your JRE_HOME, click on the Browse Directories button and navigate to where you installed JRE. For me, that is C:\Java\jre1.8.0_221\
In the System variable box, double click on the Path and add the following two entries at the end
%JAVA_HOME%\bin
%JRE_HOME%\bin
If you’ve set it up right, open a command prompt in any directory. (A quick way to do that is to go to any directory with your windows file explorer and then type ‘cmd’ (without the quotes) in the address bar of the file explorer. It’ll open up a prompt at that location.)
Navigate to a directory that’s different from your Java installation so you really know if your PATH variables are working.
Type java -version
You should see this-
C:\>java -versionjava version “1.8.0_221”Java(TM) SE Runtime Environment (build 1.8.0_221-b11)Java HotSpot(TM) 64-Bit Server VM (build 25.221-b11, mixed mode)
If you get something else like java is not recognized as an internal or external command, then your PATH is not set correctly. To make sure that it’s not a problem with the installation itself, you can go to the bin directory of the JDK and type in the above command. If it works from there but not from anywhere else, it means the system can’t find it.
For every command typed in the command prompt, your computer runs through the list in your PATH variables to find a match. That’s why errors like this are usually PATH problems.
Download the Zookeeper binary. Here is one of the mirrors to download from
Make sure to download the file that has bin in the name and not the other one. If you download the non-bin one then you’ll get an error when trying to start the server.
http://apache-mirror.8birdsvideo.com/zookeeper/stable/
Right-click on the file, and extract it at the same location using 7-zip. This will extract the tar file which is still not the real deal so it doesn’t matter where you extract this file.
For the next step, the location will matter:
Right-click on the tar file and extract it to a directory that doesn’t have spaces in the name. I put mine in C:\Apache\ So I end up with a directory like. so-
C:\Apache\apache-zookeeper-3.5.6-bin
As of this writing, the stable version of zookeeper is 3.5.6. Yours may be different.
Note the -bin appended to the name. If you don’t see this then you’ve downloaded and extracted the wrong file. Go back to the mirror.This is important otherwise when you start the Zookeeper server, you’ll get an error that looks like this
Error: Could not find or load main class org.apache.zookeeper.server.quorum.QuorumPeerMain
All the configurations happen in just one file- the configuration file, and it’s in the conf directory.
Go to the conf directory of your zookeeper install. For me, it’s at
C:\Apache\apache-zookeeper-3.5.6-bin\conf
Rename the zoo_sample.cfg file to zoo.cfg
Open it with a text editor.
In this file, you’ll see an entry called the dataDir with a value of /tmp. It pretty much tells you what to do
# the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just# example sakes.
Most all the articles on the net tell you to replace this line with something like dataDir=:\zookeeper-3.5.6\data
If you do that, you’ll run into an error like this-
ERROR— Unable to access datadir, exiting abnormallyUnable to create data directory :zookeeper-3.5.6data\version-2Unable to access datadir, exiting abnormally
To avoid this error, point your logs to a path which is one level up from the bin directory, like so-
dataDir=../logs
(it could be any level up or in the same directory. You can also type in an absolute windows path starting from root C:\\)
This will create a logs directory in your zookeeper install directory that’ll store the snapshots when you run the server.
The configuration is done. Let’s set up PATH variables so the system can find it from anywhere.
As before, start typing Environment in your Windows search bar. It’ll come up with an option to Edit the Systems variable in the Control Panel. Click on that and you’ll be in System Properties. Click on the button that says Environment Variables... on the lower right.
Under User variables which is the top box, click on New and add ZOOKEEPER_HOME. For the value, click on the Browse Directories button and navigate to where you installed Zookeeper. For me, that is C:\Apache\apache-zookeeper-3.5.6-bin
In the System variable box, double click on the Path and add the following at the end
%ZOOKEEPER_HOME%\bin
Open a command prompt in your zookeeper bin directory and type in
zkserver
It’ll start spewing out a whole bunch of messages. Some of the interesting ones to note are below. (I’ve cleaned up the verbiage for visual clarity). They look like this
2019–11–19 11:17:17,986 [myid:] — INFO -> for information
2019–11–19 11:17:17,986 [myid:] — WARN -> for warnings
myid is empty because I don’t have a myid file in my dataDir. Zookeeper keeps track of every machine in a cluster by their id. To assign an id to a machine, simply place a file name myid (without any extensions) that contains a single number. I’m running Zookeeper in a single server mode for development so setting an id is not necessary. But, if I create a file with the number 5 (arbitrary but needs to be unique if you have more than one machine in a cluster) then the command line would look like this-
2019–11–19 12:05:21,400 [myid:5] — INFO [main:FileSnap@83] — Reading snapshot ..\logs\version-2\snapshot.a6
Server environment:os.name=Windows 10Server environment:os.arch=amd64Server environment:os.version=10.0Server environment:user.name=Bivas BiswasServer environment:user.home=C:\Users\Bivas BiswasServer environment:user.dir=C:\Apache\apache-zookeeper-3.5.6-bin\binServer environment:os.memory.free=946MBServer environment:os.memory.max=14491MBServer environment:os.memory.total=977MBminSessionTimeout set to 4000maxSessionTimeout set to 40000Created server with tickTime 2000 minSessionTimeout 4000 maxSessionTimeout 40000 datadir ..\logs\version-2 snapdir ..\logs\version-2Logging initialized @5029ms to org.eclipse.jetty.util.log.Slf4jL
The reference to log4j in that last line is a reference to the logging infrastructure that zookeeper uses. You’ll also notice that it’s logging snapshots to the logs directory that we specified in the configuration file earlier.
Snapshotting: 0x0 to C:Apachezookeeper-3.5.6-binlogs\version-2\snapshot.0
After a few seconds of spewing data, it should come to these golden lines
Started AdminServer on address 0.0.0.0, port 8080 and command URL /commandsUsing org.apache.zookeeper.server.NIOServerCnxnFactory as server connection factoryConfiguring NIO connection handler with 10s sessionless connection timeout, 3 selector thread(s), 40 worker threads, and 64 kB direct buffers.binding to port 0.0.0.0/0.0.0.0:2181
Now Zookeeper server is running on localhost:2181. The AdminServer on port 8080 is a new addition. We can use that port on our browser to monitor zookeeper.
However, you can’t go to port 2181 where zookeeper is running. Zookeeper is for Kafka to use as a core kernel of a Kafka Cluster. If you navigate to that port on your browser, which will send some TCP traffic to it that it's not expecting, you’ll crash the server. This is what you’ll get —
Exception causing close of session 0x0: Len error 1195725856
So, that’s it. Your Zookeeper is up and running on Windows 10 without needing to use a docker composer or a Linux VM.
Kafka is a message broker. It lets you create topics that you can think of are like chat rooms. You post a message on that topic and people who are subscribed to the topic will receive the message. The recipients are called Consumers. The message posters are called Producers.
Kafka also comes with 2 more capabilities. One is Stream processing API which basically takes these messages and transforms them to a different value before the recipient gets it. This happens in real-time in real-time data streams.
The other is the Connector API that lets Kafka connect to databases or storage systems to store the data. This data can then be used for further processing by clusters like Hadoop, Map Reduce, etc. This can be happening in addition to the real-time delivery of messages to the consumers.
Kafka is an all in one solution today. Previously, you’d have needed a stream processing framework like Apache Storm to transform the stream but with Kafka’s native Stream API, we don’t necessarily need Storm as much as we used to. It depends on your use case and the topology that makes sense for you but nice to have options.
Download Kafka from here -
http://kafka.apache.org/downloads.html
Grab the Binary downloads. In that section, you might see multiple versions marked Scala x.xxx. If you’re using Scala as a client then grab the version that matches your Scala version. I’m using NodeJS as my client so it doesn’t matter which one I get. As of this writing, Apache recommends kafka_2.12–2.3.1.tgz so that’s the one I got.
Use 7-zip to extract the tgz to a tar file. Then use 7-zip to extract the tar file to a location that doesn’t have spaces in its path. I use C:\Apache, so after decompression, my Kafka live here -
C:\Apache\kafka_2.12–2.3.1
This article is getting long so I’m going to break this up into 2. Next, we’ll see how to set up and configure a Kafka server.
We’re not going to be setting any environment variables for Kafka. Kafka is the one looking for zookeeper and JDK. Even the producers and the consumers live within the Kafka ecosystem. They are not separate applications that’d be looking to find Kafka on your computer. In a nutshell, no environment vars to mess with.
However, there is the configuration file to set.
Go to your Kafka config directory. For me it’s at
C:\Apache\kafka_2.12–2.3.1\config
There is a sample server.properties file that we can start with.
For one broker we just need to set up this one file. If we need multiple brokers then duplicate this file once for each broker. For example, if you need 2 message brokers then you’ll end up with server.b1.properties and server.b2.properties.
In each file, you’ll change the following —
The broker id
# The id of the broker. This must be set to a unique integer for each broker.broker.id=0
If you’re just using 1 broker then leave it at 0. Nothing to change. If you have another broker then change the id in the other files so they are unique.
# The id of the broker. This must be set to a unique integer for each broker.broker.id=1
Change the log dirs. I keep mine to an absolute path. You can use any Windows-style pathing here
# A comma separated list of directories under which to store log fileslog.dirs=C:\Apache\kafka_2.12–2.3.1\logs
The replication factor is like RAID on a hard drive. It replicates the data from one broker into another broker for redundancy and fault-tolerance. For development, I’m going to keep this at 1
Browse through the fields in this file. You’ll notice the timeout values, partition values, and default Zookeeper port number which all would come in handy later for debugging if problems arise.
By default, Apache Kafka will run on port 9092 and Apache Zookeeper will run on port 2181.
With that our configuration for Kafka is done. Let’s fire up the server.
Make sure that Zookeeper server is still running.
Navigate to the bin directory in your Kafka install directory. There you’ll see a windows directory, go in there. That’s where all the awesome windows utilities are stored. For me, it’s here -
Fire up a new terminal window
C:\Apache\kafka_2.12–2.3.1\bin\windows
(If you forget to go into the windows directory, and just fire from the bin directory, the following command would just open up the shell file in Visual Studio Code instead of running the batch file)
kafka-server-start.bat C:\Apache\kafka_2.12–2.3.1\config\server.properties
You’ll see some results like these -
Client environment:java.compiler=<NA> (org.apache.zookeeper.ZooKeeper)Windows 10 (org.apache.zookeeper.ZooKeeper)Client environment:os.arch=amd64 (org.apache.zookeeper.ZooKeeper)Client environment:os.version=10.0 (org.apache.zookeeper.ZooKeeper)Client environment:user.name=Bivas Biswas Client environment:user.home=C:\Users\Bivas Biswas Client environment:user.dir=C:\Apache\kafka_2.12–2.3.1\bin\windows (org.apache.zookeeper.ZooKeeper)Initiating client connection, connectString=localhost:2181 sessionTimeout=6000 watcher=kafka.zookeeper.ZooKeeperClient$ZooKeeperClientWatcher$@57c758ac (org.apache.zookeeper.ZooKeeper)[ZooKeeperClient Kafka server] Waiting until connected. (kafka.zookeeper.ZooKeeperClient)
At this point if the server times out waiting for Zookeeper to respond, go to the command terminal where you’re running Zookeeper and hit enter. Sometimes if Zookeeper is idle for a while, I’ve seen Kafka timing out.
If all goes well, you’ll see some metadata dump from Group Coordinator and offset messages that look like this with a blinking waiting cursor
[GroupCoordinator 0]: Preparing to rebalance group console-consumer-83701 in state PreparingRebalance with old generation 1 (__consumer_offsets-10) (reason: removing member consumer-1–9bf4ef2d-97af-4e59–964e-5bb57b457289 on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)[GroupCoordinator 0]: Group console-consumer-83701 with generation 2 is now empty (__consumer_offsets-10) (kafka.coordinator.group.GroupCoordinator)
You’ll see some activity in your Zookeeper terminal. It might take a new snapshot and start a new log file. At this point your Kafka is up and running.
Couple things to keep in mind with Zookeeper —
The dataDir which we set up as the logs directory will start to fill up pretty fast with the snapshots.
In my tests, running Kafka for less than 15 minutes with one topic produced two 65MB snapshot files. These snapshots are transactional log files and they get written to every time a change in the node is detected.
Zookeeper will create duplicates at times when it combines a few log files into one larger file but it doesn’t clean up the old files. So clean this directory yourself. You can use zkTxnLogToolkit that's in the bin directory to configure log retention policy.
If you’re deploying on an EC2 instance on AWS, and you go with the free tier of t2.micro, the server won’t start.
This is because the default heap size of zookeeper and Kafka comes to about 1GB and the memory on a t2.micro is 1 GB so it’ll complain about insufficient memory space.
To avoid this error, run your Kafka on a t3.medium instance with 4GB memory instead of reducing the heap size in the config file.
There’s nothing more frustrating than following an article whose steps don’t work like it says it does. That’s the reason I started writing this in the first place while going through tons of broken articles and fixing the errors.
If you get any errors following these steps, let me know. Leave a comment below if you have trouble and I’ll get back to you.
|
[
{
"code": null,
"e": 513,
"s": 172,
"text": "Kafka’s growth is exploding. More than one-third of all Fortune 500 companies use Kafka. These companies include the top travel companies, banks, eight of the top ten insurance companies, nine of the top ten telecom companies, and much more. LinkedIn, Microsoft, and Netflix process four-comma messages a day with Kafka (1,000,000,000,000)."
},
{
"code": null,
"e": 806,
"s": 513,
"text": "Kafka is used for real-time streams of data, to collect big data, or to do real time analysis (or both). Kafka is used with in-memory microservices to provide durability and it can be used to feed events to CEP (complex event streaming systems) and IoT/IFTTT-style automation systems. — DZone"
},
{
"code": null,
"e": 1025,
"s": 806,
"text": "There are many articles on the internet on this topic but a lot of them are broken or just copy-paste from articles meant for Linux that doesn’t work on Windows. Though it's an easy installation there are some gotchas."
},
{
"code": null,
"e": 1129,
"s": 1025,
"text": "This article will help you to stay away from the pitfalls, and bring up Kafka on a Windows 10 platform."
},
{
"code": null,
"e": 1283,
"s": 1129,
"text": "Kafka depends on Zookeeper as its distributed messaging core. So the zookeeper server needs to be up and running first so Kafka server can connect to it."
},
{
"code": null,
"e": 1419,
"s": 1283,
"text": "Before you download Zookeeper and Kafka, make sure you have 7-zip installed on your system. (Great tool to work with tar and gz files.)"
},
{
"code": null,
"e": 1591,
"s": 1419,
"text": "In this article, first, we’ll make sure we have some necessary tools. Then we’ll install, configure, and run Zookeeper. After that we’ll install, configure, and run Kafka."
},
{
"code": null,
"e": 1612,
"s": 1591,
"text": "So, let’s get to it."
},
{
"code": null,
"e": 1826,
"s": 1612,
"text": "Zookeeper and Kafka are written in Java so you’ll need JDK. Many sites will tell you to install JRE only. Don’t bother. Just install JDK. It comes with JRE. Then set your HOME and PATH variables. But first, 7-zip."
},
{
"code": null,
"e": 1852,
"s": 1826,
"text": "You can find 7-zip here —"
},
{
"code": null,
"e": 1866,
"s": 1852,
"text": "www.7-zip.org"
},
{
"code": null,
"e": 1975,
"s": 1866,
"text": "When you install 7-zip, make sure to add it to your right-click menu shortcuts. It’ll make your life easier."
},
{
"code": null,
"e": 2110,
"s": 1975,
"text": "It used to be free, and it still is except now you need to create an account with Oracle to be able to download this. Here’s the link-"
},
{
"code": null,
"e": 2125,
"s": 2110,
"text": "www.oracle.com"
},
{
"code": null,
"e": 2226,
"s": 2125,
"text": "JDK will first install itself and then it’ll ask you for the location where you want to install JRE."
},
{
"code": null,
"e": 2281,
"s": 2226,
"text": "The default install location is “C:\\Program Files\\...”"
},
{
"code": null,
"e": 2460,
"s": 2281,
"text": "Normally it’s fine to put Java in there but best not to for your Kafka installation. Kafka was meant for Linux. I wouldn’t push it with Windows directory names containing spaces."
},
{
"code": null,
"e": 2543,
"s": 2460,
"text": "I put both my JDK and JRE in a path with no spaces. My install location is C:\\Java"
},
{
"code": null,
"e": 2872,
"s": 2543,
"text": "We’ll need to set PATHs for all of our installations. So we’ll be revisiting this a few times in this article. We’ll set two kinds of PATH variables — the User variable and the System variable. In the User variable, we’ll add the path to the install location, and in the system variable, we’ll set the path to the bin directory."
},
{
"code": null,
"e": 3121,
"s": 2872,
"text": "Type ‘Environment’ in your Windows search bar. It’ll come up with an option to Edit the Systems variable in the Control Panel. Click that and you’ll be in System Properties. Click on the button that says Environment Variables... on the lower right."
},
{
"code": null,
"e": 3347,
"s": 3121,
"text": "Under User variables which is the top box, click on New and add JAVA_HOME and JRE_HOME. For the value for JAVA_HOME, click on the Browse Directories button and navigate to where you installed JDK. I used C:\\Java\\jdk1.8.0_221\\"
},
{
"code": null,
"e": 3497,
"s": 3347,
"text": "For the value of your JRE_HOME, click on the Browse Directories button and navigate to where you installed JRE. For me, that is C:\\Java\\jre1.8.0_221\\"
},
{
"code": null,
"e": 3595,
"s": 3497,
"text": "In the System variable box, double click on the Path and add the following two entries at the end"
},
{
"code": null,
"e": 3611,
"s": 3595,
"text": "%JAVA_HOME%\\bin"
},
{
"code": null,
"e": 3626,
"s": 3611,
"text": "%JRE_HOME%\\bin"
},
{
"code": null,
"e": 3899,
"s": 3626,
"text": "If you’ve set it up right, open a command prompt in any directory. (A quick way to do that is to go to any directory with your windows file explorer and then type ‘cmd’ (without the quotes) in the address bar of the file explorer. It’ll open up a prompt at that location.)"
},
{
"code": null,
"e": 4023,
"s": 3899,
"text": "Navigate to a directory that’s different from your Java installation so you really know if your PATH variables are working."
},
{
"code": null,
"e": 4042,
"s": 4023,
"text": "Type java -version"
},
{
"code": null,
"e": 4063,
"s": 4042,
"text": "You should see this-"
},
{
"code": null,
"e": 4222,
"s": 4063,
"text": "C:\\>java -versionjava version “1.8.0_221”Java(TM) SE Runtime Environment (build 1.8.0_221-b11)Java HotSpot(TM) 64-Bit Server VM (build 25.221-b11, mixed mode)"
},
{
"code": null,
"e": 4576,
"s": 4222,
"text": "If you get something else like java is not recognized as an internal or external command, then your PATH is not set correctly. To make sure that it’s not a problem with the installation itself, you can go to the bin directory of the JDK and type in the above command. If it works from there but not from anywhere else, it means the system can’t find it."
},
{
"code": null,
"e": 4754,
"s": 4576,
"text": "For every command typed in the command prompt, your computer runs through the list in your PATH variables to find a match. That’s why errors like this are usually PATH problems."
},
{
"code": null,
"e": 4829,
"s": 4754,
"text": "Download the Zookeeper binary. Here is one of the mirrors to download from"
},
{
"code": null,
"e": 4998,
"s": 4829,
"text": "Make sure to download the file that has bin in the name and not the other one. If you download the non-bin one then you’ll get an error when trying to start the server."
},
{
"code": null,
"e": 5053,
"s": 4998,
"text": "http://apache-mirror.8birdsvideo.com/zookeeper/stable/"
},
{
"code": null,
"e": 5241,
"s": 5053,
"text": "Right-click on the file, and extract it at the same location using 7-zip. This will extract the tar file which is still not the real deal so it doesn’t matter where you extract this file."
},
{
"code": null,
"e": 5286,
"s": 5241,
"text": "For the next step, the location will matter:"
},
{
"code": null,
"e": 5446,
"s": 5286,
"text": "Right-click on the tar file and extract it to a directory that doesn’t have spaces in the name. I put mine in C:\\Apache\\ So I end up with a directory like. so-"
},
{
"code": null,
"e": 5483,
"s": 5446,
"text": "C:\\Apache\\apache-zookeeper-3.5.6-bin"
},
{
"code": null,
"e": 5569,
"s": 5483,
"text": "As of this writing, the stable version of zookeeper is 3.5.6. Yours may be different."
},
{
"code": null,
"e": 5808,
"s": 5569,
"text": "Note the -bin appended to the name. If you don’t see this then you’ve downloaded and extracted the wrong file. Go back to the mirror.This is important otherwise when you start the Zookeeper server, you’ll get an error that looks like this"
},
{
"code": null,
"e": 5899,
"s": 5808,
"text": "Error: Could not find or load main class org.apache.zookeeper.server.quorum.QuorumPeerMain"
},
{
"code": null,
"e": 6003,
"s": 5899,
"text": "All the configurations happen in just one file- the configuration file, and it’s in the conf directory."
},
{
"code": null,
"e": 6071,
"s": 6003,
"text": "Go to the conf directory of your zookeeper install. For me, it’s at"
},
{
"code": null,
"e": 6113,
"s": 6071,
"text": "C:\\Apache\\apache-zookeeper-3.5.6-bin\\conf"
},
{
"code": null,
"e": 6155,
"s": 6113,
"text": "Rename the zoo_sample.cfg file to zoo.cfg"
},
{
"code": null,
"e": 6183,
"s": 6155,
"text": "Open it with a text editor."
},
{
"code": null,
"e": 6294,
"s": 6183,
"text": "In this file, you’ll see an entry called the dataDir with a value of /tmp. It pretty much tells you what to do"
},
{
"code": null,
"e": 6405,
"s": 6294,
"text": "# the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just# example sakes."
},
{
"code": null,
"e": 6519,
"s": 6405,
"text": "Most all the articles on the net tell you to replace this line with something like dataDir=:\\zookeeper-3.5.6\\data"
},
{
"code": null,
"e": 6571,
"s": 6519,
"text": "If you do that, you’ll run into an error like this-"
},
{
"code": null,
"e": 6729,
"s": 6571,
"text": "ERROR— Unable to access datadir, exiting abnormallyUnable to create data directory :zookeeper-3.5.6data\\version-2Unable to access datadir, exiting abnormally"
},
{
"code": null,
"e": 6831,
"s": 6729,
"text": "To avoid this error, point your logs to a path which is one level up from the bin directory, like so-"
},
{
"code": null,
"e": 6847,
"s": 6831,
"text": "dataDir=../logs"
},
{
"code": null,
"e": 6970,
"s": 6847,
"text": "(it could be any level up or in the same directory. You can also type in an absolute windows path starting from root C:\\\\)"
},
{
"code": null,
"e": 7093,
"s": 6970,
"text": "This will create a logs directory in your zookeeper install directory that’ll store the snapshots when you run the server."
},
{
"code": null,
"e": 7189,
"s": 7093,
"text": "The configuration is done. Let’s set up PATH variables so the system can find it from anywhere."
},
{
"code": null,
"e": 7458,
"s": 7189,
"text": "As before, start typing Environment in your Windows search bar. It’ll come up with an option to Edit the Systems variable in the Control Panel. Click on that and you’ll be in System Properties. Click on the button that says Environment Variables... on the lower right."
},
{
"code": null,
"e": 7692,
"s": 7458,
"text": "Under User variables which is the top box, click on New and add ZOOKEEPER_HOME. For the value, click on the Browse Directories button and navigate to where you installed Zookeeper. For me, that is C:\\Apache\\apache-zookeeper-3.5.6-bin"
},
{
"code": null,
"e": 7778,
"s": 7692,
"text": "In the System variable box, double click on the Path and add the following at the end"
},
{
"code": null,
"e": 7799,
"s": 7778,
"text": "%ZOOKEEPER_HOME%\\bin"
},
{
"code": null,
"e": 7865,
"s": 7799,
"text": "Open a command prompt in your zookeeper bin directory and type in"
},
{
"code": null,
"e": 7874,
"s": 7865,
"text": "zkserver"
},
{
"code": null,
"e": 8044,
"s": 7874,
"text": "It’ll start spewing out a whole bunch of messages. Some of the interesting ones to note are below. (I’ve cleaned up the verbiage for visual clarity). They look like this"
},
{
"code": null,
"e": 8102,
"s": 8044,
"text": "2019–11–19 11:17:17,986 [myid:] — INFO -> for information"
},
{
"code": null,
"e": 8157,
"s": 8102,
"text": "2019–11–19 11:17:17,986 [myid:] — WARN -> for warnings"
},
{
"code": null,
"e": 8665,
"s": 8157,
"text": "myid is empty because I don’t have a myid file in my dataDir. Zookeeper keeps track of every machine in a cluster by their id. To assign an id to a machine, simply place a file name myid (without any extensions) that contains a single number. I’m running Zookeeper in a single server mode for development so setting an id is not necessary. But, if I create a file with the number 5 (arbitrary but needs to be unique if you have more than one machine in a cluster) then the command line would look like this-"
},
{
"code": null,
"e": 8773,
"s": 8665,
"text": "2019–11–19 12:05:21,400 [myid:5] — INFO [main:FileSnap@83] — Reading snapshot ..\\logs\\version-2\\snapshot.a6"
},
{
"code": null,
"e": 9410,
"s": 8773,
"text": "Server environment:os.name=Windows 10Server environment:os.arch=amd64Server environment:os.version=10.0Server environment:user.name=Bivas BiswasServer environment:user.home=C:\\Users\\Bivas BiswasServer environment:user.dir=C:\\Apache\\apache-zookeeper-3.5.6-bin\\binServer environment:os.memory.free=946MBServer environment:os.memory.max=14491MBServer environment:os.memory.total=977MBminSessionTimeout set to 4000maxSessionTimeout set to 40000Created server with tickTime 2000 minSessionTimeout 4000 maxSessionTimeout 40000 datadir ..\\logs\\version-2 snapdir ..\\logs\\version-2Logging initialized @5029ms to org.eclipse.jetty.util.log.Slf4jL"
},
{
"code": null,
"e": 9639,
"s": 9410,
"text": "The reference to log4j in that last line is a reference to the logging infrastructure that zookeeper uses. You’ll also notice that it’s logging snapshots to the logs directory that we specified in the configuration file earlier."
},
{
"code": null,
"e": 9713,
"s": 9639,
"text": "Snapshotting: 0x0 to C:Apachezookeeper-3.5.6-binlogs\\version-2\\snapshot.0"
},
{
"code": null,
"e": 9787,
"s": 9713,
"text": "After a few seconds of spewing data, it should come to these golden lines"
},
{
"code": null,
"e": 10124,
"s": 9787,
"text": "Started AdminServer on address 0.0.0.0, port 8080 and command URL /commandsUsing org.apache.zookeeper.server.NIOServerCnxnFactory as server connection factoryConfiguring NIO connection handler with 10s sessionless connection timeout, 3 selector thread(s), 40 worker threads, and 64 kB direct buffers.binding to port 0.0.0.0/0.0.0.0:2181"
},
{
"code": null,
"e": 10281,
"s": 10124,
"text": "Now Zookeeper server is running on localhost:2181. The AdminServer on port 8080 is a new addition. We can use that port on our browser to monitor zookeeper."
},
{
"code": null,
"e": 10572,
"s": 10281,
"text": "However, you can’t go to port 2181 where zookeeper is running. Zookeeper is for Kafka to use as a core kernel of a Kafka Cluster. If you navigate to that port on your browser, which will send some TCP traffic to it that it's not expecting, you’ll crash the server. This is what you’ll get —"
},
{
"code": null,
"e": 10633,
"s": 10572,
"text": "Exception causing close of session 0x0: Len error 1195725856"
},
{
"code": null,
"e": 10751,
"s": 10633,
"text": "So, that’s it. Your Zookeeper is up and running on Windows 10 without needing to use a docker composer or a Linux VM."
},
{
"code": null,
"e": 11028,
"s": 10751,
"text": "Kafka is a message broker. It lets you create topics that you can think of are like chat rooms. You post a message on that topic and people who are subscribed to the topic will receive the message. The recipients are called Consumers. The message posters are called Producers."
},
{
"code": null,
"e": 11261,
"s": 11028,
"text": "Kafka also comes with 2 more capabilities. One is Stream processing API which basically takes these messages and transforms them to a different value before the recipient gets it. This happens in real-time in real-time data streams."
},
{
"code": null,
"e": 11549,
"s": 11261,
"text": "The other is the Connector API that lets Kafka connect to databases or storage systems to store the data. This data can then be used for further processing by clusters like Hadoop, Map Reduce, etc. This can be happening in addition to the real-time delivery of messages to the consumers."
},
{
"code": null,
"e": 11877,
"s": 11549,
"text": "Kafka is an all in one solution today. Previously, you’d have needed a stream processing framework like Apache Storm to transform the stream but with Kafka’s native Stream API, we don’t necessarily need Storm as much as we used to. It depends on your use case and the topology that makes sense for you but nice to have options."
},
{
"code": null,
"e": 11904,
"s": 11877,
"text": "Download Kafka from here -"
},
{
"code": null,
"e": 11943,
"s": 11904,
"text": "http://kafka.apache.org/downloads.html"
},
{
"code": null,
"e": 12280,
"s": 11943,
"text": "Grab the Binary downloads. In that section, you might see multiple versions marked Scala x.xxx. If you’re using Scala as a client then grab the version that matches your Scala version. I’m using NodeJS as my client so it doesn’t matter which one I get. As of this writing, Apache recommends kafka_2.12–2.3.1.tgz so that’s the one I got."
},
{
"code": null,
"e": 12477,
"s": 12280,
"text": "Use 7-zip to extract the tgz to a tar file. Then use 7-zip to extract the tar file to a location that doesn’t have spaces in its path. I use C:\\Apache, so after decompression, my Kafka live here -"
},
{
"code": null,
"e": 12504,
"s": 12477,
"text": "C:\\Apache\\kafka_2.12–2.3.1"
},
{
"code": null,
"e": 12631,
"s": 12504,
"text": "This article is getting long so I’m going to break this up into 2. Next, we’ll see how to set up and configure a Kafka server."
},
{
"code": null,
"e": 12950,
"s": 12631,
"text": "We’re not going to be setting any environment variables for Kafka. Kafka is the one looking for zookeeper and JDK. Even the producers and the consumers live within the Kafka ecosystem. They are not separate applications that’d be looking to find Kafka on your computer. In a nutshell, no environment vars to mess with."
},
{
"code": null,
"e": 12999,
"s": 12950,
"text": "However, there is the configuration file to set."
},
{
"code": null,
"e": 13049,
"s": 12999,
"text": "Go to your Kafka config directory. For me it’s at"
},
{
"code": null,
"e": 13083,
"s": 13049,
"text": "C:\\Apache\\kafka_2.12–2.3.1\\config"
},
{
"code": null,
"e": 13148,
"s": 13083,
"text": "There is a sample server.properties file that we can start with."
},
{
"code": null,
"e": 13390,
"s": 13148,
"text": "For one broker we just need to set up this one file. If we need multiple brokers then duplicate this file once for each broker. For example, if you need 2 message brokers then you’ll end up with server.b1.properties and server.b2.properties."
},
{
"code": null,
"e": 13434,
"s": 13390,
"text": "In each file, you’ll change the following —"
},
{
"code": null,
"e": 13448,
"s": 13434,
"text": "The broker id"
},
{
"code": null,
"e": 13537,
"s": 13448,
"text": "# The id of the broker. This must be set to a unique integer for each broker.broker.id=0"
},
{
"code": null,
"e": 13691,
"s": 13537,
"text": "If you’re just using 1 broker then leave it at 0. Nothing to change. If you have another broker then change the id in the other files so they are unique."
},
{
"code": null,
"e": 13780,
"s": 13691,
"text": "# The id of the broker. This must be set to a unique integer for each broker.broker.id=1"
},
{
"code": null,
"e": 13877,
"s": 13780,
"text": "Change the log dirs. I keep mine to an absolute path. You can use any Windows-style pathing here"
},
{
"code": null,
"e": 13988,
"s": 13877,
"text": "# A comma separated list of directories under which to store log fileslog.dirs=C:\\Apache\\kafka_2.12–2.3.1\\logs"
},
{
"code": null,
"e": 14181,
"s": 13988,
"text": "The replication factor is like RAID on a hard drive. It replicates the data from one broker into another broker for redundancy and fault-tolerance. For development, I’m going to keep this at 1"
},
{
"code": null,
"e": 14376,
"s": 14181,
"text": "Browse through the fields in this file. You’ll notice the timeout values, partition values, and default Zookeeper port number which all would come in handy later for debugging if problems arise."
},
{
"code": null,
"e": 14467,
"s": 14376,
"text": "By default, Apache Kafka will run on port 9092 and Apache Zookeeper will run on port 2181."
},
{
"code": null,
"e": 14540,
"s": 14467,
"text": "With that our configuration for Kafka is done. Let’s fire up the server."
},
{
"code": null,
"e": 14590,
"s": 14540,
"text": "Make sure that Zookeeper server is still running."
},
{
"code": null,
"e": 14783,
"s": 14590,
"text": "Navigate to the bin directory in your Kafka install directory. There you’ll see a windows directory, go in there. That’s where all the awesome windows utilities are stored. For me, it’s here -"
},
{
"code": null,
"e": 14813,
"s": 14783,
"text": "Fire up a new terminal window"
},
{
"code": null,
"e": 14852,
"s": 14813,
"text": "C:\\Apache\\kafka_2.12–2.3.1\\bin\\windows"
},
{
"code": null,
"e": 15052,
"s": 14852,
"text": "(If you forget to go into the windows directory, and just fire from the bin directory, the following command would just open up the shell file in Visual Studio Code instead of running the batch file)"
},
{
"code": null,
"e": 15127,
"s": 15052,
"text": "kafka-server-start.bat C:\\Apache\\kafka_2.12–2.3.1\\config\\server.properties"
},
{
"code": null,
"e": 15164,
"s": 15127,
"text": "You’ll see some results like these -"
},
{
"code": null,
"e": 15875,
"s": 15164,
"text": "Client environment:java.compiler=<NA> (org.apache.zookeeper.ZooKeeper)Windows 10 (org.apache.zookeeper.ZooKeeper)Client environment:os.arch=amd64 (org.apache.zookeeper.ZooKeeper)Client environment:os.version=10.0 (org.apache.zookeeper.ZooKeeper)Client environment:user.name=Bivas Biswas Client environment:user.home=C:\\Users\\Bivas Biswas Client environment:user.dir=C:\\Apache\\kafka_2.12–2.3.1\\bin\\windows (org.apache.zookeeper.ZooKeeper)Initiating client connection, connectString=localhost:2181 sessionTimeout=6000 watcher=kafka.zookeeper.ZooKeeperClient$ZooKeeperClientWatcher$@57c758ac (org.apache.zookeeper.ZooKeeper)[ZooKeeperClient Kafka server] Waiting until connected. (kafka.zookeeper.ZooKeeperClient)"
},
{
"code": null,
"e": 16092,
"s": 15875,
"text": "At this point if the server times out waiting for Zookeeper to respond, go to the command terminal where you’re running Zookeeper and hit enter. Sometimes if Zookeeper is idle for a while, I’ve seen Kafka timing out."
},
{
"code": null,
"e": 16234,
"s": 16092,
"text": "If all goes well, you’ll see some metadata dump from Group Coordinator and offset messages that look like this with a blinking waiting cursor"
},
{
"code": null,
"e": 16671,
"s": 16234,
"text": "[GroupCoordinator 0]: Preparing to rebalance group console-consumer-83701 in state PreparingRebalance with old generation 1 (__consumer_offsets-10) (reason: removing member consumer-1–9bf4ef2d-97af-4e59–964e-5bb57b457289 on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)[GroupCoordinator 0]: Group console-consumer-83701 with generation 2 is now empty (__consumer_offsets-10) (kafka.coordinator.group.GroupCoordinator)"
},
{
"code": null,
"e": 16823,
"s": 16671,
"text": "You’ll see some activity in your Zookeeper terminal. It might take a new snapshot and start a new log file. At this point your Kafka is up and running."
},
{
"code": null,
"e": 16870,
"s": 16823,
"text": "Couple things to keep in mind with Zookeeper —"
},
{
"code": null,
"e": 16974,
"s": 16870,
"text": "The dataDir which we set up as the logs directory will start to fill up pretty fast with the snapshots."
},
{
"code": null,
"e": 17188,
"s": 16974,
"text": "In my tests, running Kafka for less than 15 minutes with one topic produced two 65MB snapshot files. These snapshots are transactional log files and they get written to every time a change in the node is detected."
},
{
"code": null,
"e": 17448,
"s": 17188,
"text": "Zookeeper will create duplicates at times when it combines a few log files into one larger file but it doesn’t clean up the old files. So clean this directory yourself. You can use zkTxnLogToolkit that's in the bin directory to configure log retention policy."
},
{
"code": null,
"e": 17562,
"s": 17448,
"text": "If you’re deploying on an EC2 instance on AWS, and you go with the free tier of t2.micro, the server won’t start."
},
{
"code": null,
"e": 17730,
"s": 17562,
"text": "This is because the default heap size of zookeeper and Kafka comes to about 1GB and the memory on a t2.micro is 1 GB so it’ll complain about insufficient memory space."
},
{
"code": null,
"e": 17860,
"s": 17730,
"text": "To avoid this error, run your Kafka on a t3.medium instance with 4GB memory instead of reducing the heap size in the config file."
},
{
"code": null,
"e": 18091,
"s": 17860,
"text": "There’s nothing more frustrating than following an article whose steps don’t work like it says it does. That’s the reason I started writing this in the first place while going through tons of broken articles and fixing the errors."
}
] |
Element Type Selector in CSS
|
The CSS element type selector is used to select all elements of a type. The syntax for CSS element type selector is as follows
element {
/*declarations*/
}
The following examples illustrate CSS element type selector
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
li {
list-style: none;
margin: 5px;
border-bottom-style: dotted;
}
div {
box-shadow: inset 0 0 8px plum;
padding: 36px;
}
</style>
</head>
<body>
<div>
<pre> \(╪)(╪) /</pre>
<ul>
<li></li>
<li></li>
</ul>
</div>
</body>
</html>
This gives the following output −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
li {
text-align: center;
list-style: none;
margin: 5px;
padding: 5px;
box-shadow: inset 0 0 15px yellowgreen;
}
div {
box-shadow: inset 0 0 8px orange;
padding: 36px;
width: 30%;
border-radius: 50%;
}
</style>
</head>
<body>
<div>
<ul>
<li>Hello</li>
<li>Guys</li>
</ul>
</div>
</body>
</html>
This gives the following output −
|
[
{
"code": null,
"e": 1189,
"s": 1062,
"text": "The CSS element type selector is used to select all elements of a type. The syntax for CSS element type selector is as follows"
},
{
"code": null,
"e": 1221,
"s": 1189,
"text": "element {\n /*declarations*/\n}"
},
{
"code": null,
"e": 1281,
"s": 1221,
"text": "The following examples illustrate CSS element type selector"
},
{
"code": null,
"e": 1292,
"s": 1281,
"text": " Live Demo"
},
{
"code": null,
"e": 1573,
"s": 1292,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nli {\n list-style: none;\n margin: 5px;\n border-bottom-style: dotted;\n}\ndiv {\n box-shadow: inset 0 0 8px plum;\n padding: 36px;\n}\n</style>\n</head>\n<body>\n<div>\n<pre> \\(╪)(╪) /</pre>\n<ul>\n<li></li>\n<li></li>\n</ul>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 1607,
"s": 1573,
"text": "This gives the following output −"
},
{
"code": null,
"e": 1618,
"s": 1607,
"text": " Live Demo"
},
{
"code": null,
"e": 1977,
"s": 1618,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nli {\n text-align: center;\n list-style: none;\n margin: 5px;\n padding: 5px;\n box-shadow: inset 0 0 15px yellowgreen;\n}\ndiv {\n box-shadow: inset 0 0 8px orange;\n padding: 36px;\n width: 30%;\n border-radius: 50%;\n}\n</style>\n</head>\n<body>\n<div>\n<ul>\n<li>Hello</li>\n<li>Guys</li>\n</ul>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 2011,
"s": 1977,
"text": "This gives the following output −"
}
] |
Can we iteratively import python modules inside a for loop?
|
Yes you can iteratively import python modules inside a for loop. You need to have a list of modules you want to import as strings. You can use the inbuilt importlib.import_module(module_name) to import the modules. For example,
>>> import importlib
>>> modnames = ["os", "sys", "math"]
>>> for lib in modnames:
... globals()[lib] = importlib.import_module(lib)
The globals() call returns a dict. We can set the lib key for each library as the object returned to us on import of a module.
|
[
{
"code": null,
"e": 1290,
"s": 1062,
"text": "Yes you can iteratively import python modules inside a for loop. You need to have a list of modules you want to import as strings. You can use the inbuilt importlib.import_module(module_name) to import the modules. For example,"
},
{
"code": null,
"e": 1427,
"s": 1290,
"text": ">>> import importlib\n>>> modnames = [\"os\", \"sys\", \"math\"]\n>>> for lib in modnames:\n... globals()[lib] = importlib.import_module(lib)"
},
{
"code": null,
"e": 1554,
"s": 1427,
"text": "The globals() call returns a dict. We can set the lib key for each library as the object returned to us on import of a module."
}
] |
AWT ActionEvent Class
|
This class is defined in java.awt.event package. The ActionEvent is generated when button is clicked or the item of a list is double clicked.
Following is the declaration for java.awt.event.ActionEvent class:
public class ActionEvent
extends AWTEvent
Following are the fields for java.awt.event.ActionEvent class:
static int ACTION_FIRST -- The first number in the range of ids used for action events.
static int ACTION_FIRST -- The first number in the range of ids used for action events.
static int ACTION_LAST -- The last number in the range of ids used for action events.
static int ACTION_LAST -- The last number in the range of ids used for action events.
static int ACTION_PERFORMED -- This event id indicates that a meaningful action occured.
static int ACTION_PERFORMED -- This event id indicates that a meaningful action occured.
static int ALT_MASK -- The alt modifier.
static int ALT_MASK -- The alt modifier.
static int CTRL_MASK -- The control modifier.
static int CTRL_MASK -- The control modifier.
static int META_MASK -- The meta modifier.
static int META_MASK -- The meta modifier.
static int SHIFT_MASK -- The shift modifier.
static int SHIFT_MASK -- The shift modifier.
ActionEvent(java.lang.Object source, int id, java.lang.String command)
Constructs an ActionEvent object.
ActionEvent(java.lang.Object source, int id, java.lang.String command, int modifiers)
Constructs an ActionEvent object with modifier keys.
ActionEvent(java.lang.Object source, int id, java.lang.String command, long when, int modifiers)
Constructs an ActionEvent object with the specified modifier keys and timestamp.
java.lang.String getActionCommand()
Returns the command string associated with this action.
int getModifiers()
Returns the modifier keys held down during this action event.
long getWhen()
Returns the timestamp of when this event occurred.
java.lang.String paramString()
Returns a parameter string identifying this action event.
This class inherits methods from the following classes:
java.awt.AWTEvent
java.awt.AWTEvent
java.util.EventObject
java.util.EventObject
java.lang.Object
java.lang.Object
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1889,
"s": 1747,
"text": "This class is defined in java.awt.event package. The ActionEvent is generated when button is clicked or the item of a list is double clicked."
},
{
"code": null,
"e": 1956,
"s": 1889,
"text": "Following is the declaration for java.awt.event.ActionEvent class:"
},
{
"code": null,
"e": 2001,
"s": 1956,
"text": "public class ActionEvent\n extends AWTEvent"
},
{
"code": null,
"e": 2064,
"s": 2001,
"text": "Following are the fields for java.awt.event.ActionEvent class:"
},
{
"code": null,
"e": 2152,
"s": 2064,
"text": "static int ACTION_FIRST -- The first number in the range of ids used for action events."
},
{
"code": null,
"e": 2240,
"s": 2152,
"text": "static int ACTION_FIRST -- The first number in the range of ids used for action events."
},
{
"code": null,
"e": 2327,
"s": 2240,
"text": "static int ACTION_LAST -- The last number in the range of ids used for action events."
},
{
"code": null,
"e": 2414,
"s": 2327,
"text": "static int ACTION_LAST -- The last number in the range of ids used for action events."
},
{
"code": null,
"e": 2504,
"s": 2414,
"text": "static int ACTION_PERFORMED -- This event id indicates that a meaningful action occured."
},
{
"code": null,
"e": 2594,
"s": 2504,
"text": "static int ACTION_PERFORMED -- This event id indicates that a meaningful action occured."
},
{
"code": null,
"e": 2636,
"s": 2594,
"text": "static int ALT_MASK -- The alt modifier."
},
{
"code": null,
"e": 2678,
"s": 2636,
"text": "static int ALT_MASK -- The alt modifier."
},
{
"code": null,
"e": 2725,
"s": 2678,
"text": "static int CTRL_MASK -- The control modifier."
},
{
"code": null,
"e": 2772,
"s": 2725,
"text": "static int CTRL_MASK -- The control modifier."
},
{
"code": null,
"e": 2816,
"s": 2772,
"text": "static int META_MASK -- The meta modifier."
},
{
"code": null,
"e": 2860,
"s": 2816,
"text": "static int META_MASK -- The meta modifier."
},
{
"code": null,
"e": 2906,
"s": 2860,
"text": "static int SHIFT_MASK -- The shift modifier."
},
{
"code": null,
"e": 2952,
"s": 2906,
"text": "static int SHIFT_MASK -- The shift modifier."
},
{
"code": null,
"e": 3023,
"s": 2952,
"text": "ActionEvent(java.lang.Object source, int id, java.lang.String command)"
},
{
"code": null,
"e": 3057,
"s": 3023,
"text": "Constructs an ActionEvent object."
},
{
"code": null,
"e": 3143,
"s": 3057,
"text": "ActionEvent(java.lang.Object source, int id, java.lang.String command, int modifiers)"
},
{
"code": null,
"e": 3196,
"s": 3143,
"text": "Constructs an ActionEvent object with modifier keys."
},
{
"code": null,
"e": 3293,
"s": 3196,
"text": "ActionEvent(java.lang.Object source, int id, java.lang.String command, long when, int modifiers)"
},
{
"code": null,
"e": 3374,
"s": 3293,
"text": "Constructs an ActionEvent object with the specified modifier keys and timestamp."
},
{
"code": null,
"e": 3410,
"s": 3374,
"text": "java.lang.String getActionCommand()"
},
{
"code": null,
"e": 3466,
"s": 3410,
"text": "Returns the command string associated with this action."
},
{
"code": null,
"e": 3485,
"s": 3466,
"text": "int getModifiers()"
},
{
"code": null,
"e": 3547,
"s": 3485,
"text": "Returns the modifier keys held down during this action event."
},
{
"code": null,
"e": 3562,
"s": 3547,
"text": "long getWhen()"
},
{
"code": null,
"e": 3613,
"s": 3562,
"text": "Returns the timestamp of when this event occurred."
},
{
"code": null,
"e": 3644,
"s": 3613,
"text": "java.lang.String paramString()"
},
{
"code": null,
"e": 3702,
"s": 3644,
"text": "Returns a parameter string identifying this action event."
},
{
"code": null,
"e": 3758,
"s": 3702,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 3776,
"s": 3758,
"text": "java.awt.AWTEvent"
},
{
"code": null,
"e": 3794,
"s": 3776,
"text": "java.awt.AWTEvent"
},
{
"code": null,
"e": 3816,
"s": 3794,
"text": "java.util.EventObject"
},
{
"code": null,
"e": 3838,
"s": 3816,
"text": "java.util.EventObject"
},
{
"code": null,
"e": 3855,
"s": 3838,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3872,
"s": 3855,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3905,
"s": 3872,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3913,
"s": 3905,
"text": " EduOLC"
},
{
"code": null,
"e": 3920,
"s": 3913,
"text": " Print"
},
{
"code": null,
"e": 3931,
"s": 3920,
"text": " Add Notes"
}
] |
Python program to replace every Nth character in String - GeeksforGeeks
|
21 Apr, 2021
Given a string, the task is to write a Python program to replace every Nth character in a string by the given value K.
Examples:
Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘$’, N = 5
Output : geeks$orge$ks i$ bes$ for$all $eeks
Explanation : Every 5th character is converted to $.
Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘*’, N = 5
Output : geeks*orge*ks i* bes* for*all *eeks
Explanation : Every 5th occurrence is converted to *.
Method 1 : Using loop and enumerate()
In this, we perform an iteration of each character and check if its Nth by performing modulo, i.e finding remainder by N. If its Nth occurrence, the character is replaced by K.
Example
Python3
# initializing stringtest_str = "geeksforgeeks is best for all geeks" # printing original stringprint("The original string is : " + str(test_str)) # initializing KK = '$' # initializing NN = 5 res = ''for idx, ele in enumerate(test_str): # add K if idx is multiple of N if idx % N == 0 and idx != 0: res = res + K else: res = res + ele # printing resultprint("String after replacement : " + str(res))
Output:
The original string is : geeksforgeeks is best for all geeks
String after replacement : geeks$orge$ks i$ bes$ for$all $eeks
Method 2 : Using generator expression, join() and enumerate()
In this, the construction of string happens using join(). The enumerate(), helps to get required indices. The generator expression provides a shorthand approach to this problem.
Example
Python3
# initializing stringtest_str = "geeksforgeeks is best for all geeks" # printing original stringprint("The original string is : " + str(test_str)) # initializing KK = '$' # initializing NN = 5 res = ''.join(ele if idx % N or idx == 0 else K for idx, ele in enumerate(test_str)) # printing resultprint("String after replacement : " + str(res))
Output:
The original string is : geeksforgeeks is best for all geeks
String after replacement : geeks$orge$ks i$ bes$ for$all $eeks
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 24411,
"s": 24292,
"text": "Given a string, the task is to write a Python program to replace every Nth character in a string by the given value K."
},
{
"code": null,
"e": 24421,
"s": 24411,
"text": "Examples:"
},
{
"code": null,
"e": 24494,
"s": 24421,
"text": "Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘$’, N = 5"
},
{
"code": null,
"e": 24539,
"s": 24494,
"text": "Output : geeks$orge$ks i$ bes$ for$all $eeks"
},
{
"code": null,
"e": 24592,
"s": 24539,
"text": "Explanation : Every 5th character is converted to $."
},
{
"code": null,
"e": 24665,
"s": 24592,
"text": "Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘*’, N = 5"
},
{
"code": null,
"e": 24710,
"s": 24665,
"text": "Output : geeks*orge*ks i* bes* for*all *eeks"
},
{
"code": null,
"e": 24764,
"s": 24710,
"text": "Explanation : Every 5th occurrence is converted to *."
},
{
"code": null,
"e": 24802,
"s": 24764,
"text": "Method 1 : Using loop and enumerate()"
},
{
"code": null,
"e": 24979,
"s": 24802,
"text": "In this, we perform an iteration of each character and check if its Nth by performing modulo, i.e finding remainder by N. If its Nth occurrence, the character is replaced by K."
},
{
"code": null,
"e": 24987,
"s": 24979,
"text": "Example"
},
{
"code": null,
"e": 24995,
"s": 24987,
"text": "Python3"
},
{
"code": "# initializing stringtest_str = \"geeksforgeeks is best for all geeks\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing KK = '$' # initializing NN = 5 res = ''for idx, ele in enumerate(test_str): # add K if idx is multiple of N if idx % N == 0 and idx != 0: res = res + K else: res = res + ele # printing resultprint(\"String after replacement : \" + str(res))",
"e": 25426,
"s": 24995,
"text": null
},
{
"code": null,
"e": 25434,
"s": 25426,
"text": "Output:"
},
{
"code": null,
"e": 25495,
"s": 25434,
"text": "The original string is : geeksforgeeks is best for all geeks"
},
{
"code": null,
"e": 25558,
"s": 25495,
"text": "String after replacement : geeks$orge$ks i$ bes$ for$all $eeks"
},
{
"code": null,
"e": 25620,
"s": 25558,
"text": "Method 2 : Using generator expression, join() and enumerate()"
},
{
"code": null,
"e": 25798,
"s": 25620,
"text": "In this, the construction of string happens using join(). The enumerate(), helps to get required indices. The generator expression provides a shorthand approach to this problem."
},
{
"code": null,
"e": 25806,
"s": 25798,
"text": "Example"
},
{
"code": null,
"e": 25814,
"s": 25806,
"text": "Python3"
},
{
"code": "# initializing stringtest_str = \"geeksforgeeks is best for all geeks\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing KK = '$' # initializing NN = 5 res = ''.join(ele if idx % N or idx == 0 else K for idx, ele in enumerate(test_str)) # printing resultprint(\"String after replacement : \" + str(res))",
"e": 26175,
"s": 25814,
"text": null
},
{
"code": null,
"e": 26183,
"s": 26175,
"text": "Output:"
},
{
"code": null,
"e": 26244,
"s": 26183,
"text": "The original string is : geeksforgeeks is best for all geeks"
},
{
"code": null,
"e": 26307,
"s": 26244,
"text": "String after replacement : geeks$orge$ks i$ bes$ for$all $eeks"
},
{
"code": null,
"e": 26330,
"s": 26307,
"text": "Python string-programs"
},
{
"code": null,
"e": 26337,
"s": 26330,
"text": "Python"
},
{
"code": null,
"e": 26353,
"s": 26337,
"text": "Python Programs"
},
{
"code": null,
"e": 26451,
"s": 26353,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26460,
"s": 26451,
"text": "Comments"
},
{
"code": null,
"e": 26473,
"s": 26460,
"text": "Old Comments"
},
{
"code": null,
"e": 26505,
"s": 26473,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26561,
"s": 26505,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26616,
"s": 26561,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26658,
"s": 26616,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26700,
"s": 26658,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26722,
"s": 26700,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26768,
"s": 26722,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26807,
"s": 26768,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26845,
"s": 26807,
"text": "Python | Convert a list to dictionary"
}
] |
How to create a Titleless and Borderless JFrame in Java?
|
To create a Titleless and Borderless JFrame, use the setUndecorated() method and set it to TRUE −
JFrame frame = new JFrame("Register!");
frame.setUndecorated(true);
The following is an example to create a titleless and borderless JFrame −
package my;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Register!");
JLabel label1, label2, label3;
frame.setLayout(new GridLayout(2, 2));
label1 = new JLabel("Id", SwingConstants.CENTER);
label2 = new JLabel("Age", SwingConstants.CENTER);
label3 = new JLabel("Password", SwingConstants.CENTER);
JTextField emailId = new JTextField(20);
JTextField age = new JTextField(20);
JPasswordField passwd = new JPasswordField();
passwd.setEchoChar('*');
frame.add(label1);
frame.add(label2);
frame.add(label3);
frame.add(emailId);
frame.add(age);
frame.add(passwd);
frame.setUndecorated(true);
frame.setSize(550, 400);
frame.setVisible(true);
}
}
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "To create a Titleless and Borderless JFrame, use the setUndecorated() method and set it to TRUE −"
},
{
"code": null,
"e": 1228,
"s": 1160,
"text": "JFrame frame = new JFrame(\"Register!\");\nframe.setUndecorated(true);"
},
{
"code": null,
"e": 1302,
"s": 1228,
"text": "The following is an example to create a titleless and borderless JFrame −"
},
{
"code": null,
"e": 2309,
"s": 1302,
"text": "package my;\nimport java.awt.GridLayout;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPasswordField;\nimport javax.swing.JTextField;\nimport javax.swing.SwingConstants;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Register!\");\n JLabel label1, label2, label3;\n frame.setLayout(new GridLayout(2, 2));\n label1 = new JLabel(\"Id\", SwingConstants.CENTER);\n label2 = new JLabel(\"Age\", SwingConstants.CENTER);\n label3 = new JLabel(\"Password\", SwingConstants.CENTER);\n JTextField emailId = new JTextField(20);\n JTextField age = new JTextField(20);\n JPasswordField passwd = new JPasswordField();\n passwd.setEchoChar('*');\n frame.add(label1);\n frame.add(label2);\n frame.add(label3);\n frame.add(emailId);\n frame.add(age);\n frame.add(passwd);\n frame.setUndecorated(true);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}"
}
] |
Execute both if and else statements simultaneously in C/C++
|
In this section we will see how to execute the if and else section simultaneously in a C or C++ code. This solution is little bit tricky.
When the if and else are executed one after another then it is like executing statements where if-else are not present. But here we will see if they are present how to execute them one after another.
#include <iostream>
using namespace std;
int main() {
int x = 10;
if(x > 5) {
lebel_1: cout << "This is inside if statement" <<endl;
goto lebel_2;
}else{
lebel_2: cout << "This is inside else statement" <<endl;
goto lebel_1;
}
}
This is inside if statement
This is inside else statement
This is inside if statement
This is inside else statement
This is inside if statement
This is inside else statement
This is inside if statement
This is inside else statement
....
....
....
This program will act as an infinite loop, but here the, if block and else block, are executing simultaneously. After the first check the condition checking is not really effect on the output.
Note: Here we are using goto statement to forcefully send the control from if block to else and else to if. But the using of goto statement is not good. It makes difficult to trace the control flow of a program.
|
[
{
"code": null,
"e": 1200,
"s": 1062,
"text": "In this section we will see how to execute the if and else section simultaneously in a C or C++ code. This solution is little bit tricky."
},
{
"code": null,
"e": 1400,
"s": 1200,
"text": "When the if and else are executed one after another then it is like executing statements where if-else are not present. But here we will see if they are present how to execute them one after another."
},
{
"code": null,
"e": 1667,
"s": 1400,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int x = 10;\n if(x > 5) {\n lebel_1: cout << \"This is inside if statement\" <<endl;\n goto lebel_2;\n }else{\n lebel_2: cout << \"This is inside else statement\" <<endl;\n goto lebel_1;\n }\n}"
},
{
"code": null,
"e": 1914,
"s": 1667,
"text": "This is inside if statement\nThis is inside else statement\nThis is inside if statement\nThis is inside else statement\nThis is inside if statement\nThis is inside else statement\nThis is inside if statement\nThis is inside else statement\n....\n....\n...."
},
{
"code": null,
"e": 2107,
"s": 1914,
"text": "This program will act as an infinite loop, but here the, if block and else block, are executing simultaneously. After the first check the condition checking is not really effect on the output."
},
{
"code": null,
"e": 2319,
"s": 2107,
"text": "Note: Here we are using goto statement to forcefully send the control from if block to else and else to if. But the using of goto statement is not good. It makes difficult to trace the control flow of a program."
}
] |
How to set the border color of the dots in matplotlib's scatterplots?
|
To set the border color of the dots in matplotlib scatterplots, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Initialize a variable "N" to store the number of sample data.
Create x and y data points using numpy.
Plot the x and y data points using scatter() method. To set the border color of the dots, use the edgecolors parameter in the scatter() method. Here, we have used "red" as the border color of the dots by using edgecolors='red'.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
N = 10
x = np.random.rand(N)
y = np.random.rand(N)
plt.scatter(x, y, s=500, c=np.random.rand(N),
edgecolors='red', linewidth=3)
plt.show()
It will produce the following output
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "To set the border color of the dots in matplotlib scatterplots, we can take the following steps −"
},
{
"code": null,
"e": 1236,
"s": 1160,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1298,
"s": 1236,
"text": "Initialize a variable \"N\" to store the number of sample data."
},
{
"code": null,
"e": 1338,
"s": 1298,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1566,
"s": 1338,
"text": "Plot the x and y data points using scatter() method. To set the border color of the dots, use the edgecolors parameter in the scatter() method. Here, we have used \"red\" as the border color of the dots by using edgecolors='red'."
},
{
"code": null,
"e": 1608,
"s": 1566,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1898,
"s": 1608,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nN = 10\n\nx = np.random.rand(N)\ny = np.random.rand(N)\n\nplt.scatter(x, y, s=500, c=np.random.rand(N),\n edgecolors='red', linewidth=3)\n\nplt.show()"
},
{
"code": null,
"e": 1935,
"s": 1898,
"text": "It will produce the following output"
}
] |
Creating word clouds with python. During a recent NLP project, I... | by Kerry Parker | Towards Data Science
|
During a recent NLP project, I came across an article where word clouds were created in the shape of US Presidents using words from their inauguration speeches. Whilst I had used word clouds to visualise the most frequent words in a document, I’d not considered using this with a mask to represent the topic or subject. This got me thinking...
Several months ago, shortly before the final series of Game Of Thrones and after having just rewatched seasons 1–7, I was eagerly awaiting the finale — so much so that I went looking for any Game Of Thrones data I could find online to create a predictor for who would survive the chaos of season 8 and what would happen within the 7 Kingdoms. Unfortunately, I was out of time but I did find plenty of data and visualisations that people had put together. When I came across the inaugural word clouds I wondered if I could use this Game Of Thrones data, particularly scripts, with image masks of the characters to create some pretty cool visualisations. In this article, as presented at a recent tech meet-up, I will walk through my steps to create Game Of Thrones word clouds using python.
Following a similar method to the inaugural word cloud article, there are several steps involved when dealing with text based data. The steps are:
Finding relevant dataCleaning dataCreating a mask from the imageGenerating word clouds
Finding relevant data
Cleaning data
Creating a mask from the image
Generating word clouds
Since I will be using python in this tutorial, there are many libraries to help with the above steps, also Dipanjan Sarkar’s guide to Natural Language Processing provides a comprehensive introduction to techniques in text analytics if you are looking for further reading around the topic.
Before getting started with the first step, I defined the goal of the project to ensure that no important steps were missed and to have a clear vision of the target.
Project goal: To create word clouds for Game Of Thrones characters masked with an image.
There is plenty of Game Of Thrones data available online — GitHub and Kaggle are where I usually first search for datasets — and I quickly found a dataset containing the scripts.
To achieve the project goal, the lines for each character need to be stated —the first question was: are the character lines are available?
Looking at a snippet from the first episode, the character data is available! However, when exploring further episodes and season, the format for character names varies.
In the case above only the character’s first name is used and this is all in uppercase, whilst in other seasons the characters full name is used with letter case. Stage directions can also be included within the character name.
Th search for all lines by the character name, a regular expressions with the character names can be used:
re.findall(r'(^'+name+r'.*:.*)', line, re.IGNORECASE)
This expression searches for the start of a line (^), followed by the character name which we input as a variable, followed by any text (.*), then a colon to indicate that this is a character’s line (:) and followed by any text (.*). By containing this regular expression within brackets, the full line is returned. Finally, the case is ignored, so the character name can be upper/lower/letter case.
Using the function below will return all the lines for a character:
# final_data taken from: # https://github.com/shekharkoirala/Game_of_Thrones# get data for charactersdef get_char_lines(char): output = [] print('Getting lines for', char) with open('final_data.txt', 'r') as f: for line in f: if re.findall(r'(^'+char+r'.*:.*)',line,re.IGNORECASE): output.append(line) f.close() print(char, 'has ', len(output), 'lines')return output# get lines usingget_char_lines('arya')
Now that we have the lines for a character, these need to be cleaned.
The following techniques are used for cleaning the lines, these same techniques are also outlined in detail in the NLP Guide referenced above. Again regular expressions are useful here to replace or remove characters:
Remove line info eg. JON:
re.sub(r'.*:', '', text)
Remove brackets — remove any stage directions from the character lines
re.sub('[\(\[].*?[\)\]]', ' ', text)
Remove accented characters and normalise using the unicodedata library
unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8', 'ignore')
Expand any contracted words eg. don’t → do notThere is a python library for this, copy contractions.py to your working directory from:https://github.com/dipanjanS/practical-machine-learning-with-python/
(Optional): apply lemmatisation where a word is stemmed to a root word that is in the dictionary, eg. is, are → be Not currently using lemmatisation as it doesn’t handle some words well eg. Stannis → Stanni
Convert all text to lowercase
text.lower()
Remove special characters (*,.!?) with the option to remove numbers too — default is set to false
pattern = r'[^a-zA-Z0-9\s]' if not remove_digits else r'[^a-zA-Z\s]' re.sub(pattern, '', text)
Remove stop words, using stop words from the nltk library by first tokenising the text, splitting the string into a list of substrings and then removing any stop words
stopword_list = stopwords.words('english') tokens = nltk.word_tokenize(text) tokens = [token.strip() for token in tokens] ' '.join([token for token in tokens if token not in stopword_list])
These cleaning techniques have been based on several different sources and there are many variations of these steps as well as additional cleaning techniques that can be used. These initial cleaning steps have been used in this project.
Based on the inauguration word clouds, the PIL library is used to open the image, a numpy array is created from the image to create a mask.
char_mask = np.array(Image.open("images/image.jpeg")) image_colors = ImageColorGenerator(char_mask)
Optionally the numpy array can be used with wordcloud.ImageColorGenerator to then recolor the word cloud to represent the colours from the image, or otherwise. This will be covered in the next section.
After initially testing an image as a word cloud mask, the background in the image created too much noise that the shape of the character was not well defined. To avoid this, it can be useful to remove the image background and replace with a white background instead.
The final step is to create the word cloud using the generate() function.
wc = WordCloud(background_color="white", max_words=200, width=400, height=400, mask=char_mask, random_state=1).generate(text)# to recolour the imageplt.imshow(wc.recolor(color_func=image_colors))
The word cloud will be masked with an image and the size of text will be based on word frequency.
The parameters of the word cloud can be adjusted — try increasingmax_words to see some of the less frequent words included, note that this should be less than the number of unique words within your document.
As mentioned in the previous section, the recolor step is optional and here is used to represent the original image colours.
Using the steps above with images of Game Of Thrones characters, the generated words clouds are presented below:
This has also been extended to generate word clouds based on Houses:
With these word clouds the initial project goal has been reached!
There are several ways in which these word clouds can be improved.
Common words: There are recurring words that are common in all the characters scripts. Currently the word clouds are generated based on the word frequency however, an alternative would be TFIDF which weights the terms based on the term frequency in the document and the frequency with respect to the corpus. Alternatively, a custom stop word list could be generated to remove other frequent words
Lemmatisation/stemming: Lemmatisation has not been used in the examples above as some words unique to Game of Thrones were shortened when testing (Stannis → Stanni), however this does mean that words which come from the same root word are not linked and occur several times in the word cloud eg. say, said. An alternative lemmatisation method or stemming technique could be used.
Text cleaning: There are further cleaning or data preparation steps that could be used
Word cloud features: I have tested with different word colours, background colours and word cloud parameters, the grey colour and black background works in this case but some of the parameters could be further optimised
Further text analysis: many insights can be drawn from this dataset. Much more scope for analysis!
Looking into further shows, I eventually found Stranger Things script — although they are missing character lines the data can still be used to generate word clouds....
In this article I have walked through the basic steps to generate word clouds which are masked with an image.
This is just the start of my experimenting with word clouds! There is a huge scope for further development and improvement in the project, I hope you can follow the steps to create your own projects with word clouds!\
Thank you for reading! If you enjoyed my article then subscribe to my monthly newsletter where you can get my latest articles and top resources delivered right to your inbox!
You can follow me on Medium for more articles, follow me on Twitter or find out more about what I’m up to on my website.
Some rights reserved
|
[
{
"code": null,
"e": 516,
"s": 172,
"text": "During a recent NLP project, I came across an article where word clouds were created in the shape of US Presidents using words from their inauguration speeches. Whilst I had used word clouds to visualise the most frequent words in a document, I’d not considered using this with a mask to represent the topic or subject. This got me thinking..."
},
{
"code": null,
"e": 1306,
"s": 516,
"text": "Several months ago, shortly before the final series of Game Of Thrones and after having just rewatched seasons 1–7, I was eagerly awaiting the finale — so much so that I went looking for any Game Of Thrones data I could find online to create a predictor for who would survive the chaos of season 8 and what would happen within the 7 Kingdoms. Unfortunately, I was out of time but I did find plenty of data and visualisations that people had put together. When I came across the inaugural word clouds I wondered if I could use this Game Of Thrones data, particularly scripts, with image masks of the characters to create some pretty cool visualisations. In this article, as presented at a recent tech meet-up, I will walk through my steps to create Game Of Thrones word clouds using python."
},
{
"code": null,
"e": 1453,
"s": 1306,
"text": "Following a similar method to the inaugural word cloud article, there are several steps involved when dealing with text based data. The steps are:"
},
{
"code": null,
"e": 1540,
"s": 1453,
"text": "Finding relevant dataCleaning dataCreating a mask from the imageGenerating word clouds"
},
{
"code": null,
"e": 1562,
"s": 1540,
"text": "Finding relevant data"
},
{
"code": null,
"e": 1576,
"s": 1562,
"text": "Cleaning data"
},
{
"code": null,
"e": 1607,
"s": 1576,
"text": "Creating a mask from the image"
},
{
"code": null,
"e": 1630,
"s": 1607,
"text": "Generating word clouds"
},
{
"code": null,
"e": 1919,
"s": 1630,
"text": "Since I will be using python in this tutorial, there are many libraries to help with the above steps, also Dipanjan Sarkar’s guide to Natural Language Processing provides a comprehensive introduction to techniques in text analytics if you are looking for further reading around the topic."
},
{
"code": null,
"e": 2085,
"s": 1919,
"text": "Before getting started with the first step, I defined the goal of the project to ensure that no important steps were missed and to have a clear vision of the target."
},
{
"code": null,
"e": 2174,
"s": 2085,
"text": "Project goal: To create word clouds for Game Of Thrones characters masked with an image."
},
{
"code": null,
"e": 2353,
"s": 2174,
"text": "There is plenty of Game Of Thrones data available online — GitHub and Kaggle are where I usually first search for datasets — and I quickly found a dataset containing the scripts."
},
{
"code": null,
"e": 2493,
"s": 2353,
"text": "To achieve the project goal, the lines for each character need to be stated —the first question was: are the character lines are available?"
},
{
"code": null,
"e": 2663,
"s": 2493,
"text": "Looking at a snippet from the first episode, the character data is available! However, when exploring further episodes and season, the format for character names varies."
},
{
"code": null,
"e": 2891,
"s": 2663,
"text": "In the case above only the character’s first name is used and this is all in uppercase, whilst in other seasons the characters full name is used with letter case. Stage directions can also be included within the character name."
},
{
"code": null,
"e": 2998,
"s": 2891,
"text": "Th search for all lines by the character name, a regular expressions with the character names can be used:"
},
{
"code": null,
"e": 3052,
"s": 2998,
"text": "re.findall(r'(^'+name+r'.*:.*)', line, re.IGNORECASE)"
},
{
"code": null,
"e": 3452,
"s": 3052,
"text": "This expression searches for the start of a line (^), followed by the character name which we input as a variable, followed by any text (.*), then a colon to indicate that this is a character’s line (:) and followed by any text (.*). By containing this regular expression within brackets, the full line is returned. Finally, the case is ignored, so the character name can be upper/lower/letter case."
},
{
"code": null,
"e": 3520,
"s": 3452,
"text": "Using the function below will return all the lines for a character:"
},
{
"code": null,
"e": 3997,
"s": 3520,
"text": "# final_data taken from: # https://github.com/shekharkoirala/Game_of_Thrones# get data for charactersdef get_char_lines(char): output = [] print('Getting lines for', char) with open('final_data.txt', 'r') as f: for line in f: if re.findall(r'(^'+char+r'.*:.*)',line,re.IGNORECASE): output.append(line) f.close() print(char, 'has ', len(output), 'lines')return output# get lines usingget_char_lines('arya')"
},
{
"code": null,
"e": 4067,
"s": 3997,
"text": "Now that we have the lines for a character, these need to be cleaned."
},
{
"code": null,
"e": 4285,
"s": 4067,
"text": "The following techniques are used for cleaning the lines, these same techniques are also outlined in detail in the NLP Guide referenced above. Again regular expressions are useful here to replace or remove characters:"
},
{
"code": null,
"e": 4311,
"s": 4285,
"text": "Remove line info eg. JON:"
},
{
"code": null,
"e": 4336,
"s": 4311,
"text": "re.sub(r'.*:', '', text)"
},
{
"code": null,
"e": 4407,
"s": 4336,
"text": "Remove brackets — remove any stage directions from the character lines"
},
{
"code": null,
"e": 4444,
"s": 4407,
"text": "re.sub('[\\(\\[].*?[\\)\\]]', ' ', text)"
},
{
"code": null,
"e": 4515,
"s": 4444,
"text": "Remove accented characters and normalise using the unicodedata library"
},
{
"code": null,
"e": 4603,
"s": 4515,
"text": "unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8', 'ignore')"
},
{
"code": null,
"e": 4806,
"s": 4603,
"text": "Expand any contracted words eg. don’t → do notThere is a python library for this, copy contractions.py to your working directory from:https://github.com/dipanjanS/practical-machine-learning-with-python/"
},
{
"code": null,
"e": 5013,
"s": 4806,
"text": "(Optional): apply lemmatisation where a word is stemmed to a root word that is in the dictionary, eg. is, are → be Not currently using lemmatisation as it doesn’t handle some words well eg. Stannis → Stanni"
},
{
"code": null,
"e": 5043,
"s": 5013,
"text": "Convert all text to lowercase"
},
{
"code": null,
"e": 5056,
"s": 5043,
"text": "text.lower()"
},
{
"code": null,
"e": 5154,
"s": 5056,
"text": "Remove special characters (*,.!?) with the option to remove numbers too — default is set to false"
},
{
"code": null,
"e": 5252,
"s": 5154,
"text": "pattern = r'[^a-zA-Z0-9\\s]' if not remove_digits else r'[^a-zA-Z\\s]' re.sub(pattern, '', text)"
},
{
"code": null,
"e": 5420,
"s": 5252,
"text": "Remove stop words, using stop words from the nltk library by first tokenising the text, splitting the string into a list of substrings and then removing any stop words"
},
{
"code": null,
"e": 5619,
"s": 5420,
"text": "stopword_list = stopwords.words('english') tokens = nltk.word_tokenize(text) tokens = [token.strip() for token in tokens] ' '.join([token for token in tokens if token not in stopword_list])"
},
{
"code": null,
"e": 5856,
"s": 5619,
"text": "These cleaning techniques have been based on several different sources and there are many variations of these steps as well as additional cleaning techniques that can be used. These initial cleaning steps have been used in this project."
},
{
"code": null,
"e": 5996,
"s": 5856,
"text": "Based on the inauguration word clouds, the PIL library is used to open the image, a numpy array is created from the image to create a mask."
},
{
"code": null,
"e": 6099,
"s": 5996,
"text": "char_mask = np.array(Image.open(\"images/image.jpeg\")) image_colors = ImageColorGenerator(char_mask)"
},
{
"code": null,
"e": 6301,
"s": 6099,
"text": "Optionally the numpy array can be used with wordcloud.ImageColorGenerator to then recolor the word cloud to represent the colours from the image, or otherwise. This will be covered in the next section."
},
{
"code": null,
"e": 6569,
"s": 6301,
"text": "After initially testing an image as a word cloud mask, the background in the image created too much noise that the shape of the character was not well defined. To avoid this, it can be useful to remove the image background and replace with a white background instead."
},
{
"code": null,
"e": 6643,
"s": 6569,
"text": "The final step is to create the word cloud using the generate() function."
},
{
"code": null,
"e": 6839,
"s": 6643,
"text": "wc = WordCloud(background_color=\"white\", max_words=200, width=400, height=400, mask=char_mask, random_state=1).generate(text)# to recolour the imageplt.imshow(wc.recolor(color_func=image_colors))"
},
{
"code": null,
"e": 6937,
"s": 6839,
"text": "The word cloud will be masked with an image and the size of text will be based on word frequency."
},
{
"code": null,
"e": 7145,
"s": 6937,
"text": "The parameters of the word cloud can be adjusted — try increasingmax_words to see some of the less frequent words included, note that this should be less than the number of unique words within your document."
},
{
"code": null,
"e": 7270,
"s": 7145,
"text": "As mentioned in the previous section, the recolor step is optional and here is used to represent the original image colours."
},
{
"code": null,
"e": 7383,
"s": 7270,
"text": "Using the steps above with images of Game Of Thrones characters, the generated words clouds are presented below:"
},
{
"code": null,
"e": 7452,
"s": 7383,
"text": "This has also been extended to generate word clouds based on Houses:"
},
{
"code": null,
"e": 7518,
"s": 7452,
"text": "With these word clouds the initial project goal has been reached!"
},
{
"code": null,
"e": 7585,
"s": 7518,
"text": "There are several ways in which these word clouds can be improved."
},
{
"code": null,
"e": 7982,
"s": 7585,
"text": "Common words: There are recurring words that are common in all the characters scripts. Currently the word clouds are generated based on the word frequency however, an alternative would be TFIDF which weights the terms based on the term frequency in the document and the frequency with respect to the corpus. Alternatively, a custom stop word list could be generated to remove other frequent words"
},
{
"code": null,
"e": 8362,
"s": 7982,
"text": "Lemmatisation/stemming: Lemmatisation has not been used in the examples above as some words unique to Game of Thrones were shortened when testing (Stannis → Stanni), however this does mean that words which come from the same root word are not linked and occur several times in the word cloud eg. say, said. An alternative lemmatisation method or stemming technique could be used."
},
{
"code": null,
"e": 8449,
"s": 8362,
"text": "Text cleaning: There are further cleaning or data preparation steps that could be used"
},
{
"code": null,
"e": 8669,
"s": 8449,
"text": "Word cloud features: I have tested with different word colours, background colours and word cloud parameters, the grey colour and black background works in this case but some of the parameters could be further optimised"
},
{
"code": null,
"e": 8768,
"s": 8669,
"text": "Further text analysis: many insights can be drawn from this dataset. Much more scope for analysis!"
},
{
"code": null,
"e": 8937,
"s": 8768,
"text": "Looking into further shows, I eventually found Stranger Things script — although they are missing character lines the data can still be used to generate word clouds...."
},
{
"code": null,
"e": 9047,
"s": 8937,
"text": "In this article I have walked through the basic steps to generate word clouds which are masked with an image."
},
{
"code": null,
"e": 9265,
"s": 9047,
"text": "This is just the start of my experimenting with word clouds! There is a huge scope for further development and improvement in the project, I hope you can follow the steps to create your own projects with word clouds!\\"
},
{
"code": null,
"e": 9440,
"s": 9265,
"text": "Thank you for reading! If you enjoyed my article then subscribe to my monthly newsletter where you can get my latest articles and top resources delivered right to your inbox!"
},
{
"code": null,
"e": 9561,
"s": 9440,
"text": "You can follow me on Medium for more articles, follow me on Twitter or find out more about what I’m up to on my website."
}
] |
Python - Character repetition string combinations - GeeksforGeeks
|
27 Mar, 2021
Given a string list and list of numbers, the task is to write a Python program to generate all possible strings by repeating each character of each string by each number in the list.
Input : test_list = [“gfg”, “is”, “best”], rep_list = [3, 5, 2]
Output : [‘gggfffggg’, ‘iiisss’, ‘bbbeeesssttt’, ‘gggggfffffggggg’, ‘iiiiisssss’, ‘bbbbbeeeeesssssttttt’, ‘ggffgg’, ‘iiss’, ‘bbeesstt’]
Explanation : Each element of ‘gfg’ is repeated 3, 5 and 2 times to output different strings.
Input : test_list = [“gfg”, “is”, “best”], rep_list = [3, 1, 2]
Output : [‘gggfffggg’, ‘iiisss’, ‘bbbeeesssttt’, ‘gfg’, ‘is’, ‘best’, ‘ggffgg’, ‘iiss’, ‘bbeesstt’]
Explanation : Each element of ‘gfg’ is repeated 3, 1 and 2 times to output different strings.
Method #1 : Using join() + loop + list comprehension + * operator
In this, the task of constructing each string is done using join(). The * operator performs the task of creating multiple character occurrences. The nested loop is used to combine each number with each string.
Python3
# Python3 code to demonstrate working of# Character repetition string combinations# Using join() + nested loop + list comprehension + * operator # initializing listtest_list = ["gfg", "is", "best"] # printing original listprint("The original list is : " + str(test_list)) # repeat listrep_list = [3, 5, 2] # * operator performs repetitions# list comprehension encapsulates logicres = [''.join(sub * ele1 for sub in ele2) for ele1 in rep_list for ele2 in test_list] # printing resultprint("All repetition combinations strings : " + str(res))
Output:
The original list is : [‘gfg’, ‘is’, ‘best’]
All repetition combinations strings : [‘gggfffggg’, ‘iiisss’, ‘bbbeeesssttt’, ‘gggggfffffggggg’, ‘iiiiisssss’, ‘bbbbbeeeeesssssttttt’, ‘ggffgg’, ‘iiss’, ‘bbeesstt’]
Method #2 : Using product() + join() + loop
The nested loop for generating pairs is avoiding in this method by the use of the product() method. Rest all the functionality remains same as the above method.
Python3
# Python3 code to demonstrate working of# Character repetition string combinations# Using product() + join() + loopfrom itertools import product # initializing listtest_list = ["gfg", "is", "best"] # printing original listprint("The original list is : " + str(test_list)) # repeat listrep_list = [3, 5, 2] # * operator performs repetitions# list comprehension encapsulates logicres = [''.join(sub * ele1 for sub in ele2) for ele2, ele1 in product(test_list, rep_list)] # printing resultprint("All repetition combinations strings : " + str(res))
Output:
The original list is : [‘gfg’, ‘is’, ‘best’]
All repetition combinations strings : [‘gggfffggg’, ‘gggggfffffggggg’, ‘ggffgg’, ‘iiisss’, ‘iiiiisssss’, ‘iiss’, ‘bbbeeesssttt’, ‘bbbbbeeeeesssssttttt’, ‘bbeesstt’]
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n27 Mar, 2021"
},
{
"code": null,
"e": 24475,
"s": 24292,
"text": "Given a string list and list of numbers, the task is to write a Python program to generate all possible strings by repeating each character of each string by each number in the list."
},
{
"code": null,
"e": 24539,
"s": 24475,
"text": "Input : test_list = [“gfg”, “is”, “best”], rep_list = [3, 5, 2]"
},
{
"code": null,
"e": 24675,
"s": 24539,
"text": "Output : [‘gggfffggg’, ‘iiisss’, ‘bbbeeesssttt’, ‘gggggfffffggggg’, ‘iiiiisssss’, ‘bbbbbeeeeesssssttttt’, ‘ggffgg’, ‘iiss’, ‘bbeesstt’]"
},
{
"code": null,
"e": 24770,
"s": 24675,
"text": "Explanation : Each element of ‘gfg’ is repeated 3, 5 and 2 times to output different strings. "
},
{
"code": null,
"e": 24834,
"s": 24770,
"text": "Input : test_list = [“gfg”, “is”, “best”], rep_list = [3, 1, 2]"
},
{
"code": null,
"e": 24934,
"s": 24834,
"text": "Output : [‘gggfffggg’, ‘iiisss’, ‘bbbeeesssttt’, ‘gfg’, ‘is’, ‘best’, ‘ggffgg’, ‘iiss’, ‘bbeesstt’]"
},
{
"code": null,
"e": 25029,
"s": 24934,
"text": "Explanation : Each element of ‘gfg’ is repeated 3, 1 and 2 times to output different strings. "
},
{
"code": null,
"e": 25095,
"s": 25029,
"text": "Method #1 : Using join() + loop + list comprehension + * operator"
},
{
"code": null,
"e": 25305,
"s": 25095,
"text": "In this, the task of constructing each string is done using join(). The * operator performs the task of creating multiple character occurrences. The nested loop is used to combine each number with each string."
},
{
"code": null,
"e": 25313,
"s": 25305,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Character repetition string combinations# Using join() + nested loop + list comprehension + * operator # initializing listtest_list = [\"gfg\", \"is\", \"best\"] # printing original listprint(\"The original list is : \" + str(test_list)) # repeat listrep_list = [3, 5, 2] # * operator performs repetitions# list comprehension encapsulates logicres = [''.join(sub * ele1 for sub in ele2) for ele1 in rep_list for ele2 in test_list] # printing resultprint(\"All repetition combinations strings : \" + str(res))",
"e": 25865,
"s": 25313,
"text": null
},
{
"code": null,
"e": 25873,
"s": 25865,
"text": "Output:"
},
{
"code": null,
"e": 25918,
"s": 25873,
"text": "The original list is : [‘gfg’, ‘is’, ‘best’]"
},
{
"code": null,
"e": 26083,
"s": 25918,
"text": "All repetition combinations strings : [‘gggfffggg’, ‘iiisss’, ‘bbbeeesssttt’, ‘gggggfffffggggg’, ‘iiiiisssss’, ‘bbbbbeeeeesssssttttt’, ‘ggffgg’, ‘iiss’, ‘bbeesstt’]"
},
{
"code": null,
"e": 26127,
"s": 26083,
"text": "Method #2 : Using product() + join() + loop"
},
{
"code": null,
"e": 26288,
"s": 26127,
"text": "The nested loop for generating pairs is avoiding in this method by the use of the product() method. Rest all the functionality remains same as the above method."
},
{
"code": null,
"e": 26296,
"s": 26288,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Character repetition string combinations# Using product() + join() + loopfrom itertools import product # initializing listtest_list = [\"gfg\", \"is\", \"best\"] # printing original listprint(\"The original list is : \" + str(test_list)) # repeat listrep_list = [3, 5, 2] # * operator performs repetitions# list comprehension encapsulates logicres = [''.join(sub * ele1 for sub in ele2) for ele2, ele1 in product(test_list, rep_list)] # printing resultprint(\"All repetition combinations strings : \" + str(res))",
"e": 26852,
"s": 26296,
"text": null
},
{
"code": null,
"e": 26860,
"s": 26852,
"text": "Output:"
},
{
"code": null,
"e": 26905,
"s": 26860,
"text": "The original list is : [‘gfg’, ‘is’, ‘best’]"
},
{
"code": null,
"e": 27070,
"s": 26905,
"text": "All repetition combinations strings : [‘gggfffggg’, ‘gggggfffffggggg’, ‘ggffgg’, ‘iiisss’, ‘iiiiisssss’, ‘iiss’, ‘bbbeeesssttt’, ‘bbbbbeeeeesssssttttt’, ‘bbeesstt’]"
},
{
"code": null,
"e": 27091,
"s": 27070,
"text": "Python list-programs"
},
{
"code": null,
"e": 27114,
"s": 27091,
"text": "Python string-programs"
},
{
"code": null,
"e": 27121,
"s": 27114,
"text": "Python"
},
{
"code": null,
"e": 27137,
"s": 27121,
"text": "Python Programs"
},
{
"code": null,
"e": 27235,
"s": 27137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27267,
"s": 27235,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27323,
"s": 27267,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27365,
"s": 27323,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27407,
"s": 27365,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27429,
"s": 27407,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27451,
"s": 27429,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27497,
"s": 27451,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27536,
"s": 27497,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27574,
"s": 27536,
"text": "Python | Convert a list to dictionary"
}
] |
HTML | <meta> charset Attribute - GeeksforGeeks
|
29 Jan, 2020
The HTML charset Attribute is used to specify the character encoding for the HTML document. The charset attribute could be overridden by using the lang attribute of any element.
Syntax:
<meta charset="character_set">
Attribute Values: It contains the value i.e character_set which specify the character encoding for the HTML document.Values:
UTF-8: It specify the character encoding for Unicode.
ISO-8859-1: It specify the character encoding for the Latin alphabet.
Example: This Example illustrates the use of charset Attribute in Meta Element.
<!DOCTYPE html><html> <head> <title> HTML charset Attribute </title> <meta name="keywords" charset="UTF-8" content="Meta Tags, Metadata" /></head> <body style="text-align:center"> <H1>Hello GeeksforGeeks!</H1> <h2> HTML charset Attribute in Meta Element </h2></body> </html>
Output:
Supported Browsers: The browser supported by HTML <meta> Charset Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
mittalaman307
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Form validation using HTML and JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 25170,
"s": 25142,
"text": "\n29 Jan, 2020"
},
{
"code": null,
"e": 25348,
"s": 25170,
"text": "The HTML charset Attribute is used to specify the character encoding for the HTML document. The charset attribute could be overridden by using the lang attribute of any element."
},
{
"code": null,
"e": 25356,
"s": 25348,
"text": "Syntax:"
},
{
"code": null,
"e": 25387,
"s": 25356,
"text": "<meta charset=\"character_set\">"
},
{
"code": null,
"e": 25512,
"s": 25387,
"text": "Attribute Values: It contains the value i.e character_set which specify the character encoding for the HTML document.Values:"
},
{
"code": null,
"e": 25566,
"s": 25512,
"text": "UTF-8: It specify the character encoding for Unicode."
},
{
"code": null,
"e": 25636,
"s": 25566,
"text": "ISO-8859-1: It specify the character encoding for the Latin alphabet."
},
{
"code": null,
"e": 25716,
"s": 25636,
"text": "Example: This Example illustrates the use of charset Attribute in Meta Element."
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML charset Attribute </title> <meta name=\"keywords\" charset=\"UTF-8\" content=\"Meta Tags, Metadata\" /></head> <body style=\"text-align:center\"> <H1>Hello GeeksforGeeks!</H1> <h2> HTML charset Attribute in Meta Element </h2></body> </html>",
"e": 26037,
"s": 25716,
"text": null
},
{
"code": null,
"e": 26045,
"s": 26037,
"text": "Output:"
},
{
"code": null,
"e": 26138,
"s": 26045,
"text": "Supported Browsers: The browser supported by HTML <meta> Charset Attribute are listed below:"
},
{
"code": null,
"e": 26152,
"s": 26138,
"text": "Google Chrome"
},
{
"code": null,
"e": 26170,
"s": 26152,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26178,
"s": 26170,
"text": "Firefox"
},
{
"code": null,
"e": 26184,
"s": 26178,
"text": "Opera"
},
{
"code": null,
"e": 26191,
"s": 26184,
"text": "Safari"
},
{
"code": null,
"e": 26328,
"s": 26191,
"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": 26342,
"s": 26328,
"text": "mittalaman307"
},
{
"code": null,
"e": 26358,
"s": 26342,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 26363,
"s": 26358,
"text": "HTML"
},
{
"code": null,
"e": 26380,
"s": 26363,
"text": "Web Technologies"
},
{
"code": null,
"e": 26385,
"s": 26380,
"text": "HTML"
},
{
"code": null,
"e": 26483,
"s": 26385,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26492,
"s": 26483,
"text": "Comments"
},
{
"code": null,
"e": 26505,
"s": 26492,
"text": "Old Comments"
},
{
"code": null,
"e": 26553,
"s": 26505,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26603,
"s": 26553,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26627,
"s": 26603,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26677,
"s": 26627,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26719,
"s": 26677,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 26761,
"s": 26719,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26794,
"s": 26761,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26837,
"s": 26794,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26882,
"s": 26837,
"text": "Convert a string to an integer in JavaScript"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.