title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to write long strings in Multi-lines C/C++? - GeeksforGeeks
22 Aug, 2019 Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. #include<stdio.h>int main(){ // We can put two double quotes anywhere in a string char *str1 = "geeks""quiz"; // We can put space line break between two double quotes char *str2 = "Qeeks" "Quiz"; char *str3 = "Qeeks" "Quiz"; puts(str1); puts(str2); puts(str3); puts("Geeks" // Breaking string in multiple lines "forGeeks"); return 0;} Output:geeksquizQeeksQuizQeeksQuizGeeksforGeeks Below are few examples with long long strings broken using two double quotes for better readability. #include<stdio.h>int main(){ char *str = "These are reserved words in C language are int, float, " "if, else, for, while etc. An Identifier is a sequence of" "letters and digits, but must start with a letter. " "Underscore ( _ ) is treated as a letter. Identifiers are " "case sensitive. Identifiers are used to name variables," "functions etc."; puts(str); return 0; } Output: These are reserved words in C language are int, float, if, else, for, while etc. An Identifier is a sequence ofletters and digits, but must start with a letter. Underscore ( _ ) is treated as a letter. Identifiers are case sensitive. Identifiers are used to name variables,functions etc. Similarly, we can write long strings in printf and or cout. #include<stdio.h>int main(){ char *str = "An Identifier is a sequence of" "letters and digits, but must start with a letter. " "Underscore ( _ ) is treated as a letter. Identifiers are " "case sensitive. Identifiers are used to name variables," "functions etc."; printf ("These are reserved words in C language are int, float, " "if, else, for, while etc. %s ", str); return 0; } Output: These are reserved words in C language are int, float, if, else, for, while etc. An Identifier is a sequence ofletters and digits, but must start with a letter. Underscore ( _ ) is treated as a letter. Identifiers are case sensitive. Identifiers are used to name variables,functions etc. This article is contributed by Ayush Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rahul1642 nidhi_biet C Array and String cpp-string C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 24232, "s": 24204, "text": "\n22 Aug, 2019" }, { "code": null, "e": 24328, "s": 24232, "text": "Image a situation where we want to use or print a long long string in C or C++, how to do this?" }, { "code": null, "e": 24477, "s": 24328, "text": "In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same." }, { "code": "#include<stdio.h>int main(){ // We can put two double quotes anywhere in a string char *str1 = \"geeks\"\"quiz\"; // We can put space line break between two double quotes char *str2 = \"Qeeks\" \"Quiz\"; char *str3 = \"Qeeks\" \"Quiz\"; puts(str1); puts(str2); puts(str3); puts(\"Geeks\" // Breaking string in multiple lines \"forGeeks\"); return 0;}", "e": 24881, "s": 24477, "text": null }, { "code": null, "e": 24929, "s": 24881, "text": "Output:geeksquizQeeksQuizQeeksQuizGeeksforGeeks" }, { "code": null, "e": 25030, "s": 24929, "text": "Below are few examples with long long strings broken using two double quotes for better readability." }, { "code": "#include<stdio.h>int main(){ char *str = \"These are reserved words in C language are int, float, \" \"if, else, for, while etc. An Identifier is a sequence of\" \"letters and digits, but must start with a letter. \" \"Underscore ( _ ) is treated as a letter. Identifiers are \" \"case sensitive. Identifiers are used to name variables,\" \"functions etc.\"; puts(str); return 0; } ", "e": 25477, "s": 25030, "text": null }, { "code": null, "e": 25773, "s": 25477, "text": "Output: These are reserved words in C language are int, float, if, else, for, while etc. An Identifier is a sequence ofletters and digits, but must start with a letter. Underscore ( _ ) is treated as a letter. Identifiers are case sensitive. Identifiers are used to name variables,functions etc." }, { "code": null, "e": 25833, "s": 25773, "text": "Similarly, we can write long strings in printf and or cout." }, { "code": "#include<stdio.h>int main(){ char *str = \"An Identifier is a sequence of\" \"letters and digits, but must start with a letter. \" \"Underscore ( _ ) is treated as a letter. Identifiers are \" \"case sensitive. Identifiers are used to name variables,\" \"functions etc.\"; printf (\"These are reserved words in C language are int, float, \" \"if, else, for, while etc. %s \", str); return 0; }", "e": 26286, "s": 25833, "text": null }, { "code": null, "e": 26582, "s": 26286, "text": "Output: These are reserved words in C language are int, float, if, else, for, while etc. An Identifier is a sequence ofletters and digits, but must start with a letter. Underscore ( _ ) is treated as a letter. Identifiers are case sensitive. Identifiers are used to name variables,functions etc." }, { "code": null, "e": 26749, "s": 26582, "text": "This article is contributed by Ayush Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 26759, "s": 26749, "text": "rahul1642" }, { "code": null, "e": 26770, "s": 26759, "text": "nidhi_biet" }, { "code": null, "e": 26789, "s": 26770, "text": "C Array and String" }, { "code": null, "e": 26800, "s": 26789, "text": "cpp-string" }, { "code": null, "e": 26811, "s": 26800, "text": "C Language" }, { "code": null, "e": 26815, "s": 26811, "text": "C++" }, { "code": null, "e": 26819, "s": 26815, "text": "CPP" }, { "code": null, "e": 26917, "s": 26819, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26955, "s": 26917, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26975, "s": 26955, "text": "Multithreading in C" }, { "code": null, "e": 27001, "s": 26975, "text": "Exception Handling in C++" }, { "code": null, "e": 27023, "s": 27001, "text": "'this' pointer in C++" }, { "code": null, "e": 27064, "s": 27023, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27082, "s": 27064, "text": "Vector in C++ STL" }, { "code": null, "e": 27128, "s": 27082, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 27147, "s": 27128, "text": "Inheritance in C++" }, { "code": null, "e": 27190, "s": 27147, "text": "Map in C++ Standard Template Library (STL)" } ]
Sentiment Analysis with PySpark. One of the tools I’m deeply interested... | by Ricky Kim | Towards Data Science
One of the tools I’m deeply interested but haven’t had many chances to explore is Apache Spark. Most of the time, Pandas and Scikit-Learn is enough to handle the size of data I’m trying to build a model on. But that also means that I haven’t had a chance to deal with petabytes of data yet, and I want to be prepared for the case I’m faced with a real big-data. I have tried some basic data manipulation with PySpark before, but only to a very basic level. I want to learn more and be more comfortable in using PySpark. This post is my endeavour to have a better understanding of PySpark. Python is great for data science modelling, thanks to its numerous modules and packages that help achieve data science goals. But what if the data you are dealing with cannot be fit into a single machine? Maybe you can implement careful sampling to do your analysis on a single machine, but with distributed computing framework like PySpark, you can efficiently implement the task for large datasets. Spark API is available in multiple programming languages (Scala, Java, Python and R). There are debates about how Spark performance varies depending on which language you run it on, but since the main language I have been using is Python, I will focus on PySpark without going into too much detail of what language should I choose for Apache Spark. Spark has three different data structures available through its APIs: RDD, Dataframe (this is different from Pandas data frame), Dataset. For this post, I will work with Dataframe, and the corresponding machine learning library SparkML. I first decided on the data structure I would like to use based on the advice from the post in Analytics Vidhya. “Dataframe is much faster than RDD because it has metadata (some information about data) associated with it, which allows Spark to optimize query plan.” You can find a comprehensive introduction from the original post. And there’s also an informative post on Databricks comparing different data structures of Apache Spark: “A Tale of Three Apache Spark APIs: RDDs, DataFrames, and Datasets”. Then I figured out that I need to use SparkML instead SparkMLLib if I want to deal with Dataframe. SparkMLLib is used with RDD, while SparkML supports Dataframe. One more thing to note is that I will work in local mode with my laptop. The local mode is often used for prototyping, development, debugging, and testing. However, as Spark’s local mode is fully compatible with the cluster mode, codes written locally can be run on a cluster with just a few additional steps. In order to use PySpark in Jupyter Notebook, you should either configure PySpark driver or use a package called Findspark to make a Spark Context available in your Jupyter Notebook. You can easily install Findspark by “pip install findspark” on your command line. Let’s first load some of the basic dependencies we need. *In addition to short code blocks I will attach, you can find the link for the whole Jupyter Notebook at the end of this post. import findsparkfindspark.init()import pyspark as psimport warningsfrom pyspark.sql import SQLContext First step in any Apache programming is to create a SparkContext. SparkContext is needed when we want to execute operations in a cluster. SparkContext tells Spark how and where to access a cluster. It is first step to connect with Apache Cluster. try: # create SparkContext on all CPUs available: in my case I have 4 CPUs on my laptop sc = ps.SparkContext('local[4]') sqlContext = SQLContext(sc) print("Just created a SparkContext")except ValueError: warnings.warn("SparkContext already exists in this scope") The dataset I’ll use for this post is annotated Tweets from “Sentiment140”. It originated from a Stanford research project, and I used this dataset for my previous series of Twitter sentiment analysis. Since I already cleaned the tweets during the process of my previous project, I will use pre-cleaned tweets. If you want to know more in detail about the cleaning process I took, you can check my previous post: “Another Twitter sentiment analysis with Python-Part 2” . df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('project-capstone/Twitter_sentiment_analysis/clean_tweet.csv')type(df) df.show(5) df = df.dropna()df.count() After successfully loading the data as Spark Dataframe, we can take a peek at the data by calling .show(), which is equivalent to Pandas .head(). After dropping NA, we have a bit less than 1.6 million Tweets. I will split this into three parts; training, validation, test. Since I have around 1.6 million entries, 1% each for validation and test set will be enough to test the models. (train_set, val_set, test_set) = df.randomSplit([0.98, 0.01, 0.01], seed = 2000) Through my previous attempt at sentiment analysis with Pandas and Scikit-Learn, I learned that TF-IDF with Logistic Regression is quite a strong combination, and showed robust performance, as high as Word2Vec + Convolutional Neural Network model. So in this post, I will try to implement TF-IDF + Logistic Regression model with PySpark. By the way, if you want to know more in detail about how TF-IDF is calculated, please check my previous post: “Another Twitter sentiment analysis with Python — Part 5 (Tfidf vectorizer, model comparison, lexical approach)” from pyspark.ml.classification import LogisticRegressionlr = LogisticRegression(maxIter=100)lrModel = lr.fit(train_df)predictions = lrModel.transform(val_df)from pyspark.ml.evaluation import BinaryClassificationEvaluatorevaluator = BinaryClassificationEvaluator(rawPredictionCol="rawPrediction")evaluator.evaluate(predictions) 0.86! That looks good, maybe too good. Because I already tried the same combination of techniques with the same data in Pandas and SKLearn, I know that the result for unigram TF-IDF with Logistic Regression is around 80% accuracy. There can be some slight difference due to the detailed model parameters, but still, this looks too good. And by looking at the Spark documentation I realised that what BinaryClassificationEvaluator evaluates is by default areaUnderROC. And for binary classification, Spark doesn’t support accuracy as a metric. But I can still calculate accuracy by counting the number of predictions matching the label and dividing it by the total entries. accuracy = predictions.filter(predictions.label == predictions.prediction).count() / float(val_set.count())accuracy Now it looks more plausible, actually, the accuracy is slightly lower than what I have seen from SKLearn’s result. There’s another way that you can get term frequency for IDF (Inverse Document Frequency) calculation. It is CountVectorizer in SparkML. Apart from the reversibility of the features (vocabularies), there is an important difference in how each of them filters top features. In case of HashingTF it is dimensionality reduction with possible collisions. CountVectorizer discards infrequent tokens. Let’s see if performance changes if we use CountVectorizer instead of HashingTF. It looks like using CountVectorizer has improved the performance a little bit. In Scikit-Learn, n-gram implementation is fairly easy. You can define a range of n-grams when you call TfIdf Vectorizer. But with Spark, it is a bit more complicated. It does not automatically combine features from different n-grams, so I had to use VectorAssembler in the pipeline, to combine the features I get from each n-gram. I first tried to extract around 16,000 features from unigram, bigram, trigram. This means I will get around 48,000 features in total. Then I implemented Chi-Squared feature selection to reduce the number of features to 16,000 in total. And now I’m ready to run the function I defined above. %%timetrigram_pipelineFit = build_trigrams().fit(train_set)predictions = trigram_pipelineFit.transform(val_set)accuracy = predictions.filter(predictions.label == predictions.prediction).count() / float(dev_set.count())roc_auc = evaluator.evaluate(predictions)# print accuracy, roc_aucprint "Accuracy Score: {0:.4f}".format(accuracy)print "ROC-AUC: {0:.4f}".format(roc_auc) Accuracy has improved, but as you might have noticed, fitting the model took 4 hours! And this is mainly because of ChiSqSelector. What if I extract 5,460 features each from unigram, bigram, trigram in the first place, to have around 16,000 features in total in the end, without Chi Squared feature selection? %%timetrigramwocs_pipelineFit = build_ngrams_wocs().fit(train_set)predictions_wocs = trigramwocs_pipelineFit.transform(val_set)accuracy_wocs = predictions_wocs.filter(predictions_wocs.label == predictions_wocs.prediction).count() / float(val_set.count())roc_auc_wocs = evaluator.evaluate(predictions_wocs)# print accuracy, roc_aucprint "Accuracy Score: {0:.4f}".format(accuracy_wocs)print "ROC-AUC: {0:.4f}".format(roc_auc_wocs) This has given me almost same result, marginally lower, but the difference is in the fourth digit. Considering it takes only 6 mins without ChiSqSelector, I definitely choose the model without ChiSqSelector. And finally, let’s try this model on the final test set. test_predictions = trigramwocs_pipelineFit.transform(test_set)test_accuracy = test_predictions.filter(test_predictions.label == test_predictions.prediction).count() / float(test_set.count())test_roc_auc = evaluator.evaluate(test_predictions)# print accuracy, roc_aucprint "Accuracy Score: {0:.4f}".format(test_accuracy)print "ROC-AUC: {0:.4f}".format(test_roc_auc) Final test set accuracy is 81.22% with ROC-AUC 0.8862. Through this post, I have implemented a simple sentiment analysis model with PySpark. Even though it might not be an advanced level use of PySpark, but I believe it is important to keep expose myself to new environment and new challenges. Exploring some basic functions of PySpark really sparked (no pun intended) my interest. I am attending Spark London Meetup tomorrow (13/03/2018) for “Apache Spark: Deep Learning Pipelines, PySpark MLLib and models in Streams”. I can’t wait to explore deeper into PySpark world!! Thank you for reading and you can find the Jupyter Notebook from the below link:
[ { "code": null, "e": 634, "s": 272, "text": "One of the tools I’m deeply interested but haven’t had many chances to explore is Apache Spark. Most of the time, Pandas and Scikit-Learn is enough to handle the size of data I’m trying to build a model on. But that also means that I haven’t had a chance to deal with petabytes of data yet, and I want to be prepared for the case I’m faced with a real big-data." }, { "code": null, "e": 861, "s": 634, "text": "I have tried some basic data manipulation with PySpark before, but only to a very basic level. I want to learn more and be more comfortable in using PySpark. This post is my endeavour to have a better understanding of PySpark." }, { "code": null, "e": 1262, "s": 861, "text": "Python is great for data science modelling, thanks to its numerous modules and packages that help achieve data science goals. But what if the data you are dealing with cannot be fit into a single machine? Maybe you can implement careful sampling to do your analysis on a single machine, but with distributed computing framework like PySpark, you can efficiently implement the task for large datasets." }, { "code": null, "e": 1611, "s": 1262, "text": "Spark API is available in multiple programming languages (Scala, Java, Python and R). There are debates about how Spark performance varies depending on which language you run it on, but since the main language I have been using is Python, I will focus on PySpark without going into too much detail of what language should I choose for Apache Spark." }, { "code": null, "e": 2180, "s": 1611, "text": "Spark has three different data structures available through its APIs: RDD, Dataframe (this is different from Pandas data frame), Dataset. For this post, I will work with Dataframe, and the corresponding machine learning library SparkML. I first decided on the data structure I would like to use based on the advice from the post in Analytics Vidhya. “Dataframe is much faster than RDD because it has metadata (some information about data) associated with it, which allows Spark to optimize query plan.” You can find a comprehensive introduction from the original post." }, { "code": null, "e": 2353, "s": 2180, "text": "And there’s also an informative post on Databricks comparing different data structures of Apache Spark: “A Tale of Three Apache Spark APIs: RDDs, DataFrames, and Datasets”." }, { "code": null, "e": 2515, "s": 2353, "text": "Then I figured out that I need to use SparkML instead SparkMLLib if I want to deal with Dataframe. SparkMLLib is used with RDD, while SparkML supports Dataframe." }, { "code": null, "e": 2825, "s": 2515, "text": "One more thing to note is that I will work in local mode with my laptop. The local mode is often used for prototyping, development, debugging, and testing. However, as Spark’s local mode is fully compatible with the cluster mode, codes written locally can be run on a cluster with just a few additional steps." }, { "code": null, "e": 3146, "s": 2825, "text": "In order to use PySpark in Jupyter Notebook, you should either configure PySpark driver or use a package called Findspark to make a Spark Context available in your Jupyter Notebook. You can easily install Findspark by “pip install findspark” on your command line. Let’s first load some of the basic dependencies we need." }, { "code": null, "e": 3273, "s": 3146, "text": "*In addition to short code blocks I will attach, you can find the link for the whole Jupyter Notebook at the end of this post." }, { "code": null, "e": 3375, "s": 3273, "text": "import findsparkfindspark.init()import pyspark as psimport warningsfrom pyspark.sql import SQLContext" }, { "code": null, "e": 3622, "s": 3375, "text": "First step in any Apache programming is to create a SparkContext. SparkContext is needed when we want to execute operations in a cluster. SparkContext tells Spark how and where to access a cluster. It is first step to connect with Apache Cluster." }, { "code": null, "e": 3900, "s": 3622, "text": "try: # create SparkContext on all CPUs available: in my case I have 4 CPUs on my laptop sc = ps.SparkContext('local[4]') sqlContext = SQLContext(sc) print(\"Just created a SparkContext\")except ValueError: warnings.warn(\"SparkContext already exists in this scope\")" }, { "code": null, "e": 4371, "s": 3900, "text": "The dataset I’ll use for this post is annotated Tweets from “Sentiment140”. It originated from a Stanford research project, and I used this dataset for my previous series of Twitter sentiment analysis. Since I already cleaned the tweets during the process of my previous project, I will use pre-cleaned tweets. If you want to know more in detail about the cleaning process I took, you can check my previous post: “Another Twitter sentiment analysis with Python-Part 2” ." }, { "code": null, "e": 4546, "s": 4371, "text": "df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('project-capstone/Twitter_sentiment_analysis/clean_tweet.csv')type(df)" }, { "code": null, "e": 4557, "s": 4546, "text": "df.show(5)" }, { "code": null, "e": 4584, "s": 4557, "text": "df = df.dropna()df.count()" }, { "code": null, "e": 4969, "s": 4584, "text": "After successfully loading the data as Spark Dataframe, we can take a peek at the data by calling .show(), which is equivalent to Pandas .head(). After dropping NA, we have a bit less than 1.6 million Tweets. I will split this into three parts; training, validation, test. Since I have around 1.6 million entries, 1% each for validation and test set will be enough to test the models." }, { "code": null, "e": 5050, "s": 4969, "text": "(train_set, val_set, test_set) = df.randomSplit([0.98, 0.01, 0.01], seed = 2000)" }, { "code": null, "e": 5387, "s": 5050, "text": "Through my previous attempt at sentiment analysis with Pandas and Scikit-Learn, I learned that TF-IDF with Logistic Regression is quite a strong combination, and showed robust performance, as high as Word2Vec + Convolutional Neural Network model. So in this post, I will try to implement TF-IDF + Logistic Regression model with PySpark." }, { "code": null, "e": 5610, "s": 5387, "text": "By the way, if you want to know more in detail about how TF-IDF is calculated, please check my previous post: “Another Twitter sentiment analysis with Python — Part 5 (Tfidf vectorizer, model comparison, lexical approach)”" }, { "code": null, "e": 5937, "s": 5610, "text": "from pyspark.ml.classification import LogisticRegressionlr = LogisticRegression(maxIter=100)lrModel = lr.fit(train_df)predictions = lrModel.transform(val_df)from pyspark.ml.evaluation import BinaryClassificationEvaluatorevaluator = BinaryClassificationEvaluator(rawPredictionCol=\"rawPrediction\")evaluator.evaluate(predictions)" }, { "code": null, "e": 6274, "s": 5937, "text": "0.86! That looks good, maybe too good. Because I already tried the same combination of techniques with the same data in Pandas and SKLearn, I know that the result for unigram TF-IDF with Logistic Regression is around 80% accuracy. There can be some slight difference due to the detailed model parameters, but still, this looks too good." }, { "code": null, "e": 6405, "s": 6274, "text": "And by looking at the Spark documentation I realised that what BinaryClassificationEvaluator evaluates is by default areaUnderROC." }, { "code": null, "e": 6610, "s": 6405, "text": "And for binary classification, Spark doesn’t support accuracy as a metric. But I can still calculate accuracy by counting the number of predictions matching the label and dividing it by the total entries." }, { "code": null, "e": 6726, "s": 6610, "text": "accuracy = predictions.filter(predictions.label == predictions.prediction).count() / float(val_set.count())accuracy" }, { "code": null, "e": 6841, "s": 6726, "text": "Now it looks more plausible, actually, the accuracy is slightly lower than what I have seen from SKLearn’s result." }, { "code": null, "e": 7235, "s": 6841, "text": "There’s another way that you can get term frequency for IDF (Inverse Document Frequency) calculation. It is CountVectorizer in SparkML. Apart from the reversibility of the features (vocabularies), there is an important difference in how each of them filters top features. In case of HashingTF it is dimensionality reduction with possible collisions. CountVectorizer discards infrequent tokens." }, { "code": null, "e": 7316, "s": 7235, "text": "Let’s see if performance changes if we use CountVectorizer instead of HashingTF." }, { "code": null, "e": 7395, "s": 7316, "text": "It looks like using CountVectorizer has improved the performance a little bit." }, { "code": null, "e": 7726, "s": 7395, "text": "In Scikit-Learn, n-gram implementation is fairly easy. You can define a range of n-grams when you call TfIdf Vectorizer. But with Spark, it is a bit more complicated. It does not automatically combine features from different n-grams, so I had to use VectorAssembler in the pipeline, to combine the features I get from each n-gram." }, { "code": null, "e": 7962, "s": 7726, "text": "I first tried to extract around 16,000 features from unigram, bigram, trigram. This means I will get around 48,000 features in total. Then I implemented Chi-Squared feature selection to reduce the number of features to 16,000 in total." }, { "code": null, "e": 8017, "s": 7962, "text": "And now I’m ready to run the function I defined above." }, { "code": null, "e": 8390, "s": 8017, "text": "%%timetrigram_pipelineFit = build_trigrams().fit(train_set)predictions = trigram_pipelineFit.transform(val_set)accuracy = predictions.filter(predictions.label == predictions.prediction).count() / float(dev_set.count())roc_auc = evaluator.evaluate(predictions)# print accuracy, roc_aucprint \"Accuracy Score: {0:.4f}\".format(accuracy)print \"ROC-AUC: {0:.4f}\".format(roc_auc)" }, { "code": null, "e": 8521, "s": 8390, "text": "Accuracy has improved, but as you might have noticed, fitting the model took 4 hours! And this is mainly because of ChiSqSelector." }, { "code": null, "e": 8700, "s": 8521, "text": "What if I extract 5,460 features each from unigram, bigram, trigram in the first place, to have around 16,000 features in total in the end, without Chi Squared feature selection?" }, { "code": null, "e": 9129, "s": 8700, "text": "%%timetrigramwocs_pipelineFit = build_ngrams_wocs().fit(train_set)predictions_wocs = trigramwocs_pipelineFit.transform(val_set)accuracy_wocs = predictions_wocs.filter(predictions_wocs.label == predictions_wocs.prediction).count() / float(val_set.count())roc_auc_wocs = evaluator.evaluate(predictions_wocs)# print accuracy, roc_aucprint \"Accuracy Score: {0:.4f}\".format(accuracy_wocs)print \"ROC-AUC: {0:.4f}\".format(roc_auc_wocs)" }, { "code": null, "e": 9337, "s": 9129, "text": "This has given me almost same result, marginally lower, but the difference is in the fourth digit. Considering it takes only 6 mins without ChiSqSelector, I definitely choose the model without ChiSqSelector." }, { "code": null, "e": 9394, "s": 9337, "text": "And finally, let’s try this model on the final test set." }, { "code": null, "e": 9759, "s": 9394, "text": "test_predictions = trigramwocs_pipelineFit.transform(test_set)test_accuracy = test_predictions.filter(test_predictions.label == test_predictions.prediction).count() / float(test_set.count())test_roc_auc = evaluator.evaluate(test_predictions)# print accuracy, roc_aucprint \"Accuracy Score: {0:.4f}\".format(test_accuracy)print \"ROC-AUC: {0:.4f}\".format(test_roc_auc)" }, { "code": null, "e": 9814, "s": 9759, "text": "Final test set accuracy is 81.22% with ROC-AUC 0.8862." }, { "code": null, "e": 10141, "s": 9814, "text": "Through this post, I have implemented a simple sentiment analysis model with PySpark. Even though it might not be an advanced level use of PySpark, but I believe it is important to keep expose myself to new environment and new challenges. Exploring some basic functions of PySpark really sparked (no pun intended) my interest." }, { "code": null, "e": 10332, "s": 10141, "text": "I am attending Spark London Meetup tomorrow (13/03/2018) for “Apache Spark: Deep Learning Pipelines, PySpark MLLib and models in Streams”. I can’t wait to explore deeper into PySpark world!!" } ]
SQL - ALTER TABLE Command
The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table. You should also use the ALTER TABLE command to add and drop various constraints on an existing table. The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows. ALTER TABLE table_name ADD column_name datatype; The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows. ALTER TABLE table_name DROP COLUMN column_name; The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a table is as follows. ALTER TABLE table_name MODIFY COLUMN column_name datatype; The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column in a table is as follows. ALTER TABLE table_name MODIFY column_name datatype NOT NULL; The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows. ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...); The basic syntax of an ALTER TABLE command to ADD CHECK CONSTRAINT to a table is as follows. ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION); The basic syntax of an ALTER TABLE command to ADD PRIMARY KEY constraint to a table is as follows. ALTER TABLE table_name ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...); The basic syntax of an ALTER TABLE command to DROP CONSTRAINT from a table is as follows. ALTER TABLE table_name DROP CONSTRAINT MyUniqueConstraint; If you're using MySQL, the code is as follows − ALTER TABLE table_name DROP INDEX MyUniqueConstraint; The basic syntax of an ALTER TABLE command to DROP PRIMARY KEY constraint from a table is as follows. ALTER TABLE table_name DROP CONSTRAINT MyPrimaryKey; If you're using MySQL, the code is as follows − ALTER TABLE table_name DROP PRIMARY KEY; Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is the example to ADD a New Column to an existing table − ALTER TABLE CUSTOMERS ADD SEX char(1); Now, the CUSTOMERS table is changed and following would be output from the SELECT statement. +----+---------+-----+-----------+----------+------+ | ID | NAME | AGE | ADDRESS | SALARY | SEX | +----+---------+-----+-----------+----------+------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | NULL | | 2 | Ramesh | 25 | Delhi | 1500.00 | NULL | | 3 | kaushik | 23 | Kota | 2000.00 | NULL | | 4 | kaushik | 25 | Mumbai | 6500.00 | NULL | | 5 | Hardik | 27 | Bhopal | 8500.00 | NULL | | 6 | Komal | 22 | MP | 4500.00 | NULL | | 7 | Muffy | 24 | Indore | 10000.00 | NULL | +----+---------+-----+-----------+----------+------+ Following is the example to DROP sex column from the existing table. ALTER TABLE CUSTOMERS DROP SEX; Now, the CUSTOMERS table is changed and following would be the output from the SELECT statement. +----+---------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Ramesh | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | kaushik | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+---------+-----+-----------+----------+ 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2646, "s": 2453, "text": "The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table. You should also use the ALTER TABLE command to add and drop various constraints on an existing table." }, { "code": null, "e": 2745, "s": 2646, "text": "The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows." }, { "code": null, "e": 2795, "s": 2745, "text": "ALTER TABLE table_name ADD column_name datatype;\n" }, { "code": null, "e": 2889, "s": 2795, "text": "The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows." }, { "code": null, "e": 2938, "s": 2889, "text": "ALTER TABLE table_name DROP COLUMN column_name;\n" }, { "code": null, "e": 3043, "s": 2938, "text": "The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a table is as follows." }, { "code": null, "e": 3103, "s": 3043, "text": "ALTER TABLE table_name MODIFY COLUMN column_name datatype;\n" }, { "code": null, "e": 3213, "s": 3103, "text": "The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column in a table is as follows." }, { "code": null, "e": 3275, "s": 3213, "text": "ALTER TABLE table_name MODIFY column_name datatype NOT NULL;\n" }, { "code": null, "e": 3358, "s": 3275, "text": "The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows." }, { "code": null, "e": 3446, "s": 3358, "text": "ALTER TABLE table_name \nADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);\n" }, { "code": null, "e": 3539, "s": 3446, "text": "The basic syntax of an ALTER TABLE command to ADD CHECK CONSTRAINT to a table is as follows." }, { "code": null, "e": 3617, "s": 3539, "text": "ALTER TABLE table_name \nADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);\n" }, { "code": null, "e": 3716, "s": 3617, "text": "The basic syntax of an ALTER TABLE command to ADD PRIMARY KEY constraint to a table is as follows." }, { "code": null, "e": 3804, "s": 3716, "text": "ALTER TABLE table_name \nADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);\n" }, { "code": null, "e": 3894, "s": 3804, "text": "The basic syntax of an ALTER TABLE command to DROP CONSTRAINT from a table is as follows." }, { "code": null, "e": 3955, "s": 3894, "text": "ALTER TABLE table_name \nDROP CONSTRAINT MyUniqueConstraint;\n" }, { "code": null, "e": 4003, "s": 3955, "text": "If you're using MySQL, the code is as follows −" }, { "code": null, "e": 4058, "s": 4003, "text": "ALTER TABLE table_name \nDROP INDEX MyUniqueConstraint;" }, { "code": null, "e": 4160, "s": 4058, "text": "The basic syntax of an ALTER TABLE command to DROP PRIMARY KEY constraint from a table is as follows." }, { "code": null, "e": 4215, "s": 4160, "text": "ALTER TABLE table_name \nDROP CONSTRAINT MyPrimaryKey;\n" }, { "code": null, "e": 4263, "s": 4215, "text": "If you're using MySQL, the code is as follows −" }, { "code": null, "e": 4305, "s": 4263, "text": "ALTER TABLE table_name \nDROP PRIMARY KEY;" }, { "code": null, "e": 4365, "s": 4305, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 4882, "s": 4365, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 4950, "s": 4882, "text": "Following is the example to ADD a New Column to an existing table −" }, { "code": null, "e": 4989, "s": 4950, "text": "ALTER TABLE CUSTOMERS ADD SEX char(1);" }, { "code": null, "e": 5082, "s": 4989, "text": "Now, the CUSTOMERS table is changed and following would be output from the SELECT statement." }, { "code": null, "e": 5666, "s": 5082, "text": "+----+---------+-----+-----------+----------+------+\n| ID | NAME | AGE | ADDRESS | SALARY | SEX |\n+----+---------+-----+-----------+----------+------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | NULL |\n| 2 | Ramesh | 25 | Delhi | 1500.00 | NULL |\n| 3 | kaushik | 23 | Kota | 2000.00 | NULL |\n| 4 | kaushik | 25 | Mumbai | 6500.00 | NULL |\n| 5 | Hardik | 27 | Bhopal | 8500.00 | NULL |\n| 6 | Komal | 22 | MP | 4500.00 | NULL |\n| 7 | Muffy | 24 | Indore | 10000.00 | NULL |\n+----+---------+-----+-----------+----------+------+\n" }, { "code": null, "e": 5735, "s": 5666, "text": "Following is the example to DROP sex column from the existing table." }, { "code": null, "e": 5767, "s": 5735, "text": "ALTER TABLE CUSTOMERS DROP SEX;" }, { "code": null, "e": 5864, "s": 5767, "text": "Now, the CUSTOMERS table is changed and following would be the output from the SELECT statement." }, { "code": null, "e": 6371, "s": 5864, "text": "+----+---------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+---------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Ramesh | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | kaushik | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+---------+-----+-----------+----------+\n" }, { "code": null, "e": 6404, "s": 6371, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 6418, "s": 6404, "text": " Anadi Sharma" }, { "code": null, "e": 6451, "s": 6418, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 6465, "s": 6451, "text": " Anadi Sharma" }, { "code": null, "e": 6500, "s": 6465, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6514, "s": 6500, "text": " Anadi Sharma" }, { "code": null, "e": 6547, "s": 6514, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 6569, "s": 6547, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 6604, "s": 6569, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6658, "s": 6604, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 6691, "s": 6658, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 6719, "s": 6691, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6726, "s": 6719, "text": " Print" }, { "code": null, "e": 6737, "s": 6726, "text": " Add Notes" } ]
How to create rounded and circular images with CSS?
Following is the code to create rounded and circular images with CSS − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> img { border-radius: 50%; width: 300px; height: 300px; } </style> </head> <body> <h1>Rounded Images Example</h1> <img src="https://i.picsum.photos/id/271/400/400.jpg"> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1133, "s": 1062, "text": "Following is the code to create rounded and circular images with CSS −" }, { "code": null, "e": 1144, "s": 1133, "text": " Live Demo" }, { "code": null, "e": 1444, "s": 1144, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\nimg {\n border-radius: 50%;\n width: 300px;\n height: 300px;\n}\n</style>\n</head>\n<body>\n<h1>Rounded Images Example</h1>\n<img src=\"https://i.picsum.photos/id/271/400/400.jpg\">\n</body>\n</html>" }, { "code": null, "e": 1495, "s": 1444, "text": "The above code will produce the following output −" } ]
Print matrix in diagonal pattern
Given a 2d array of n*n and the task is to find the antispiral arrangement of the given matrix Input : arr[4][4]={1,2,3,4, 5,6,7,8, 9,10,11,12 13,14,15,16} Output : 1 6 11 16 4 7 10 13 START Step 1 -> declare start variables as r=4, c=4, i and j Step 2 -> initialize array as mat[r][c] with elements Step 3 -> Loop For i=0 and i<r and i++ Print mat[i][j] Step 4 -> print \n Step 5 -> Loop For i=0 and i<r and i++ Print mat[i][4-1-i] End STOP #include<iostream> #include <bits/stdc++.h> using namespace std; int main() { int R=4,C=4,i,j; int mat[R][C] = { {1,2,3, 4}, {5,6,7,8},{9,10,11,12},{13,14,15,16}}; for(i=0;i<R;i++) { cout<<mat[i][i]<<" "; } cout<<"\n"; for(i=0;i<R;i++) { cout<<mat[i][4-1-i]<<" "; } } if we run the above program then it will generate the following output 1 6 11 16 4 7 10 13
[ { "code": null, "e": 1157, "s": 1062, "text": "Given a 2d array of n*n and the task is to find the antispiral arrangement of the given matrix" }, { "code": null, "e": 1256, "s": 1157, "text": "Input : arr[4][4]={1,2,3,4,\n 5,6,7,8,\n 9,10,11,12\n 13,14,15,16}\nOutput : 1 6 11 16 4 7 10 13" }, { "code": null, "e": 1519, "s": 1256, "text": "START\nStep 1 -> declare start variables as r=4, c=4, i and j\nStep 2 -> initialize array as mat[r][c] with elements\nStep 3 -> Loop For i=0 and i<r and i++\n Print mat[i][j]\nStep 4 -> print \\n\nStep 5 -> Loop For i=0 and i<r and i++\n Print mat[i][4-1-i]\nEnd\nSTOP" }, { "code": null, "e": 1820, "s": 1519, "text": "#include<iostream>\n#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n int R=4,C=4,i,j;\n int mat[R][C] = { {1,2,3, 4}, {5,6,7,8},{9,10,11,12},{13,14,15,16}};\n for(i=0;i<R;i++) {\n cout<<mat[i][i]<<\" \";\n }\n cout<<\"\\n\";\n for(i=0;i<R;i++) {\n cout<<mat[i][4-1-i]<<\" \";\n }\n}" }, { "code": null, "e": 1891, "s": 1820, "text": "if we run the above program then it will generate the following output" }, { "code": null, "e": 1911, "s": 1891, "text": "1 6 11 16\n4 7 10 13" } ]
Javascript performance test - for vs for each vs (map, reduce, filter, find). | by Deepak Gupta | Towards Data Science
We all know that for loop are faster than for each or javascript function since under the hood of javascript functions might be using for loops or something else which I’m not sure. I did a simple test with an array of objects and doing some operation via for loop/ for each / javascript functions and observing the time it takes to execute. These results are from small examples and may vary as per the operation performed, the choice of execution env. and choice of VM. // calculated the sum of upVotesconst posts = [ {id: 1, upVotes: 2}, {id: 2, upVotes: 18}, {id: 3, upVotes: 1}, {id: 4, upVotes: 30}, {id: 5, upVotes: 50} ];let sum = 0;console.time('reduce');sum = posts.reduce((s, p)=> s+=p.upVotes,0);console.timeEnd('reduce')sum = 0;console.time('for loop');for(let i=0; i<posts.length; i++) { sum += posts[i].upVotes;}console.timeEnd('for loop');sum = 0;console.time('for each');posts.forEach(element => { sum += element.upVotes;});console.timeEnd('for each'); Note: Below is the list of results and code can be found here . Map/Reduce/Filter/Find are slow because of many reasons, some of them are They have a call back to execute so that acts as an overhead.There are a lot of corner cases that javascript functions consider like getters, sparse array and checking arguments that are passed is an array or not which adds up to overhead. They have a call back to execute so that acts as an overhead. There are a lot of corner cases that javascript functions consider like getters, sparse array and checking arguments that are passed is an array or not which adds up to overhead. I found a lib. that reimplement several common builtin native JavaScript functions. But the choice of usage depends on not just the performance alone, there are more factors to be considered, some of them are: Code readability and maintainabilityEase codeQuickness to codeImplementation vs optimizationPersonal choice Code readability and maintainability Ease code Quickness to code Implementation vs optimization Personal choice Personally, I love map, reduce, filter, find and I am using them for a long time. They helped me write clean, precise, fast and to the point code which aligns with my thought process. I use for a loop when I have no choice left. As far as optimization is concerned, map/reduce/filter/find a replacement should be the last option or not an option depending upon what level of optimization is required. Note: If you’re using loops, always use them idiomatically since compilers are now smart enough to correctly optimize idiomatic loops Update: Here you can find the result for the large data set and heavy computation. I write articles on overflowjs.com and part 2 of this article comparing ramada inline caching warm cache, and some of GC stuff. So, Don't forget to stay tuned on overflowjs.com Please consider entering your email here if you’d like to be added to my email list and follow me on medium to read more article on javascript and on github to see my crazy code. If anything is not clear or you want to point out something, please comment down below. Javascript Execution Context and HoistingJavascript — Generator-Yield/Next & Async-Await 🤔Understanding Javascript ‘this’ keyword (Context).Javascript data structure with map, reduce, filterJavascript- Currying VS Partial ApplicationJavascript ES6 — Iterables and IteratorsJavascript performance test — for vs for each vs (map, reduce, filter, find).Javascript — ProxyJavascript — ScopesImage Object detection with Tensorflow-js 🤔Nodejs app structure — To build highly scalable architecture.Node.js 10.0.0, What to expect as a Backend developer/Security enthusiast?Image Processing — Making Custom Image Filters in React.jsGoogle India Interview Questions Javascript Execution Context and Hoisting Javascript — Generator-Yield/Next & Async-Await 🤔 Understanding Javascript ‘this’ keyword (Context). Javascript data structure with map, reduce, filter Javascript- Currying VS Partial Application Javascript ES6 — Iterables and Iterators Javascript performance test — for vs for each vs (map, reduce, filter, find). Javascript — Proxy Javascript — Scopes Image Object detection with Tensorflow-js 🤔 Nodejs app structure — To build highly scalable architecture. Node.js 10.0.0, What to expect as a Backend developer/Security enthusiast? Image Processing — Making Custom Image Filters in React.js Google India Interview Questions
[ { "code": null, "e": 513, "s": 171, "text": "We all know that for loop are faster than for each or javascript function since under the hood of javascript functions might be using for loops or something else which I’m not sure. I did a simple test with an array of objects and doing some operation via for loop/ for each / javascript functions and observing the time it takes to execute." }, { "code": null, "e": 643, "s": 513, "text": "These results are from small examples and may vary as per the operation performed, the choice of execution env. and choice of VM." }, { "code": null, "e": 1156, "s": 643, "text": "// calculated the sum of upVotesconst posts = [ {id: 1, upVotes: 2}, {id: 2, upVotes: 18}, {id: 3, upVotes: 1}, {id: 4, upVotes: 30}, {id: 5, upVotes: 50} ];let sum = 0;console.time('reduce');sum = posts.reduce((s, p)=> s+=p.upVotes,0);console.timeEnd('reduce')sum = 0;console.time('for loop');for(let i=0; i<posts.length; i++) { sum += posts[i].upVotes;}console.timeEnd('for loop');sum = 0;console.time('for each');posts.forEach(element => { sum += element.upVotes;});console.timeEnd('for each');" }, { "code": null, "e": 1220, "s": 1156, "text": "Note: Below is the list of results and code can be found here ." }, { "code": null, "e": 1294, "s": 1220, "text": "Map/Reduce/Filter/Find are slow because of many reasons, some of them are" }, { "code": null, "e": 1534, "s": 1294, "text": "They have a call back to execute so that acts as an overhead.There are a lot of corner cases that javascript functions consider like getters, sparse array and checking arguments that are passed is an array or not which adds up to overhead." }, { "code": null, "e": 1596, "s": 1534, "text": "They have a call back to execute so that acts as an overhead." }, { "code": null, "e": 1775, "s": 1596, "text": "There are a lot of corner cases that javascript functions consider like getters, sparse array and checking arguments that are passed is an array or not which adds up to overhead." }, { "code": null, "e": 1859, "s": 1775, "text": "I found a lib. that reimplement several common builtin native JavaScript functions." }, { "code": null, "e": 1985, "s": 1859, "text": "But the choice of usage depends on not just the performance alone, there are more factors to be considered, some of them are:" }, { "code": null, "e": 2093, "s": 1985, "text": "Code readability and maintainabilityEase codeQuickness to codeImplementation vs optimizationPersonal choice" }, { "code": null, "e": 2130, "s": 2093, "text": "Code readability and maintainability" }, { "code": null, "e": 2140, "s": 2130, "text": "Ease code" }, { "code": null, "e": 2158, "s": 2140, "text": "Quickness to code" }, { "code": null, "e": 2189, "s": 2158, "text": "Implementation vs optimization" }, { "code": null, "e": 2205, "s": 2189, "text": "Personal choice" }, { "code": null, "e": 2434, "s": 2205, "text": "Personally, I love map, reduce, filter, find and I am using them for a long time. They helped me write clean, precise, fast and to the point code which aligns with my thought process. I use for a loop when I have no choice left." }, { "code": null, "e": 2606, "s": 2434, "text": "As far as optimization is concerned, map/reduce/filter/find a replacement should be the last option or not an option depending upon what level of optimization is required." }, { "code": null, "e": 2740, "s": 2606, "text": "Note: If you’re using loops, always use them idiomatically since compilers are now smart enough to correctly optimize idiomatic loops" }, { "code": null, "e": 2823, "s": 2740, "text": "Update: Here you can find the result for the large data set and heavy computation." }, { "code": null, "e": 3000, "s": 2823, "text": "I write articles on overflowjs.com and part 2 of this article comparing ramada inline caching warm cache, and some of GC stuff. So, Don't forget to stay tuned on overflowjs.com" }, { "code": null, "e": 3267, "s": 3000, "text": "Please consider entering your email here if you’d like to be added to my email list and follow me on medium to read more article on javascript and on github to see my crazy code. If anything is not clear or you want to point out something, please comment down below." }, { "code": null, "e": 3923, "s": 3267, "text": "Javascript Execution Context and HoistingJavascript — Generator-Yield/Next & Async-Await 🤔Understanding Javascript ‘this’ keyword (Context).Javascript data structure with map, reduce, filterJavascript- Currying VS Partial ApplicationJavascript ES6 — Iterables and IteratorsJavascript performance test — for vs for each vs (map, reduce, filter, find).Javascript — ProxyJavascript — ScopesImage Object detection with Tensorflow-js 🤔Nodejs app structure — To build highly scalable architecture.Node.js 10.0.0, What to expect as a Backend developer/Security enthusiast?Image Processing — Making Custom Image Filters in React.jsGoogle India Interview Questions" }, { "code": null, "e": 3965, "s": 3923, "text": "Javascript Execution Context and Hoisting" }, { "code": null, "e": 4015, "s": 3965, "text": "Javascript — Generator-Yield/Next & Async-Await 🤔" }, { "code": null, "e": 4066, "s": 4015, "text": "Understanding Javascript ‘this’ keyword (Context)." }, { "code": null, "e": 4117, "s": 4066, "text": "Javascript data structure with map, reduce, filter" }, { "code": null, "e": 4161, "s": 4117, "text": "Javascript- Currying VS Partial Application" }, { "code": null, "e": 4202, "s": 4161, "text": "Javascript ES6 — Iterables and Iterators" }, { "code": null, "e": 4280, "s": 4202, "text": "Javascript performance test — for vs for each vs (map, reduce, filter, find)." }, { "code": null, "e": 4299, "s": 4280, "text": "Javascript — Proxy" }, { "code": null, "e": 4319, "s": 4299, "text": "Javascript — Scopes" }, { "code": null, "e": 4363, "s": 4319, "text": "Image Object detection with Tensorflow-js 🤔" }, { "code": null, "e": 4425, "s": 4363, "text": "Nodejs app structure — To build highly scalable architecture." }, { "code": null, "e": 4500, "s": 4425, "text": "Node.js 10.0.0, What to expect as a Backend developer/Security enthusiast?" }, { "code": null, "e": 4559, "s": 4500, "text": "Image Processing — Making Custom Image Filters in React.js" } ]
Amazon Interview Experience (Onsite) - GeeksforGeeks
09 Mar, 2021 I had 4 interviews in Amazon Chime. Each one was 55 mins, the first 30 mins were about behavior questions(2-3) and only 25 mins for technical. Technical: Given pattern (ex: “ShC” ) and dictionary:"ShipClass","SchoolClass","Traeler","Class" Return list of strings matching this patern like: ShC -> "ShipClass", s->"ShipClass","SchoolClass","Class" TL->""Design TwitterOop: design FileFinderGiven a social network and 2 people, find the shortest friends path between them Given pattern (ex: “ShC” ) and dictionary:"ShipClass","SchoolClass","Traeler","Class" Return list of strings matching this patern like: ShC -> "ShipClass", s->"ShipClass","SchoolClass","Class" TL->"" "ShipClass","SchoolClass","Traeler","Class" Return list of strings matching this patern like: ShC -> "ShipClass", s->"ShipClass","SchoolClass","Class" TL->"" Design Twitter Oop: design FileFinder Given a social network and 2 people, find the shortest friends path between them Behaviors: The time when you fail commitment,The time when measuring customer experienceThe time when you got bad feedback from your managerThe time when you help a teammateThe time when you innovate somethingThe time when you pushing your ideaThe time when your idea was rejected The time when you fail commitment, The time when measuring customer experience The time when you got bad feedback from your manager The time when you help a teammate The time when you innovate something The time when you pushing your idea The time when your idea was rejected Tips: Behavior questions take lots of time, and it’s very important to have different prepared stories for them. You can you same story for different questions if you can show the required aspect.On the technical part, the most important thing is the idea, because you have only 25 mins. You will not have a compilator, so small mistakes in syntax are not so important.You should write clean code, but always ask the recruiter if he wants you to implement methods or not. it will help you to save time and focus on important parts. Behavior questions take lots of time, and it’s very important to have different prepared stories for them. You can you same story for different questions if you can show the required aspect. On the technical part, the most important thing is the idea, because you have only 25 mins. You will not have a compilator, so small mistakes in syntax are not so important. You should write clean code, but always ask the recruiter if he wants you to implement methods or not. it will help you to save time and focus on important parts. Good luck! Amazon Marketing Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience Amazon Interview Experience for SDE-1 (On-Campus) Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE-1 (Off-Campus) Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Persistent Systems Interview Experience (Martian Program)
[ { "code": null, "e": 25054, "s": 25026, "text": "\n09 Mar, 2021" }, { "code": null, "e": 25197, "s": 25054, "text": "I had 4 interviews in Amazon Chime. Each one was 55 mins, the first 30 mins were about behavior questions(2-3) and only 25 mins for technical." }, { "code": null, "e": 25209, "s": 25197, "text": "Technical: " }, { "code": null, "e": 25525, "s": 25209, "text": "Given pattern (ex: “ShC” ) and dictionary:\"ShipClass\",\"SchoolClass\",\"Traeler\",\"Class\"\nReturn list of strings matching this patern like:\nShC -> \"ShipClass\", s->\"ShipClass\",\"SchoolClass\",\"Class\" TL->\"\"Design TwitterOop: design FileFinderGiven a social network and 2 people, find the shortest friends path between them" }, { "code": null, "e": 25725, "s": 25525, "text": "Given pattern (ex: “ShC” ) and dictionary:\"ShipClass\",\"SchoolClass\",\"Traeler\",\"Class\"\nReturn list of strings matching this patern like:\nShC -> \"ShipClass\", s->\"ShipClass\",\"SchoolClass\",\"Class\" TL->\"\"" }, { "code": null, "e": 25883, "s": 25725, "text": "\"ShipClass\",\"SchoolClass\",\"Traeler\",\"Class\"\nReturn list of strings matching this patern like:\nShC -> \"ShipClass\", s->\"ShipClass\",\"SchoolClass\",\"Class\" TL->\"\"" }, { "code": null, "e": 25898, "s": 25883, "text": "Design Twitter" }, { "code": null, "e": 25921, "s": 25898, "text": "Oop: design FileFinder" }, { "code": null, "e": 26002, "s": 25921, "text": "Given a social network and 2 people, find the shortest friends path between them" }, { "code": null, "e": 26013, "s": 26002, "text": "Behaviors:" }, { "code": null, "e": 26283, "s": 26013, "text": "The time when you fail commitment,The time when measuring customer experienceThe time when you got bad feedback from your managerThe time when you help a teammateThe time when you innovate somethingThe time when you pushing your ideaThe time when your idea was rejected" }, { "code": null, "e": 26318, "s": 26283, "text": "The time when you fail commitment," }, { "code": null, "e": 26362, "s": 26318, "text": "The time when measuring customer experience" }, { "code": null, "e": 26415, "s": 26362, "text": "The time when you got bad feedback from your manager" }, { "code": null, "e": 26449, "s": 26415, "text": "The time when you help a teammate" }, { "code": null, "e": 26486, "s": 26449, "text": "The time when you innovate something" }, { "code": null, "e": 26522, "s": 26486, "text": "The time when you pushing your idea" }, { "code": null, "e": 26559, "s": 26522, "text": "The time when your idea was rejected" }, { "code": null, "e": 26566, "s": 26559, "text": "Tips: " }, { "code": null, "e": 27092, "s": 26566, "text": "Behavior questions take lots of time, and it’s very important to have different prepared stories for them. You can you same story for different questions if you can show the required aspect.On the technical part, the most important thing is the idea, because you have only 25 mins. You will not have a compilator, so small mistakes in syntax are not so important.You should write clean code, but always ask the recruiter if he wants you to implement methods or not. it will help you to save time and focus on important parts." }, { "code": null, "e": 27283, "s": 27092, "text": "Behavior questions take lots of time, and it’s very important to have different prepared stories for them. You can you same story for different questions if you can show the required aspect." }, { "code": null, "e": 27376, "s": 27283, "text": "On the technical part, the most important thing is the idea, because you have only 25 mins. " }, { "code": null, "e": 27458, "s": 27376, "text": "You will not have a compilator, so small mistakes in syntax are not so important." }, { "code": null, "e": 27621, "s": 27458, "text": "You should write clean code, but always ask the recruiter if he wants you to implement methods or not. it will help you to save time and focus on important parts." }, { "code": null, "e": 27632, "s": 27621, "text": "Good luck!" }, { "code": null, "e": 27639, "s": 27632, "text": "Amazon" }, { "code": null, "e": 27649, "s": 27639, "text": "Marketing" }, { "code": null, "e": 27671, "s": 27649, "text": "Interview Experiences" }, { "code": null, "e": 27678, "s": 27671, "text": "Amazon" }, { "code": null, "e": 27776, "s": 27678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27804, "s": 27776, "text": "Amazon Interview Experience" }, { "code": null, "e": 27854, "s": 27804, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 27913, "s": 27854, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 27951, "s": 27913, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 28002, "s": 27951, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 28048, "s": 28002, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 28098, "s": 28048, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 28136, "s": 28098, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 28201, "s": 28136, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" } ]
What is xpath in Selenium?
Xpath is one of the most important locators used in Selenium for identifying web elements. It works in the following ways − It navigates through the Document Object Model (DOM) with the help of elements and their attributes for identification. It navigates through the Document Object Model (DOM) with the help of elements and their attributes for identification. Although it helps to locate the elements uniquely, it is slower in terms of speed from the other locators. Although it helps to locate the elements uniquely, it is slower in terms of speed from the other locators. An xpath is represented by two ways namely ‘/ ‘and ‘// ‘. A forward single slash means absolute path. Here xpath traverses direct from parent to child in DOM. Thus in absolute xpath we have to travel from the root node to the target. Syntax − driver.findElement(By.xpath("/html/body/div/input")). A double forward ‘// ‘slash means relative path. Here xpath finds the matching element in every corner of DOM. It doesn't have a particular beginning point. Syntax − driver.findElement(By.xpath("//input[@name=’Tutorial’]")). It is always recommended to use relative xpath rather than absolute xpath. In absolute xpath, we need to specify from the root to the desired element so if any of the attributes and its value get changed in between, then our xpath will no longer be correct. Syntax for xpath − //tagname[@attribute=’value’] or //*[@attribute=’value’] Xpath basically locates elements with the help of XML path. XML known as the Extensible Markup Language.
[ { "code": null, "e": 1186, "s": 1062, "text": "Xpath is one of the most important locators used in Selenium for identifying web elements. It works in the following ways −" }, { "code": null, "e": 1306, "s": 1186, "text": "It navigates through the Document Object Model (DOM) with the help of\nelements and their attributes for identification." }, { "code": null, "e": 1426, "s": 1306, "text": "It navigates through the Document Object Model (DOM) with the help of\nelements and their attributes for identification." }, { "code": null, "e": 1533, "s": 1426, "text": "Although it helps to locate the elements uniquely, it is slower in terms of speed from the other locators." }, { "code": null, "e": 1640, "s": 1533, "text": "Although it helps to locate the elements uniquely, it is slower in terms of speed from the other locators." }, { "code": null, "e": 1874, "s": 1640, "text": "An xpath is represented by two ways namely ‘/ ‘and ‘// ‘. A forward single slash means absolute path. Here xpath traverses direct from parent to child in DOM. Thus in absolute xpath we have to travel from the root node to the target." }, { "code": null, "e": 1883, "s": 1874, "text": "Syntax −" }, { "code": null, "e": 1937, "s": 1883, "text": "driver.findElement(By.xpath(\"/html/body/div/input\"))." }, { "code": null, "e": 2094, "s": 1937, "text": "A double forward ‘// ‘slash means relative path. Here xpath finds the matching element in every corner of DOM. It doesn't have a particular beginning point." }, { "code": null, "e": 2103, "s": 2094, "text": "Syntax −" }, { "code": null, "e": 2163, "s": 2103, "text": "driver.findElement(By.xpath(\"//input[@name=’Tutorial’]\")).\n" }, { "code": null, "e": 2421, "s": 2163, "text": "It is always recommended to use relative xpath rather than absolute xpath. In absolute xpath, we need to specify from the root to the desired element so if any of the attributes and its value get changed in between, then our xpath will no longer be correct." }, { "code": null, "e": 2440, "s": 2421, "text": "Syntax for xpath −" }, { "code": null, "e": 2497, "s": 2440, "text": "//tagname[@attribute=’value’] or //*[@attribute=’value’]" }, { "code": null, "e": 2602, "s": 2497, "text": "Xpath basically locates elements with the help of XML path. XML known as the Extensible Markup Language." } ]
Asynchronous Nature in Cypress
Cypress is built on node.js server and it works with Javascript programming language. Anything which is dependent on node.js is asynchronous in nature and so Cypress commands work in that mode. When we have a group of test steps in a test case, all the steps start executing in parallel without waiting for the previous step to complete. In a synchronous execution, each test step runs in sequence and we move to the next step only if the previous step execution is done. Thus in asynchronous execution like Cypress, each test step is independent to each other even though the test steps are designed in a sequential order. In short, in an asynchronous mode each step does not take into account the result or state of the previous step execution and simply runs every steps. Cypress has come up with a wrapper which makes sure that test execution of its commands happen in sequence in which they are developed. Thus these commands are executed all at once but they are queued. However if a Javascript command works along with a Cypress command, it remains asynchronous. Now let us execute a Cypress code − // test suite describe('Tutorialspoint Test', function () { // test case it('Test Case1', function (){ // test step to launch a URL cy.visit("https://www.tutorialspoint.com/index.htm"); // enter test in the edit box cy.get('#gs_50d > tbody > tr > td'). should('have.length',2); // locate element with get and find method cy.get('#gs_50d > tbody > tr > td'). find('input') //enter test in the edit box .type('Cypress'); console.log('Tutorialspoint'); }); }); On triggering the above code for execution, if we open the browser console, we will find Tutorialspoint printed on it even before the browser is loaded. This confirms the fact that console.log test step did not wait for other test steps and prints immediately in console. Thus we see that since console.log is a Javascript command it doesn't queue itself like a Cypress compound and carries on with its execution. Cypress executes its steps serially with the help of promise handling. A promise is a programming language that determines the state of a Cypress command. There are three types of promise states as listed below − Resolved − This is the state if the test step executes without failure. Resolved − This is the state if the test step executes without failure. Pending − This is the state if the test step execution result is being awaited. Pending − This is the state if the test step execution result is being awaited. Rejected − This is the state if the test step executes with failure. Rejected − This is the state if the test step executes with failure. The following command in Cypress gets executed only after the previous command or promise response is resolved. We can implement promise in our Cypress code with the help of then() method. The code below describes the promise implemented in Javascript for each Cypress compound. This implementation makes a code dirty and lengthy. // test suite describe('Tutorialspoint Test', function () { // test case it('Test Case1', function (){ return cy.visit('https://www.tutorialspoint.com/index.htm') .then(() => { return cy.get('.product'); }) .then(($element) => { return cy.click($element); }) }) }) Cypress handles promises internally and resolves them with the help of wrappers and we can implement our code without taking into account the promise states. Thus the code readability increases to a large extent. The above code in Cypress without promise. // test suite describe('Tutorialspoint Test', function () { // test case it('Test Case1', function (){ cy.visit('https://www.tutorialspoint.com/index.htm') cy.get('.product').click(); }) }) Thus Cypress takes into account that the next step in a test case shall execute only if the prior command or promise is in resolved state.
[ { "code": null, "e": 1256, "s": 1062, "text": "Cypress is built on node.js server and it works with Javascript programming\nlanguage. Anything which is dependent on node.js is asynchronous in nature and\nso Cypress commands work in that mode." }, { "code": null, "e": 1534, "s": 1256, "text": "When we have a group of test steps in a test case, all the steps start executing in\nparallel without waiting for the previous step to complete. In a synchronous\nexecution, each test step runs in sequence and we move to the next step only if the\nprevious step execution is done." }, { "code": null, "e": 1837, "s": 1534, "text": "Thus in asynchronous execution like Cypress, each test step is independent to each\nother even though the test steps are designed in a sequential order. In short, in an\nasynchronous mode each step does not take into account the result or state of the\nprevious step execution and simply runs every steps." }, { "code": null, "e": 2132, "s": 1837, "text": "Cypress has come up with a wrapper which makes sure that test execution of its\ncommands happen in sequence in which they are developed. Thus these\ncommands are executed all at once but they are queued. However if a Javascript\ncommand works along with a Cypress command, it remains asynchronous." }, { "code": null, "e": 2168, "s": 2132, "text": "Now let us execute a Cypress code −" }, { "code": null, "e": 2689, "s": 2168, "text": "// test suite\ndescribe('Tutorialspoint Test', function () {\n // test case\n it('Test Case1', function (){\n // test step to launch a URL\n cy.visit(\"https://www.tutorialspoint.com/index.htm\");\n // enter test in the edit box\n cy.get('#gs_50d > tbody > tr > td'). should('have.length',2);\n // locate element with get and find method\n cy.get('#gs_50d > tbody > tr > td'). find('input')\n //enter test in the edit box\n .type('Cypress');\n console.log('Tutorialspoint');\n });\n});" }, { "code": null, "e": 2961, "s": 2689, "text": "On triggering the above code for execution, if we open the browser console, we will find Tutorialspoint printed on it even before the browser is loaded. This confirms the fact that console.log test step did not wait for other test steps and prints immediately in console." }, { "code": null, "e": 3174, "s": 2961, "text": "Thus we see that since console.log is a Javascript command it doesn't queue itself like a Cypress compound and carries on with its execution. Cypress executes its steps serially with the help of promise handling." }, { "code": null, "e": 3316, "s": 3174, "text": "A promise is a programming language that determines the state of a Cypress\ncommand. There are three types of promise states as listed below −" }, { "code": null, "e": 3388, "s": 3316, "text": "Resolved − This is the state if the test step executes without failure." }, { "code": null, "e": 3460, "s": 3388, "text": "Resolved − This is the state if the test step executes without failure." }, { "code": null, "e": 3540, "s": 3460, "text": "Pending − This is the state if the test step execution result is being awaited." }, { "code": null, "e": 3620, "s": 3540, "text": "Pending − This is the state if the test step execution result is being awaited." }, { "code": null, "e": 3689, "s": 3620, "text": "Rejected − This is the state if the test step executes with failure." }, { "code": null, "e": 3758, "s": 3689, "text": "Rejected − This is the state if the test step executes with failure." }, { "code": null, "e": 3947, "s": 3758, "text": "The following command in Cypress gets executed only after the previous command or promise response is resolved. We can implement promise in our Cypress code with the help of then() method." }, { "code": null, "e": 4089, "s": 3947, "text": "The code below describes the promise implemented in Javascript for each Cypress\ncompound. This implementation makes a code dirty and lengthy." }, { "code": null, "e": 4411, "s": 4089, "text": "// test suite\ndescribe('Tutorialspoint Test', function () {\n // test case\n it('Test Case1', function (){\n return cy.visit('https://www.tutorialspoint.com/index.htm')\n .then(() => {\n return cy.get('.product');\n })\n .then(($element) => {\n return cy.click($element);\n })\n })\n})" }, { "code": null, "e": 4624, "s": 4411, "text": "Cypress handles promises internally and resolves them with the help of wrappers\nand we can implement our code without taking into account the promise states.\nThus the code readability increases to a large extent." }, { "code": null, "e": 4667, "s": 4624, "text": "The above code in Cypress without promise." }, { "code": null, "e": 4878, "s": 4667, "text": "// test suite\ndescribe('Tutorialspoint Test', function () {\n // test case\n it('Test Case1', function (){\n cy.visit('https://www.tutorialspoint.com/index.htm')\n cy.get('.product').click();\n })\n})" }, { "code": null, "e": 5017, "s": 4878, "text": "Thus Cypress takes into account that the next step in a test case shall execute only\nif the prior command or promise is in resolved state." } ]
Stub
Stubs are used during Top-down integration testing, in order to simulate the behaviour of the lower-level modules that are not yet integrated. Stubs are the modules that act as temporary replacement for a called module and give the same output as that of the actual product. Stubs are also used when the software needs to interact with an external system. The above diagram clearly states that Modules 1, 2 and 3 are available for integration, whereas, below modules are still under development that cannot be integrated at this point of time. Hence, Stubs are used to test the modules. The order of Integration will be: 1,2 1,3 2,Stub 1 2,Stub 2 3,Stub 3 3,Stub 4 + Firstly, the integration between the modules 1,2 and 3 + Test the integration between the module 2 and stub 1,stub 2 + Test the integration between the module 3 and stub 3,stub 4 80 Lectures 7.5 hours Arnab Chakraborty 10 Lectures 1 hours Zach Miller 17 Lectures 1.5 hours Zach Miller 60 Lectures 5 hours John Shea 99 Lectures 10 hours Daniel IT 62 Lectures 5 hours GlobalETraining Print Add Notes Bookmark this page
[ { "code": null, "e": 6020, "s": 5745, "text": "Stubs are used during Top-down integration testing, in order to simulate the behaviour of the lower-level modules that are not yet integrated. Stubs are the modules that act as temporary replacement for a called module and give the same output as that of the actual product." }, { "code": null, "e": 6101, "s": 6020, "text": "Stubs are also used when the software needs to interact with an external system." }, { "code": null, "e": 6366, "s": 6101, "text": "The above diagram clearly states that Modules 1, 2 and 3 are available for integration, whereas, below modules are still under development that cannot be integrated at this point of time. Hence, Stubs are used to test the modules. The order of Integration will be:" }, { "code": null, "e": 6410, "s": 6366, "text": "1,2\n1,3\n2,Stub 1\n2,Stub 2\n3,Stub 3\n3,Stub 4" }, { "code": null, "e": 6591, "s": 6410, "text": "+ Firstly, the integration between the modules 1,2 and 3\n+ Test the integration between the module 2 and stub 1,stub 2\n+ Test the integration between the module 3 and stub 3,stub 4" }, { "code": null, "e": 6626, "s": 6591, "text": "\n 80 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6645, "s": 6626, "text": " Arnab Chakraborty" }, { "code": null, "e": 6678, "s": 6645, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6691, "s": 6678, "text": " Zach Miller" }, { "code": null, "e": 6726, "s": 6691, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6739, "s": 6726, "text": " Zach Miller" }, { "code": null, "e": 6772, "s": 6739, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 6783, "s": 6772, "text": " John Shea" }, { "code": null, "e": 6817, "s": 6783, "text": "\n 99 Lectures \n 10 hours \n" }, { "code": null, "e": 6828, "s": 6817, "text": " Daniel IT" }, { "code": null, "e": 6861, "s": 6828, "text": "\n 62 Lectures \n 5 hours \n" }, { "code": null, "e": 6878, "s": 6861, "text": " GlobalETraining" }, { "code": null, "e": 6885, "s": 6878, "text": " Print" }, { "code": null, "e": 6896, "s": 6885, "text": " Add Notes" } ]
Core Dump (Segmentation fault) in C/C++ - GeeksforGeeks
07 Feb, 2022 Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump. It is an error indicating memory corruption. Common segmentation fault scenarios: Modifying a string literal : The below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read only memory. C int main(){ char *str; /* Stored in read only part of data segment */ str = "GfG"; /* Problem: trying to modify read only memory */ *(str+1) = 'n'; return 0;} Abnormal termination of program. Refer Storage for Strings in C for details Accessing an address that is freed : Here in the below code, the pointer p is dereferenced after freeing the memory block, which is not allowed by the compiler. So it produces the error segment fault or abnormal program termination at runtime. Example: C++ C // C++ program to illustrate// Core Dump/Segmentation fault#include <iostream>using namespace std; int main(void){ // allocating memory to p int* p = (int*) malloc(8*sizeof(int)); *p = 100; // deallocated the space allocated to p free(p); // core dump/segmentation fault // as now this statement is illegal *p = 110; return 0;} // This code is contributed by shivanisinghss2110 // C program to illustrate// Core Dump/Segmentation fault#include <stdio.h>#include<alloc.h>int main(void){ // allocating memory to p int* p = malloc(8); *p = 100; // deallocated the space allocated to p free(p); // core dump/segmentation fault // as now this statement is illegal *p = 110; return 0;} Output: Abnormal termination of program. Accessing out of array index bounds : CPP // C++ program to demonstrate segmentation// fault when array out of bound is accessed.#include <iostream>using namespace std; int main(){ int arr[2]; arr[3] = 10; // Accessing out of bound return 0;} Output: Abnormal termination of program. Improper use of scanf() : scanf() function expects address of a variable as an input. Here in this program n takes value of 2 and assume it’s address as 1000. If we pass n to scanf(), input fetched from STDIN is placed in invalid memory 2 which should be 1000 instead. It’s a memory corruption leading to Segmentation fault. C++ C // C++ program to demonstrate segmentation// fault when value is passed to scanf#include <iostream>using namespace std; int main(){ int n = 2; cin >> " " >> n; return 0;} // This code is contributed by shivanisinghss2110 // C program to demonstrate segmentation// fault when value is passed to scanf#include <stdio.h> int main(){ int n = 2; scanf(" ",n); return 0;} Output: Abnormal termination of program. Stack Overflow It’s not a pointer related problem even code may not have single pointer. It’s because of recursive function gets called repeatedly which eats up all the stack memory resulting in stack overflow. Running out of memory on the stack is also a type of memory corruption. It can be resolved by having a base condition to return from the recursive function. Dereferencing uninitialized pointer A pointer must point to valid memory before accessing it. C++14 C // C++ program to demonstrate segmentation// fault when uninitialized pointer is accessed.#include <iostream>using namespace std; int main(){ int* p; cout << *p; return 0;}// This code is contributed by Mayank Tyagi // C program to demonstrate segmentation// fault when uninitialized pointer is accessed.#include <stdio.h> int main(){ int *p; printf("%d",*p); return 0;} This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. kani_26 mayanktyagi1709 tejender shivanisinghss2110 12chiranth animeshalok C-Dynamic Memory Allocation C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ Substring in C++ fork() in C Command line arguments in C/C++ Function Pointer in C Different methods to reverse a string in C/C++ Structures in C TCP Server-Client implementation in C
[ { "code": null, "e": 24416, "s": 24388, "text": "\n07 Feb, 2022" }, { "code": null, "e": 24533, "s": 24416, "text": "Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” " }, { "code": null, "e": 24677, "s": 24533, "text": "When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump." }, { "code": null, "e": 24722, "s": 24677, "text": "It is an error indicating memory corruption." }, { "code": null, "e": 24761, "s": 24722, "text": "Common segmentation fault scenarios: " }, { "code": null, "e": 24920, "s": 24761, "text": "Modifying a string literal : The below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read only memory. " }, { "code": null, "e": 24922, "s": 24920, "text": "C" }, { "code": "int main(){ char *str; /* Stored in read only part of data segment */ str = \"GfG\"; /* Problem: trying to modify read only memory */ *(str+1) = 'n'; return 0;}", "e": 25100, "s": 24922, "text": null }, { "code": null, "e": 25135, "s": 25102, "text": "Abnormal termination of program." }, { "code": null, "e": 25180, "s": 25135, "text": "Refer Storage for Strings in C for details " }, { "code": null, "e": 25435, "s": 25180, "text": "Accessing an address that is freed : Here in the below code, the pointer p is dereferenced after freeing the memory block, which is not allowed by the compiler. So it produces the error segment fault or abnormal program termination at runtime. Example: " }, { "code": null, "e": 25439, "s": 25435, "text": "C++" }, { "code": null, "e": 25441, "s": 25439, "text": "C" }, { "code": "// C++ program to illustrate// Core Dump/Segmentation fault#include <iostream>using namespace std; int main(void){ // allocating memory to p int* p = (int*) malloc(8*sizeof(int)); *p = 100; // deallocated the space allocated to p free(p); // core dump/segmentation fault // as now this statement is illegal *p = 110; return 0;} // This code is contributed by shivanisinghss2110", "e": 25867, "s": 25441, "text": null }, { "code": "// C program to illustrate// Core Dump/Segmentation fault#include <stdio.h>#include<alloc.h>int main(void){ // allocating memory to p int* p = malloc(8); *p = 100; // deallocated the space allocated to p free(p); // core dump/segmentation fault // as now this statement is illegal *p = 110; return 0;}", "e": 26212, "s": 25867, "text": null }, { "code": null, "e": 26222, "s": 26212, "text": "Output: " }, { "code": null, "e": 26255, "s": 26222, "text": "Abnormal termination of program." }, { "code": null, "e": 26297, "s": 26257, "text": "Accessing out of array index bounds : " }, { "code": null, "e": 26301, "s": 26297, "text": "CPP" }, { "code": "// C++ program to demonstrate segmentation// fault when array out of bound is accessed.#include <iostream>using namespace std; int main(){ int arr[2]; arr[3] = 10; // Accessing out of bound return 0;}", "e": 26509, "s": 26301, "text": null }, { "code": null, "e": 26519, "s": 26509, "text": "Output: " }, { "code": null, "e": 26552, "s": 26519, "text": "Abnormal termination of program." }, { "code": null, "e": 26881, "s": 26554, "text": "Improper use of scanf() : scanf() function expects address of a variable as an input. Here in this program n takes value of 2 and assume it’s address as 1000. If we pass n to scanf(), input fetched from STDIN is placed in invalid memory 2 which should be 1000 instead. It’s a memory corruption leading to Segmentation fault. " }, { "code": null, "e": 26885, "s": 26881, "text": "C++" }, { "code": null, "e": 26887, "s": 26885, "text": "C" }, { "code": "// C++ program to demonstrate segmentation// fault when value is passed to scanf#include <iostream>using namespace std; int main(){ int n = 2; cin >> \" \" >> n; return 0;} // This code is contributed by shivanisinghss2110", "e": 27115, "s": 26887, "text": null }, { "code": "// C program to demonstrate segmentation// fault when value is passed to scanf#include <stdio.h> int main(){ int n = 2; scanf(\" \",n); return 0;}", "e": 27266, "s": 27115, "text": null }, { "code": null, "e": 27276, "s": 27266, "text": "Output: " }, { "code": null, "e": 27309, "s": 27276, "text": "Abnormal termination of program." }, { "code": null, "e": 27680, "s": 27311, "text": "Stack Overflow It’s not a pointer related problem even code may not have single pointer. It’s because of recursive function gets called repeatedly which eats up all the stack memory resulting in stack overflow. Running out of memory on the stack is also a type of memory corruption. It can be resolved by having a base condition to return from the recursive function. " }, { "code": null, "e": 27776, "s": 27680, "text": "Dereferencing uninitialized pointer A pointer must point to valid memory before accessing it. " }, { "code": null, "e": 27782, "s": 27776, "text": "C++14" }, { "code": null, "e": 27784, "s": 27782, "text": "C" }, { "code": "// C++ program to demonstrate segmentation// fault when uninitialized pointer is accessed.#include <iostream>using namespace std; int main(){ int* p; cout << *p; return 0;}// This code is contributed by Mayank Tyagi", "e": 28009, "s": 27784, "text": null }, { "code": "// C program to demonstrate segmentation// fault when uninitialized pointer is accessed.#include <stdio.h> int main(){ int *p; printf(\"%d\",*p); return 0;}", "e": 28170, "s": 28009, "text": null }, { "code": null, "e": 28599, "s": 28172, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 28607, "s": 28599, "text": "kani_26" }, { "code": null, "e": 28623, "s": 28607, "text": "mayanktyagi1709" }, { "code": null, "e": 28632, "s": 28623, "text": "tejender" }, { "code": null, "e": 28651, "s": 28632, "text": "shivanisinghss2110" }, { "code": null, "e": 28662, "s": 28651, "text": "12chiranth" }, { "code": null, "e": 28674, "s": 28662, "text": "animeshalok" }, { "code": null, "e": 28702, "s": 28674, "text": "C-Dynamic Memory Allocation" }, { "code": null, "e": 28713, "s": 28702, "text": "C Language" }, { "code": null, "e": 28811, "s": 28713, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28846, "s": 28811, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 28874, "s": 28846, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 28920, "s": 28874, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 28937, "s": 28920, "text": "Substring in C++" }, { "code": null, "e": 28949, "s": 28937, "text": "fork() in C" }, { "code": null, "e": 28981, "s": 28949, "text": "Command line arguments in C/C++" }, { "code": null, "e": 29003, "s": 28981, "text": "Function Pointer in C" }, { "code": null, "e": 29050, "s": 29003, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 29066, "s": 29050, "text": "Structures in C" } ]
Set NOT NULL attribute to an existing column in MySQL
To set NOT NULL attribute to an existing column, use ALTER TABLE command. Let us first create a table − mysql> create table DemoTable1949 ( UserId int, UserName varchar(20) ); Query OK, 0 rows affected (0.00 sec) Here is the query to set NOT NULL attribute to an existing column − mysql> alter table DemoTable1949 modify UserName varchar(20) not null; Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0 Let us check the description of table − mysql> desc DemoTable1949; This will produce the following output − +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | UserId | int(11) | YES | | NULL | | | UserName | varchar(20) | NO | | NULL | | +----------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1949 values(101,NULL); ERROR 1048 (23000): Column 'UserName' cannot be null mysql> insert into DemoTable1949 values(101,'Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1949 values(102,'Bob'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1949; This will produce the following output − +--------+----------+ | UserId | UserName | +--------+----------+ | 101 | Chris | | 102 | Bob | +--------+----------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1166, "s": 1062, "text": "To set NOT NULL attribute to an existing column, use ALTER TABLE command. Let us first create a table −" }, { "code": null, "e": 1287, "s": 1166, "text": "mysql> create table DemoTable1949\n (\n UserId int,\n UserName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1355, "s": 1287, "text": "Here is the query to set NOT NULL attribute to an existing column −" }, { "code": null, "e": 1502, "s": 1355, "text": "mysql> alter table DemoTable1949 modify UserName varchar(20) not null;\nQuery OK, 0 rows affected (0.00 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1542, "s": 1502, "text": "Let us check the description of table −" }, { "code": null, "e": 1569, "s": 1542, "text": "mysql> desc DemoTable1949;" }, { "code": null, "e": 1610, "s": 1569, "text": "This will produce the following output −" }, { "code": null, "e": 1983, "s": 1610, "text": "+----------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------+-------------+------+-----+---------+-------+\n| UserId | int(11) | YES | | NULL | |\n| UserName | varchar(20) | NO | | NULL | |\n+----------+-------------+------+-----+---------+-------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 2039, "s": 1983, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2321, "s": 2039, "text": "mysql> insert into DemoTable1949 values(101,NULL);\nERROR 1048 (23000): Column 'UserName' cannot be null\nmysql> insert into DemoTable1949 values(101,'Chris');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1949 values(102,'Bob');\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 2381, "s": 2321, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2417, "s": 2381, "text": "mysql> select * from DemoTable1949;" }, { "code": null, "e": 2458, "s": 2417, "text": "This will produce the following output −" }, { "code": null, "e": 2615, "s": 2458, "text": "+--------+----------+\n| UserId | UserName |\n+--------+----------+\n| 101 | Chris |\n| 102 | Bob |\n+--------+----------+\n2 rows in set (0.00 sec)" } ]
Create a model with Azure Custom Vision and Python | by Henk Boelman | Towards Data Science
The answer to that is simple, if you build the training process in code you can version it for instance on Github. Having your code versioned means you can read back what you have done, work ina team on it and run it again if you need to. Let’s dive into the code! Before we start, I assume you have Python 3.6 installed. The first thing you need to do is create an Azure Custom Vision service. If you don’t have an Azure subscription you can get $200 credit for the first month. You can create an Azure Custom Vision endpoint easily through the portal, but you can also use the Azure CLI for this. If you don’ t have the Azure cli installed you can install it using pip. pip install azure-cli The first step is to login to your Azure subscription, select the right subscription and create a resource group for the Custom Vision Endpoints. az login az account set -s <SUBSCRIPTION_ID> az group create --name CustomVision_Demo-RG --location westeurope The Custom Vision Service has 2 types of endpoints. One for training the model and one for running predictions against the model. Let’s create the two endpoints. az cognitiveservices account create --name CustomVisionDemo-Prediction --resource-group CustomVision_Demo-RG --kind CustomVision.Prediction --sku S0 --location westeurope –yes az cognitiveservices account create --name CustomVisionDemo-Training --resource-group CustomVision_Demo-RG --kind CustomVision.Training --sku S0 --location westeurope –yes Now that we have created the endpoints we can start with training the model. Every Machine Learning journey starts with a question you want to have answered. For this example, you are going to answer the question: Is it a Homer or a Marge Lego figure. Now that we know what to ask the model, we can go on to the next requirement; that is data. Our model is going to be a classification model, meaning the model will look at the picture and scores the pictures against the different classes. So, the output will be I’m 70% confident this is Homer and 1% confident that this is Marge. By taking the class with the highest score and setting a minimum threshold for the confidence score we know what is on the picture. I have created a dataset for you with 50 pictures of a Homer Simpson Lego figure and 50 pictures of a Marge Simpsons Lego figure. I have taken the photos with a few things in mind, used a lot of different backgrounds and took the photos from different angles. I made sure the only object in the photo was Homer or Marge and the quality of the photos was somehow the consistent. Download the dataset here For the training we are going the use the Custom Vision Service Python SDK, you can install this package using pip. pip install azure-cognitiveservices-vision-customvision Create a new Python file called ‘train.py’ and start adding code. Start with importing the packages needed. from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient from azure.cognitiveservices.vision.customvision.training.models import ImageFileCreateEntry Next, create variables for the Custom Vision endpoint, Custom Vision training key and the location where the training images are stored. cv_endpoint = "https://westeurope.api.cognitive.microsoft.com" training_key = "<INSERT TRAINING KEY>" training_images = "LegoSimpsons/TrainingImages" To start with the training, we need to create a Training Client. This method takes as input the endpoint and the training key. trainer = CustomVisionTrainingClient(training_key, endpoint= cv_endpoint) Now you are ready to create your first project. The project takes a name and domain as input, the name can be anything. The domain is a different story. You can ask for a list of all possible domains and choose the one closest to what you are trying to accomplish. For instance if you are trying to classify food you pick the domain “Food” or “Landmarks” for landmarks. Use the code below to show all domains. for domain in trainer.get_domains(): print(domain.id, "\t", domain.name) You might notice that some domains have the word “Compact” next to them. If this is the case it means the Azure Custom Vision Service will create a smaller model, which you will be able to export and run locally on your mobile phone or desktop. Let’s create a new project with the domain set to “General Compact”. project = trainer.create_project("Lego - Simpsons - v1","0732100f-1a38-4e49-a514-c9b44c697ab5") Next you need to create tags, these tags are the same as classes mentioned above. When you have created a few tags we can tag images with them and upload the images to the Azure Custom Vision Service. Our images are sorted per tag/class in a folder. All the photos of Marge are in the folder named ‘Marge’ and all the images of Homer are in the folder named ‘Homer’. In the code below we do the following steps: We open the directory containing the folders with training images. Loop through all the directories found in this folder Create a new tag with the folder name Open the folder containing the images Create, for every image in that folder, an ImageFileEntry that contains the filename, file content and the tag. Add this ImageFileEntry to a list. image_list = []directories = os.listdir(training_images)for tagName in directories: tag = trainer.create_tag(project.id, tagName) images = os.listdir(os.path.join(training_images,tagName)) for img in images: with open(os.path.join(training_images,tagName,img), "rb") as image_contents: image_list.append(ImageFileCreateEntry(name=img, contents=image_contents.read(), tag_ids=[tag.id])) Now you have a list that contains all tagged images. So far no images have been added to the Azure Custom Vision service, only the tags have been created. Uploading images goes in batches with a max size of 64 images per batch. Our dataset is 100 images big, so first we need to split the list into chunks of 64 images. def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n]batchedImages = chunks(image_list, 64) Now we have our images split in batches of 64, we can upload them batch by batch to the Azure Custom Vision Service. Note: This can take a while! for batchOfImages in batchedImages: upload_result = trainer.create_images_from_files(project.id, images=batchOfImages) Now you have reached the final step, we can publish the model. Its then available in a prediction API and ready to be consumed from an application. Every time you train your model its called an iteration. Often you have to retrain your model when you have new data or when you find out that in the real world your model is behaving different than expected. The concept of the Custom Vision Service is that you can publish an iteration of your model under a specific name. This means that you can have multiple versions of your model available for your application to use, for instance you can a-b test your model very quickly with this. To publish an iteration of your model you call the publish_iteration method, this method requires a few parameters. Project ID and Iteration ID, these are values from the previous steps. You can choose a name for publication of your model, for instance ‘latest’ or ‘version1 . The last parameter you need is the ‘resource identifier’ of the resource where you want to publish it to. This is the resource identifier of the Azure Custom Vision Prediction resource we created at the beginning with our AZ command. You can use this command to retrieve all the details about the Prediction resource you created: az cognitiveservices account show --name CustomVisionDemo-Prediction --resource-group CustomVision_Demo-RG You can copy the value that is behind the field ID, it looks like this: /subscriptions/<SUBSCRIPTION-ID>/resourceGroups/<RESOURCE_GROUP_NAME>/providers/Microsoft.CognitiveServices/accounts/<RESOURCE_NAME>") When you have the resource ID, paste it in the variable below and call the ‘publish_iteration’ method. publish_iteration_name = '' resource_identifier = '' trainer.publish_iteration(project.id, iteration.id, publish_iteration_name, resource_identifier) Now you have successfully trained and published your model! A small recap of what have we done: You created an Azure Resource group containing an Azure Custom Vision service training and prediction endpoint You have created a new Project In that project you have created tags You have uploaded images in batches of 64 and tagged them You have trained an iteration of your model You have published the iteration to a prediction endpoint View the full code here Using the model in an application is as easy as calling an API. You could do just a json post to the endpoint, but you can also use the methods in the Custom Vision Python SDK, which will make things a lot easier. Create a new file called ‘predict.py’ Start with importing the dependencies you need to do a prediction. from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient The next thing you need is the prediction key. This is the key from the resource where you have published the model to. You can use this az command to list the keys. az cognitiveservices account keys list --name CustomVisionDemo-Prediction --resource-group CustomVision_Demo-RG When you have your prediction key you can create a prediction client. For this client you also need the endpoint. You can run the az command below and copy the url behind the field “endpoint”. az cognitiveservices account show --name CustomVisionDemo-Prediction --resource-group CustomVision_Demo-RG Now you have the prediction key and the endpoint you can create the PredictionClient. predictor = CustomVisionPredictionClient(prediction_key, endpoint=ENDPOINT) You have multiple options to classify an image. You can send a URL or you can send the binary image to the endpoint. By default the Azure Custom Vision service keeps a history of all the images posted to the endpoint. The images and their predictions can be reviewed in the portal and used to retrain your model. But sometimes you don’t want the images to be kept in history and therefore it is possible to disable this feature. I have uploaded 2 images you can use for testing, but feel free to use a search engine to find other images of Marge and Homer. To classify an image using a URL and keep the history you call the ‘classify_image_url’ method. You give it the project id and iteration name from a few steps above and provide the URL to the image. results = predictor.classify_image_url(project.id,publish_iteration_name,url="https://missedprints.com/wp-content/uploads/2014/03/marge-simpson-lego-minifig.jpg") To show the score for the different classes on the screen you can use the code below to loop through the results and display the tag name and confidence score for the image. for prediction in results.predictions: print("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100)) Now you are all done and have your own classification model running in the cloud! Here is a recap of what you have achieved: We asked a question Collected data Created an Azure Custom Vision Service endpoint Created a new Project Tagged and uploaded content Trained the model Published the iteration so it can be used in an API Ran predictions against the model using the API In the rest of this series of articles we will use this model for different solutions! Stay tuned! View the full code here How to install the Azure CLI Creating cognitive services through the CLI Python SDK Custom Vision Documentation
[ { "code": null, "e": 410, "s": 171, "text": "The answer to that is simple, if you build the training process in code you can version it for instance on Github. Having your code versioned means you can read back what you have done, work ina team on it and run it again if you need to." }, { "code": null, "e": 493, "s": 410, "text": "Let’s dive into the code! Before we start, I assume you have Python 3.6 installed." }, { "code": null, "e": 651, "s": 493, "text": "The first thing you need to do is create an Azure Custom Vision service. If you don’t have an Azure subscription you can get $200 credit for the first month." }, { "code": null, "e": 843, "s": 651, "text": "You can create an Azure Custom Vision endpoint easily through the portal, but you can also use the Azure CLI for this. If you don’ t have the Azure cli installed you can install it using pip." }, { "code": null, "e": 865, "s": 843, "text": "pip install azure-cli" }, { "code": null, "e": 1011, "s": 865, "text": "The first step is to login to your Azure subscription, select the right subscription and create a resource group for the Custom Vision Endpoints." }, { "code": null, "e": 1122, "s": 1011, "text": "az login az account set -s <SUBSCRIPTION_ID> az group create --name CustomVision_Demo-RG --location westeurope" }, { "code": null, "e": 1252, "s": 1122, "text": "The Custom Vision Service has 2 types of endpoints. One for training the model and one for running predictions against the model." }, { "code": null, "e": 1284, "s": 1252, "text": "Let’s create the two endpoints." }, { "code": null, "e": 1632, "s": 1284, "text": "az cognitiveservices account create --name CustomVisionDemo-Prediction --resource-group CustomVision_Demo-RG --kind CustomVision.Prediction --sku S0 --location westeurope –yes az cognitiveservices account create --name CustomVisionDemo-Training --resource-group CustomVision_Demo-RG --kind CustomVision.Training --sku S0 --location westeurope –yes" }, { "code": null, "e": 1709, "s": 1632, "text": "Now that we have created the endpoints we can start with training the model." }, { "code": null, "e": 1884, "s": 1709, "text": "Every Machine Learning journey starts with a question you want to have answered. For this example, you are going to answer the question: Is it a Homer or a Marge Lego figure." }, { "code": null, "e": 2347, "s": 1884, "text": "Now that we know what to ask the model, we can go on to the next requirement; that is data. Our model is going to be a classification model, meaning the model will look at the picture and scores the pictures against the different classes. So, the output will be I’m 70% confident this is Homer and 1% confident that this is Marge. By taking the class with the highest score and setting a minimum threshold for the confidence score we know what is on the picture." }, { "code": null, "e": 2725, "s": 2347, "text": "I have created a dataset for you with 50 pictures of a Homer Simpson Lego figure and 50 pictures of a Marge Simpsons Lego figure. I have taken the photos with a few things in mind, used a lot of different backgrounds and took the photos from different angles. I made sure the only object in the photo was Homer or Marge and the quality of the photos was somehow the consistent." }, { "code": null, "e": 2751, "s": 2725, "text": "Download the dataset here" }, { "code": null, "e": 2867, "s": 2751, "text": "For the training we are going the use the Custom Vision Service Python SDK, you can install this package using pip." }, { "code": null, "e": 2923, "s": 2867, "text": "pip install azure-cognitiveservices-vision-customvision" }, { "code": null, "e": 2989, "s": 2923, "text": "Create a new Python file called ‘train.py’ and start adding code." }, { "code": null, "e": 3031, "s": 2989, "text": "Start with importing the packages needed." }, { "code": null, "e": 3216, "s": 3031, "text": "from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient from azure.cognitiveservices.vision.customvision.training.models import ImageFileCreateEntry" }, { "code": null, "e": 3353, "s": 3216, "text": "Next, create variables for the Custom Vision endpoint, Custom Vision training key and the location where the training images are stored." }, { "code": null, "e": 3503, "s": 3353, "text": "cv_endpoint = \"https://westeurope.api.cognitive.microsoft.com\" training_key = \"<INSERT TRAINING KEY>\" training_images = \"LegoSimpsons/TrainingImages\"" }, { "code": null, "e": 3630, "s": 3503, "text": "To start with the training, we need to create a Training Client. This method takes as input the endpoint and the training key." }, { "code": null, "e": 3704, "s": 3630, "text": "trainer = CustomVisionTrainingClient(training_key, endpoint= cv_endpoint)" }, { "code": null, "e": 4114, "s": 3704, "text": "Now you are ready to create your first project. The project takes a name and domain as input, the name can be anything. The domain is a different story. You can ask for a list of all possible domains and choose the one closest to what you are trying to accomplish. For instance if you are trying to classify food you pick the domain “Food” or “Landmarks” for landmarks. Use the code below to show all domains." }, { "code": null, "e": 4192, "s": 4114, "text": "for domain in trainer.get_domains(): print(domain.id, \"\\t\", domain.name)" }, { "code": null, "e": 4437, "s": 4192, "text": "You might notice that some domains have the word “Compact” next to them. If this is the case it means the Azure Custom Vision Service will create a smaller model, which you will be able to export and run locally on your mobile phone or desktop." }, { "code": null, "e": 4506, "s": 4437, "text": "Let’s create a new project with the domain set to “General Compact”." }, { "code": null, "e": 4602, "s": 4506, "text": "project = trainer.create_project(\"Lego - Simpsons - v1\",\"0732100f-1a38-4e49-a514-c9b44c697ab5\")" }, { "code": null, "e": 4803, "s": 4602, "text": "Next you need to create tags, these tags are the same as classes mentioned above. When you have created a few tags we can tag images with them and upload the images to the Azure Custom Vision Service." }, { "code": null, "e": 4969, "s": 4803, "text": "Our images are sorted per tag/class in a folder. All the photos of Marge are in the folder named ‘Marge’ and all the images of Homer are in the folder named ‘Homer’." }, { "code": null, "e": 5014, "s": 4969, "text": "In the code below we do the following steps:" }, { "code": null, "e": 5081, "s": 5014, "text": "We open the directory containing the folders with training images." }, { "code": null, "e": 5135, "s": 5081, "text": "Loop through all the directories found in this folder" }, { "code": null, "e": 5173, "s": 5135, "text": "Create a new tag with the folder name" }, { "code": null, "e": 5211, "s": 5173, "text": "Open the folder containing the images" }, { "code": null, "e": 5323, "s": 5211, "text": "Create, for every image in that folder, an ImageFileEntry that contains the filename, file content and the tag." }, { "code": null, "e": 5358, "s": 5323, "text": "Add this ImageFileEntry to a list." }, { "code": null, "e": 5752, "s": 5358, "text": "image_list = []directories = os.listdir(training_images)for tagName in directories: tag = trainer.create_tag(project.id, tagName) images = os.listdir(os.path.join(training_images,tagName)) for img in images: with open(os.path.join(training_images,tagName,img), \"rb\") as image_contents: image_list.append(ImageFileCreateEntry(name=img, contents=image_contents.read(), tag_ids=[tag.id]))" }, { "code": null, "e": 5907, "s": 5752, "text": "Now you have a list that contains all tagged images. So far no images have been added to the Azure Custom Vision service, only the tags have been created." }, { "code": null, "e": 6072, "s": 5907, "text": "Uploading images goes in batches with a max size of 64 images per batch. Our dataset is 100 images big, so first we need to split the list into chunks of 64 images." }, { "code": null, "e": 6178, "s": 6072, "text": "def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n]batchedImages = chunks(image_list, 64)" }, { "code": null, "e": 6324, "s": 6178, "text": "Now we have our images split in batches of 64, we can upload them batch by batch to the Azure Custom Vision Service. Note: This can take a while!" }, { "code": null, "e": 6444, "s": 6324, "text": "for batchOfImages in batchedImages: upload_result = trainer.create_images_from_files(project.id, images=batchOfImages)" }, { "code": null, "e": 6592, "s": 6444, "text": "Now you have reached the final step, we can publish the model. Its then available in a prediction API and ready to be consumed from an application." }, { "code": null, "e": 6801, "s": 6592, "text": "Every time you train your model its called an iteration. Often you have to retrain your model when you have new data or when you find out that in the real world your model is behaving different than expected." }, { "code": null, "e": 7081, "s": 6801, "text": "The concept of the Custom Vision Service is that you can publish an iteration of your model under a specific name. This means that you can have multiple versions of your model available for your application to use, for instance you can a-b test your model very quickly with this." }, { "code": null, "e": 7197, "s": 7081, "text": "To publish an iteration of your model you call the publish_iteration method, this method requires a few parameters." }, { "code": null, "e": 7592, "s": 7197, "text": "Project ID and Iteration ID, these are values from the previous steps. You can choose a name for publication of your model, for instance ‘latest’ or ‘version1 . The last parameter you need is the ‘resource identifier’ of the resource where you want to publish it to. This is the resource identifier of the Azure Custom Vision Prediction resource we created at the beginning with our AZ command." }, { "code": null, "e": 7688, "s": 7592, "text": "You can use this command to retrieve all the details about the Prediction resource you created:" }, { "code": null, "e": 7795, "s": 7688, "text": "az cognitiveservices account show --name CustomVisionDemo-Prediction --resource-group CustomVision_Demo-RG" }, { "code": null, "e": 7867, "s": 7795, "text": "You can copy the value that is behind the field ID, it looks like this:" }, { "code": null, "e": 8002, "s": 7867, "text": "/subscriptions/<SUBSCRIPTION-ID>/resourceGroups/<RESOURCE_GROUP_NAME>/providers/Microsoft.CognitiveServices/accounts/<RESOURCE_NAME>\")" }, { "code": null, "e": 8105, "s": 8002, "text": "When you have the resource ID, paste it in the variable below and call the ‘publish_iteration’ method." }, { "code": null, "e": 8255, "s": 8105, "text": "publish_iteration_name = '' resource_identifier = '' trainer.publish_iteration(project.id, iteration.id, publish_iteration_name, resource_identifier)" }, { "code": null, "e": 8315, "s": 8255, "text": "Now you have successfully trained and published your model!" }, { "code": null, "e": 8351, "s": 8315, "text": "A small recap of what have we done:" }, { "code": null, "e": 8462, "s": 8351, "text": "You created an Azure Resource group containing an Azure Custom Vision service training and prediction endpoint" }, { "code": null, "e": 8493, "s": 8462, "text": "You have created a new Project" }, { "code": null, "e": 8531, "s": 8493, "text": "In that project you have created tags" }, { "code": null, "e": 8589, "s": 8531, "text": "You have uploaded images in batches of 64 and tagged them" }, { "code": null, "e": 8633, "s": 8589, "text": "You have trained an iteration of your model" }, { "code": null, "e": 8691, "s": 8633, "text": "You have published the iteration to a prediction endpoint" }, { "code": null, "e": 8715, "s": 8691, "text": "View the full code here" }, { "code": null, "e": 8929, "s": 8715, "text": "Using the model in an application is as easy as calling an API. You could do just a json post to the endpoint, but you can also use the methods in the Custom Vision Python SDK, which will make things a lot easier." }, { "code": null, "e": 8967, "s": 8929, "text": "Create a new file called ‘predict.py’" }, { "code": null, "e": 9034, "s": 8967, "text": "Start with importing the dependencies you need to do a prediction." }, { "code": null, "e": 9130, "s": 9034, "text": "from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient" }, { "code": null, "e": 9296, "s": 9130, "text": "The next thing you need is the prediction key. This is the key from the resource where you have published the model to. You can use this az command to list the keys." }, { "code": null, "e": 9408, "s": 9296, "text": "az cognitiveservices account keys list --name CustomVisionDemo-Prediction --resource-group CustomVision_Demo-RG" }, { "code": null, "e": 9601, "s": 9408, "text": "When you have your prediction key you can create a prediction client. For this client you also need the endpoint. You can run the az command below and copy the url behind the field “endpoint”." }, { "code": null, "e": 9708, "s": 9601, "text": "az cognitiveservices account show --name CustomVisionDemo-Prediction --resource-group CustomVision_Demo-RG" }, { "code": null, "e": 9794, "s": 9708, "text": "Now you have the prediction key and the endpoint you can create the PredictionClient." }, { "code": null, "e": 9870, "s": 9794, "text": "predictor = CustomVisionPredictionClient(prediction_key, endpoint=ENDPOINT)" }, { "code": null, "e": 10299, "s": 9870, "text": "You have multiple options to classify an image. You can send a URL or you can send the binary image to the endpoint. By default the Azure Custom Vision service keeps a history of all the images posted to the endpoint. The images and their predictions can be reviewed in the portal and used to retrain your model. But sometimes you don’t want the images to be kept in history and therefore it is possible to disable this feature." }, { "code": null, "e": 10427, "s": 10299, "text": "I have uploaded 2 images you can use for testing, but feel free to use a search engine to find other images of Marge and Homer." }, { "code": null, "e": 10626, "s": 10427, "text": "To classify an image using a URL and keep the history you call the ‘classify_image_url’ method. You give it the project id and iteration name from a few steps above and provide the URL to the image." }, { "code": null, "e": 10789, "s": 10626, "text": "results = predictor.classify_image_url(project.id,publish_iteration_name,url=\"https://missedprints.com/wp-content/uploads/2014/03/marge-simpson-lego-minifig.jpg\")" }, { "code": null, "e": 10963, "s": 10789, "text": "To show the score for the different classes on the screen you can use the code below to loop through the results and display the tag name and confidence score for the image." }, { "code": null, "e": 11089, "s": 10963, "text": "for prediction in results.predictions: print(\"\\t\" + prediction.tag_name + \": {0:.2f}%\".format(prediction.probability * 100))" }, { "code": null, "e": 11214, "s": 11089, "text": "Now you are all done and have your own classification model running in the cloud! Here is a recap of what you have achieved:" }, { "code": null, "e": 11234, "s": 11214, "text": "We asked a question" }, { "code": null, "e": 11249, "s": 11234, "text": "Collected data" }, { "code": null, "e": 11297, "s": 11249, "text": "Created an Azure Custom Vision Service endpoint" }, { "code": null, "e": 11319, "s": 11297, "text": "Created a new Project" }, { "code": null, "e": 11347, "s": 11319, "text": "Tagged and uploaded content" }, { "code": null, "e": 11365, "s": 11347, "text": "Trained the model" }, { "code": null, "e": 11417, "s": 11365, "text": "Published the iteration so it can be used in an API" }, { "code": null, "e": 11465, "s": 11417, "text": "Ran predictions against the model using the API" }, { "code": null, "e": 11564, "s": 11465, "text": "In the rest of this series of articles we will use this model for different solutions! Stay tuned!" }, { "code": null, "e": 11588, "s": 11564, "text": "View the full code here" }, { "code": null, "e": 11617, "s": 11588, "text": "How to install the Azure CLI" }, { "code": null, "e": 11661, "s": 11617, "text": "Creating cognitive services through the CLI" }, { "code": null, "e": 11672, "s": 11661, "text": "Python SDK" } ]
Protobuf - List/Repeated
Lists are one of the composite datatypes of Protobuf. Protobuf translates this to a java.util.list interface in Java. Continuing with our theater example, following is the syntax that we need to have to instruct Protobuf that we will be creating a list − syntax = "proto3"; package theater; option java_package = "com.tutorialspoint.theater"; message Theater { repeated string snacks = 8; } Now our message class contains a list for snacks. Note that although we have a string list, we can as well have number, Boolean, custom data type list. To use Protobuf, we will now have to use protoc binary to create the required classes from this ".proto" file. Let us see how to do that − protoc --java_out=java/src/main/java proto_files\theater.proto The above command should create the required files and now we can use it in our Java code. First, we will have a writer to write the theater information − package com.tutorialspoint.theater; import java.util.List; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import com.tutorialspoint.theater.TheaterOuterClass.Theater; public class TheaterWriter{ public static void main(String[] args) throws IOException { List<String> snacks = new ArrayList<>(); snacks.add("Popcorn"); snacks.add("Coke"); snacks.add("Chips"); snacks.add("Soda"); Theater theater = Theater.newBuilder() .addAllSnacks(snacks) .build(); String filename = "theater_protobuf_output"; System.out.println("Saving theater information to file: " + filename); try(FileOutputStream output = new FileOutputStream(filename)){ theater.writeTo(output); } System.out.println("Saved theater information with following data to disk: \n" + theater); } } Next, we will have a reader to read the theater information − package com.tutorialspoint.theater; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import com.tutorialspoint.greeting.Greeting.Greet; import com.tutorialspoint.theater.TheaterOuterClass.Theater; import com.tutorialspoint.theater.TheaterOuterClass.Theater.Builder; public class TheaterReader{ public static void main(String[] args) throws IOException { Builder theaterBuilder = Theater.newBuilder(); String filename = "theater_protobuf_output"; System.out.println("Reading from file " + filename); try(FileInputStream input = new FileInputStream(filename)) { Theater theater = theaterBuilder.mergeFrom(input).build(); System.out.println(theater); } } } Now, post compilation, let us execute the writer first − > java -cp .\target\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterWriter Saving theater information to file: theater_protobuf_output Saved theater information with following data to disk: snacks: "Popcorn" snacks: "Coke" snacks: "Chips" snacks: "Soda" Now, let us execute the reader to read from the same file − java -cp .\target\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterReader Reading from file theater_protobuf_output snacks: "Popcorn" snacks: "Coke" snacks: "Chips" snacks: "Soda" So, as we see, we are able to read the serialized list by deserializing the binary data to Theater object. In the next chapter, we will look at the map data type of Protobuf. Print Add Notes Bookmark this page
[ { "code": null, "e": 2163, "s": 2045, "text": "Lists are one of the composite datatypes of Protobuf. Protobuf translates this to a java.util.list interface in Java." }, { "code": null, "e": 2300, "s": 2163, "text": "Continuing with our theater example, following is the syntax that we need to have to instruct Protobuf that we will be creating a list −" }, { "code": null, "e": 2441, "s": 2300, "text": "syntax = \"proto3\";\npackage theater;\noption java_package = \"com.tutorialspoint.theater\";\n\nmessage Theater {\n repeated string snacks = 8;\n}\n" }, { "code": null, "e": 2593, "s": 2441, "text": "Now our message class contains a list for snacks. Note that although we have a string list, we can as well have number, Boolean, custom data type list." }, { "code": null, "e": 2732, "s": 2593, "text": "To use Protobuf, we will now have to use protoc binary to create the required classes from this \".proto\" file. Let us see how to do that −" }, { "code": null, "e": 2797, "s": 2732, "text": "protoc --java_out=java/src/main/java proto_files\\theater.proto\n" }, { "code": null, "e": 2952, "s": 2797, "text": "The above command should create the required files and now we can use it in our Java code. First, we will have a writer to write the theater information −" }, { "code": null, "e": 3860, "s": 2952, "text": "package com.tutorialspoint.theater;\n\nimport java.util.List;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport com.tutorialspoint.theater.TheaterOuterClass.Theater;\n\npublic class TheaterWriter{\n public static void main(String[] args) throws IOException {\n List<String> snacks = new ArrayList<>();\n snacks.add(\"Popcorn\");\n snacks.add(\"Coke\");\n snacks.add(\"Chips\");\n snacks.add(\"Soda\");\n\t \n Theater theater = Theater.newBuilder()\n .addAllSnacks(snacks)\n .build();\n\t\t\n String filename = \"theater_protobuf_output\";\n System.out.println(\"Saving theater information to file: \" + filename);\n\t\t\n try(FileOutputStream output = new FileOutputStream(filename)){\n theater.writeTo(output);\n }\n System.out.println(\"Saved theater information with following data to disk: \\n\" + theater);\n }\n}\t" }, { "code": null, "e": 3922, "s": 3860, "text": "Next, we will have a reader to read the theater information −" }, { "code": null, "e": 4686, "s": 3922, "text": "package com.tutorialspoint.theater;\n\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport com.tutorialspoint.greeting.Greeting.Greet;\nimport com.tutorialspoint.theater.TheaterOuterClass.Theater;\nimport com.tutorialspoint.theater.TheaterOuterClass.Theater.Builder;\n\npublic class TheaterReader{\n public static void main(String[] args) throws IOException {\n Builder theaterBuilder = Theater.newBuilder();\n\n String filename = \"theater_protobuf_output\";\n System.out.println(\"Reading from file \" + filename);\n \n try(FileInputStream input = new FileInputStream(filename)) {\n Theater theater = theaterBuilder.mergeFrom(input).build();\n System.out.println(theater);\n }\n }\n}" }, { "code": null, "e": 4743, "s": 4686, "text": "Now, post compilation, let us execute the writer first −" }, { "code": null, "e": 5011, "s": 4743, "text": "> java -cp .\\target\\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterWriter\n\nSaving theater information to file: theater_protobuf_output\nSaved theater information with following data to disk:\nsnacks: \"Popcorn\"\nsnacks: \"Coke\"\nsnacks: \"Chips\"\nsnacks: \"Soda\"\n" }, { "code": null, "e": 5071, "s": 5011, "text": "Now, let us execute the reader to read from the same file −" }, { "code": null, "e": 5264, "s": 5071, "text": "java -cp .\\target\\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterReader\n\nReading from file theater_protobuf_output\nsnacks: \"Popcorn\"\nsnacks: \"Coke\"\nsnacks: \"Chips\"\nsnacks: \"Soda\"\n" }, { "code": null, "e": 5439, "s": 5264, "text": "So, as we see, we are able to read the serialized list by deserializing the binary data to Theater object. In the next chapter, we will look at the map data type of Protobuf." }, { "code": null, "e": 5446, "s": 5439, "text": " Print" }, { "code": null, "e": 5457, "s": 5446, "text": " Add Notes" } ]
Password Verification in Node.js - GeeksforGeeks
14 Oct, 2021 In Node for password hashing and verification we can use a npm library known as bcryptjs npm-bcryptjs. Installation of bcryptjs: Node.js contains an inbuilt crypto module’s randomBytes interface which is used to obtain the secure random numbers. npm install bcryptjs Approach: To hash a password use bcrypt.hash(plainTextPassword, salt, callback) which returns a promise if no callback is passed. To verify plain text password with hashed password use bcrypt.compare(plainTextPassword, hashedPassword, callback) which also returns a promise if no callback is passed. Example 1: // Use bcryptjs moduleconst bcrypt = require("bcryptjs"); // Store the password into variableconst password = "password123"; // Use bcrypt.hash() function to hash the passwordbcrypt.hash(password, 8, (err, hashedPassword) => { if (err) { return err; } // Display the hashed password console.log(hashedPassword); // Use bcrypt.compare() function to compare // the password with hashed password bcrypt.compare(password, hashedPassword, (err, isMatch) => { if( err ) { return err; } // If password matches then display true console.log(isMatch); });}); Output: $2a$08$PV4rYpBwXUPAGuMedxUnAOxq/TozK9o/QSUWaKE1XL8psOyZ.JL4q true Example 2: // Use bcryptjs moduleconst bcrypt = require("bcryptjs"); // Store the password into variableconst password = "password123"; // Use bcrypt.hash() function to hash the passwordbcrypt.hash(password, 8).then(hashedPassword => { // Display the hashed password console.log(hashedPassword); // Compare the password with hashed password // and return its value return bcrypt.compare(password, hashedPassword); }).then(isMatch => { // If password matches then display true console.log(isMatch);}).catch(err => { // Display error log console.log(err);}); Output: $2a$08$LKZU9S9WVs3C.S/zpu2U7eua/ocfzD1ytF68QPT5M600auT6M.SxG true Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.readFile() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24101, "s": 24073, "text": "\n14 Oct, 2021" }, { "code": null, "e": 24204, "s": 24101, "text": "In Node for password hashing and verification we can use a npm library known as bcryptjs npm-bcryptjs." }, { "code": null, "e": 24347, "s": 24204, "text": "Installation of bcryptjs: Node.js contains an inbuilt crypto module’s randomBytes interface which is used to obtain the secure random numbers." }, { "code": null, "e": 24368, "s": 24347, "text": "npm install bcryptjs" }, { "code": null, "e": 24378, "s": 24368, "text": "Approach:" }, { "code": null, "e": 24498, "s": 24378, "text": "To hash a password use bcrypt.hash(plainTextPassword, salt, callback) which returns a promise if no callback is passed." }, { "code": null, "e": 24668, "s": 24498, "text": "To verify plain text password with hashed password use bcrypt.compare(plainTextPassword, hashedPassword, callback) which also returns a promise if no callback is passed." }, { "code": null, "e": 24679, "s": 24668, "text": "Example 1:" }, { "code": "// Use bcryptjs moduleconst bcrypt = require(\"bcryptjs\"); // Store the password into variableconst password = \"password123\"; // Use bcrypt.hash() function to hash the passwordbcrypt.hash(password, 8, (err, hashedPassword) => { if (err) { return err; } // Display the hashed password console.log(hashedPassword); // Use bcrypt.compare() function to compare // the password with hashed password bcrypt.compare(password, hashedPassword, (err, isMatch) => { if( err ) { return err; } // If password matches then display true console.log(isMatch); });});", "e": 25323, "s": 24679, "text": null }, { "code": null, "e": 25331, "s": 25323, "text": "Output:" }, { "code": null, "e": 25397, "s": 25331, "text": "$2a$08$PV4rYpBwXUPAGuMedxUnAOxq/TozK9o/QSUWaKE1XL8psOyZ.JL4q\ntrue" }, { "code": null, "e": 25408, "s": 25397, "text": "Example 2:" }, { "code": "// Use bcryptjs moduleconst bcrypt = require(\"bcryptjs\"); // Store the password into variableconst password = \"password123\"; // Use bcrypt.hash() function to hash the passwordbcrypt.hash(password, 8).then(hashedPassword => { // Display the hashed password console.log(hashedPassword); // Compare the password with hashed password // and return its value return bcrypt.compare(password, hashedPassword); }).then(isMatch => { // If password matches then display true console.log(isMatch);}).catch(err => { // Display error log console.log(err);});", "e": 26000, "s": 25408, "text": null }, { "code": null, "e": 26008, "s": 26000, "text": "Output:" }, { "code": null, "e": 26074, "s": 26008, "text": "$2a$08$LKZU9S9WVs3C.S/zpu2U7eua/ocfzD1ytF68QPT5M600auT6M.SxG\ntrue" }, { "code": null, "e": 26081, "s": 26074, "text": "Picked" }, { "code": null, "e": 26089, "s": 26081, "text": "Node.js" }, { "code": null, "e": 26106, "s": 26089, "text": "Web Technologies" }, { "code": null, "e": 26204, "s": 26106, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26213, "s": 26204, "text": "Comments" }, { "code": null, "e": 26226, "s": 26213, "text": "Old Comments" }, { "code": null, "e": 26255, "s": 26226, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 26285, "s": 26255, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 26342, "s": 26285, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 26396, "s": 26342, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 26433, "s": 26396, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 26489, "s": 26433, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26551, "s": 26489, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26594, "s": 26551, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26644, "s": 26594, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to check a variable is an array or not in PHP ? - GeeksforGeeks
22 Oct, 2021 There are two ways for checking whether the variable is an array or not. We can check whether a variable is an array or not by using the PHP is_array() function and by casting the variable to the array. Approach 1: We can check whether a variable is an array or not using the is_array() function. The PHP is_array() function is a variable handling function that checks whether a variable is an array or not. Syntax: is_array( $variable_name ); Parameter: It accepts a single parameter. This parameter must be the variable name for which the check is done if it is an array or not. Return value: It returns true if the boolean value is TRUE else false. Example 1: The is_array() function returns true(1) when passed parameter is array else it will return false (nothing). PHP <?php $isArr = "friends"; if(is_array($isArr)) { echo "Array";} else { echo "Not an Array";} echo "<br>"; $isArr = array("smith", "john", "josh"); if(is_array($isArr)) { echo "Array";} else { echo "Not an Array";} ?> Not an Array<br>Array Approach 2: By casting the variable to an array. We have to cast the variable to an array that we want to check. For Array: type casted array === original array Original array: john, johnson, steve Type casted array: john, johnson, steve For normal variable: type casted array != original array Original variable: friends Type casted variable: friends, , Example 2: After typecasting, an index-based array will be formed. PHP <?php $isArr = array("john", "johnson", "steve"); if((array)$isArr === $isArr) { echo "It is an Array\n";}else { echo "It is not an Array\n";} $isArr = "friends"; if((array)$isArr === $isArr) { echo "It is an Array";}else { echo "It is not an Array";} ?> It is an Array It is not an Array PHP-function PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP How to create admin login page using PHP? Different ways for passing data to view in Laravel Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24581, "s": 24553, "text": "\n22 Oct, 2021" }, { "code": null, "e": 24784, "s": 24581, "text": "There are two ways for checking whether the variable is an array or not. We can check whether a variable is an array or not by using the PHP is_array() function and by casting the variable to the array." }, { "code": null, "e": 24989, "s": 24784, "text": "Approach 1: We can check whether a variable is an array or not using the is_array() function. The PHP is_array() function is a variable handling function that checks whether a variable is an array or not." }, { "code": null, "e": 24997, "s": 24989, "text": "Syntax:" }, { "code": null, "e": 25029, "s": 24997, "text": "is_array( $variable_name ); " }, { "code": null, "e": 25167, "s": 25029, "text": "Parameter: It accepts a single parameter. This parameter must be the variable name for which the check is done if it is an array or not." }, { "code": null, "e": 25238, "s": 25167, "text": "Return value: It returns true if the boolean value is TRUE else false." }, { "code": null, "e": 25357, "s": 25238, "text": "Example 1: The is_array() function returns true(1) when passed parameter is array else it will return false (nothing)." }, { "code": null, "e": 25361, "s": 25357, "text": "PHP" }, { "code": "<?php $isArr = \"friends\"; if(is_array($isArr)) { echo \"Array\";} else { echo \"Not an Array\";} echo \"<br>\"; $isArr = array(\"smith\", \"john\", \"josh\"); if(is_array($isArr)) { echo \"Array\";} else { echo \"Not an Array\";} ?>", "e": 25596, "s": 25361, "text": null }, { "code": null, "e": 25618, "s": 25596, "text": "Not an Array<br>Array" }, { "code": null, "e": 25743, "s": 25618, "text": "Approach 2: By casting the variable to an array. We have to cast the variable to an array that we want to check. " }, { "code": null, "e": 25792, "s": 25743, "text": "For Array: type casted array === original array" }, { "code": null, "e": 25808, "s": 25792, "text": "Original array:" }, { "code": null, "e": 25829, "s": 25808, "text": "john, johnson, steve" }, { "code": null, "e": 25848, "s": 25829, "text": "Type casted array:" }, { "code": null, "e": 25869, "s": 25848, "text": "john, johnson, steve" }, { "code": null, "e": 25927, "s": 25869, "text": " For normal variable: type casted array != original array" }, { "code": null, "e": 25948, "s": 25927, "text": " Original variable:" }, { "code": null, "e": 25956, "s": 25948, "text": "friends" }, { "code": null, "e": 25979, "s": 25956, "text": " Type casted variable:" }, { "code": null, "e": 25991, "s": 25979, "text": "friends, , " }, { "code": null, "e": 26058, "s": 25991, "text": "Example 2: After typecasting, an index-based array will be formed." }, { "code": null, "e": 26062, "s": 26058, "text": "PHP" }, { "code": "<?php $isArr = array(\"john\", \"johnson\", \"steve\"); if((array)$isArr === $isArr) { echo \"It is an Array\\n\";}else { echo \"It is not an Array\\n\";} $isArr = \"friends\"; if((array)$isArr === $isArr) { echo \"It is an Array\";}else { echo \"It is not an Array\";} ?>", "e": 26334, "s": 26062, "text": null }, { "code": null, "e": 26368, "s": 26334, "text": "It is an Array\nIt is not an Array" }, { "code": null, "e": 26381, "s": 26368, "text": "PHP-function" }, { "code": null, "e": 26395, "s": 26381, "text": "PHP-Questions" }, { "code": null, "e": 26402, "s": 26395, "text": "Picked" }, { "code": null, "e": 26406, "s": 26402, "text": "PHP" }, { "code": null, "e": 26423, "s": 26406, "text": "Web Technologies" }, { "code": null, "e": 26427, "s": 26423, "text": "PHP" }, { "code": null, "e": 26525, "s": 26427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26534, "s": 26525, "text": "Comments" }, { "code": null, "e": 26547, "s": 26534, "text": "Old Comments" }, { "code": null, "e": 26629, "s": 26547, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 26693, "s": 26629, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 26767, "s": 26693, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 26809, "s": 26767, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 26860, "s": 26809, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 26916, "s": 26860, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26949, "s": 26916, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27011, "s": 26949, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27054, "s": 27011, "text": "How to fetch data from an API in ReactJS ?" } ]
Java ResultSet relative() method with example
When we execute certain SQL queries (SELECT query in general) they return tabular data. The java.sql.ResultSet interface represents such tabular data returned by the SQL statements. i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general). The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row. The relative() method of the ResultSet interface moves the ResultSet pointer/cursor n number of rows from the current position. This method returns an integer value representing the current row number to which the ResultSet pointer points to. 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 the database, retrieves the contents of the table MyPlayers into a ResultSet object, retrieves the current position of the cursor moves it in forward and backward directions relatively. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ResultSet_relative { 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); //Moving the cursor to 3rd position rs.absolute(3); System.out.println("Position of the pointer: "+rs.getRow()); //Moving the pointer 2 positions forward from the current System.out.println("Position of the pointer after moving it to 2 places forward relatively: "+rs.relative(2)); //Moving the pointer 3 positions backwards from the current System.out.println("Position of the pointer after moving it to 3 places backward relatively: "+rs.relative(-3)); } } Connection established...... Position of the pointer: 3 Position of the pointer after moving it to 2 places forward relatively: true Position of the pointer after moving it to 3 places backward relatively: true
[ { "code": null, "e": 1150, "s": 1062, "text": "When we execute certain SQL queries (SELECT query in general) they return tabular data." }, { "code": null, "e": 1244, "s": 1150, "text": "The java.sql.ResultSet interface represents such tabular data returned by the SQL statements." }, { "code": null, "e": 1434, "s": 1244, "text": "i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general)." }, { "code": null, "e": 1563, "s": 1434, "text": "The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row." }, { "code": null, "e": 1691, "s": 1563, "text": "The relative() method of the ResultSet interface moves the ResultSet pointer/cursor n number of rows from the current position." }, { "code": null, "e": 1806, "s": 1691, "text": "This method returns an integer value representing the current row number to which the ResultSet pointer points to." }, { "code": null, "e": 1906, "s": 1806, "text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below: " }, { "code": null, "e": 2099, "s": 1906, "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": 2173, "s": 2099, "text": "Now, we will insert 7 records in MyPlayers table using INSERT statements:" }, { "code": null, "e": 2835, "s": 2173, "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": 3072, "s": 2835, "text": "Following JDBC program establishes connection with the database, retrieves the contents of the table MyPlayers into a ResultSet object, retrieves the current position of the cursor moves it in forward and backward directions relatively." }, { "code": null, "e": 4379, "s": 3072, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ResultSet_relative {\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 //Moving the cursor to 3rd position\n rs.absolute(3);\n System.out.println(\"Position of the pointer: \"+rs.getRow());\n //Moving the pointer 2 positions forward from the current\n System.out.println(\"Position of the pointer after moving it to 2 places forward relatively: \"+rs.relative(2));\n //Moving the pointer 3 positions backwards from the current\n System.out.println(\"Position of the pointer after moving it to 3 places backward relatively: \"+rs.relative(-3));\n }\n}" }, { "code": null, "e": 4590, "s": 4379, "text": "Connection established......\nPosition of the pointer: 3\nPosition of the pointer after moving it to 2 places forward relatively: true\nPosition of the pointer after moving it to 3 places backward relatively: true" } ]
EasyMock - JUnit Integration
In this chapter, we'll learn how to integrate JUnit and EasyMock together. Here we will create a Math Application which uses CalculatorService to perform basic mathematical operations such as addition, subtraction, multiply, and division. We'll use EasyMock to mock the dummy implementation of CalculatorService. In addition, we've made extensive use of annotations to showcase their compatibility with both JUnit and EasyMock. The process is discussed below in a step-by-step manner. Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); } } Step 4: Create a class to execute to test cases. Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. true To learn more about JUnit, please refer to JUnit Tutorial at Tutorials Point. Print Add Notes Bookmark this page
[ { "code": null, "e": 2337, "s": 1909, "text": "In this chapter, we'll learn how to integrate JUnit and EasyMock together. Here we will create a Math Application which uses CalculatorService to perform basic mathematical operations such as addition, subtraction, multiply, and division. We'll use EasyMock to mock the dummy implementation of CalculatorService. In addition, we've made extensive use of annotations to showcase their compatibility with both JUnit and EasyMock." }, { "code": null, "e": 2394, "s": 2337, "text": "The process is discussed below in a step-by-step manner." }, { "code": null, "e": 2481, "s": 2394, "text": "Step 1: Create an interface called CalculatorService to provide mathematical functions" }, { "code": null, "e": 2510, "s": 2481, "text": "File: CalculatorService.java" }, { "code": null, "e": 2770, "s": 2510, "text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}" }, { "code": null, "e": 2827, "s": 2770, "text": "Step 2: Create a JAVA class to represent MathApplication" }, { "code": null, "e": 2854, "s": 2827, "text": "File: MathApplication.java" }, { "code": null, "e": 3479, "s": 2854, "text": "public class MathApplication {\n private CalculatorService calcService;\n\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n public double add(double input1, double input2){\n return calcService.add(input1, input2);\n }\n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}" }, { "code": null, "e": 3518, "s": 3479, "text": "Step 3: Test the MathApplication class" }, { "code": null, "e": 3638, "s": 3518, "text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock." }, { "code": null, "e": 3671, "s": 3638, "text": "File: MathApplicationTester.java" }, { "code": null, "e": 4675, "s": 3671, "text": "import org.easymock.EasyMock;\nimport org.easymock.EasyMockRunner;\nimport org.easymock.Mock;\nimport org.easymock.TestSubject;\n\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\n// @RunWith attaches a runner with the test class to initialize the test data\n@RunWith(EasyMockRunner.class)\npublic class MathApplicationTester {\n // @TestSubject annotation is used to identify class which is going to use the mock object\n @TestSubject\n MathApplication mathApplication = new MathApplication();\n\n //@Mock annotation is used to create the mock object to be injected\n @Mock\n CalculatorService calcService;\n\n @Test\n public void testAdd(){\n //add the behavior of calc service to add two numbers\n EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);\n\n //activate the mock\n EasyMock.replay(calcService);\t\n\t\t\n //test the add functionality\n Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);\n }\n}" }, { "code": null, "e": 4724, "s": 4675, "text": "Step 4: Create a class to execute to test cases." }, { "code": null, "e": 4818, "s": 4724, "text": "Create a java class file named TestRunner in C:\\> EasyMock_WORKSPACE to execute Test case(s)." }, { "code": null, "e": 4840, "s": 4818, "text": "File: TestRunner.java" }, { "code": null, "e": 5267, "s": 4840, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 5293, "s": 5267, "text": "Step 5: Verify the Result" }, { "code": null, "e": 5347, "s": 5293, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 5463, "s": 5347, "text": "C:\\EasyMock_WORKSPACE>javac CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java\n" }, { "code": null, "e": 5507, "s": 5463, "text": "Now run the Test Runner to see the result −" }, { "code": null, "e": 5546, "s": 5507, "text": "C:\\EasyMock_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 5565, "s": 5546, "text": "Verify the output." }, { "code": null, "e": 5571, "s": 5565, "text": "true\n" }, { "code": null, "e": 5649, "s": 5571, "text": "To learn more about JUnit, please refer to JUnit Tutorial at Tutorials Point." }, { "code": null, "e": 5656, "s": 5649, "text": " Print" }, { "code": null, "e": 5667, "s": 5656, "text": " Add Notes" } ]
How to use a transcript in PowerShell?
Transcript in Powershell is like a recording session. So whenever you start a transcript in PowerShell, it starts recording your commands and outputs and doesn't matter if there is any error output, it gets recorded too. To start the transcript, you need to run Start-Transcript command at the beginning, and then whatever you write, it will get recorded. To start the recording, you need to write Start-Transcript command and have to give the path for the transcript as shown in the below example, Start-Transcript -Path C:\Temp\sessionrecord.txt Once you enter the above command you will get the message as shown below. Start-Transcript -Path .\Sessionrecording.txt PS E:\scripts\Powershell> Start-Transcript -Path .\Sessionrecording.txt Transcript started, output file is .\Sessionrecording.txt Below is the PowerShell session screen after starting the transcript. PS E:\scripts\Powershell> Get-Service | Select -First 2 Status Name DisplayName ------ ---- ----------- Stopped AarSvc_777b7 Agent Activation Runtime_777b7 Running AdobeARMservice Adobe Acrobat Update Service PS E:\scripts\Powershell> wrongcommand wrongcommand : The term 'wrongcommand' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + wrongcommand + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (wrongcommand:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException The above commands should get recorded in the transcript. Simultaneously you can check the transcript file that the commands and outputs are recorded parallelly. To stop the transcript, you need to run the Stop-Transcript command. PS E:\scripts\Powershell> Stop-Transcript Transcript stopped, output file is E:\scripts\Powershell\Sessionrecording.txt We will now check our transcript file sessionrecording.txt stored at the current location. ********************** Windows PowerShell transcript start Start time: 20200711122407 Username: DESKTOP-9435KM9\admin RunAs User: DESKTOP-9435KM9\admin Configuration Name: Machine: DESKTOP-9435KM9 (Microsoft Windows NT 10.0.18362.0) Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe Process ID: 4520 PSVersion: 5.1.18362.752 PSEdition: Desktop PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.18362.752 BuildVersion: 10.0.18362.752 CLRVersion: 4.0.30319.42000 WSManStackVersion: 3.0 PSRemotingProtocolVersion: 2.3 SerializationVersion: 1.1.0.1 ********************** Transcript started, output file is .\Sessionrecording.txt PS E:\scripts\Powershell> Get-Service | Select -First 2 Status Name DisplayName ------ ---- ----------- Stopped AarSvc_777b7 Agent Activation Runtime_777b7 Running AdobeARMservice Adobe Acrobat Update Service PS E:\scripts\Powershell> wrongcommand wrongcommand : The term 'wrongcommand' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + wrongcommand + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (wrongcommand:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException wrongcommand : The term 'wrongcommand' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + wrongcommand + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (wrongcommand:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS E:\scripts\Powershell> Stop-Transcript ********************** Windows PowerShell transcript end End time: 20200711124434 ********************** You can notice in the above output that the user who executed the commands, computer name, start time, and end time is also recorded.
[ { "code": null, "e": 1418, "s": 1062, "text": "Transcript in Powershell is like a recording session. So whenever you start a transcript in PowerShell, it starts recording your commands and outputs and doesn't matter if there is any error output, it gets recorded too. To start the transcript, you need to run Start-Transcript command at the beginning, and then whatever you write, it will get recorded." }, { "code": null, "e": 1561, "s": 1418, "text": "To start the recording, you need to write Start-Transcript command and have to give the path for the transcript as shown in the below example," }, { "code": null, "e": 1610, "s": 1561, "text": "Start-Transcript -Path C:\\Temp\\sessionrecord.txt" }, { "code": null, "e": 1684, "s": 1610, "text": "Once you enter the above command you will get the message as shown below." }, { "code": null, "e": 1730, "s": 1684, "text": "Start-Transcript -Path .\\Sessionrecording.txt" }, { "code": null, "e": 1860, "s": 1730, "text": "PS E:\\scripts\\Powershell> Start-Transcript -Path .\\Sessionrecording.txt\nTranscript started, output file is .\\Sessionrecording.txt" }, { "code": null, "e": 1930, "s": 1860, "text": "Below is the PowerShell session screen after starting the transcript." }, { "code": null, "e": 2595, "s": 1930, "text": "PS E:\\scripts\\Powershell> Get-Service | Select -First 2\nStatus Name DisplayName\n------ ---- -----------\nStopped AarSvc_777b7 Agent Activation Runtime_777b7\nRunning AdobeARMservice Adobe Acrobat Update Service\n\n\nPS E:\\scripts\\Powershell> wrongcommand wrongcommand : The term 'wrongcommand' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if\na path was included, verify that the path is correct and try again.\nAt line:1 char:1\n+ wrongcommand\n+ ~~~~~~~~~~~~\n+ CategoryInfo : ObjectNotFound: (wrongcommand:String) [], CommandNotFoundException\n+ FullyQualifiedErrorId : CommandNotFoundException\n" }, { "code": null, "e": 2757, "s": 2595, "text": "The above commands should get recorded in the transcript. Simultaneously you can check the transcript file that the commands and outputs are recorded parallelly." }, { "code": null, "e": 2826, "s": 2757, "text": "To stop the transcript, you need to run the Stop-Transcript command." }, { "code": null, "e": 2946, "s": 2826, "text": "PS E:\\scripts\\Powershell> Stop-Transcript\nTranscript stopped, output file is E:\\scripts\\Powershell\\Sessionrecording.txt" }, { "code": null, "e": 3037, "s": 2946, "text": "We will now check our transcript file sessionrecording.txt stored at the current location." }, { "code": null, "e": 4917, "s": 3037, "text": "**********************\nWindows PowerShell transcript start\nStart time: 20200711122407\nUsername: DESKTOP-9435KM9\\admin\nRunAs User: DESKTOP-9435KM9\\admin\nConfiguration Name:\nMachine: DESKTOP-9435KM9 (Microsoft Windows NT 10.0.18362.0)\nHost Application: C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\nProcess ID: 4520\nPSVersion: 5.1.18362.752\nPSEdition: Desktop\nPSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.18362.752\nBuildVersion: 10.0.18362.752\nCLRVersion: 4.0.30319.42000\nWSManStackVersion: 3.0\nPSRemotingProtocolVersion: 2.3\nSerializationVersion: 1.1.0.1\n**********************\nTranscript started, output file is .\\Sessionrecording.txt\nPS E:\\scripts\\Powershell> Get-Service | Select -First 2\n\nStatus Name DisplayName\n------ ---- -----------\nStopped AarSvc_777b7 Agent Activation Runtime_777b7\nRunning AdobeARMservice Adobe Acrobat Update Service\n\n\nPS E:\\scripts\\Powershell> wrongcommand\nwrongcommand : The term 'wrongcommand' is not recognized as the name of a cmdlet, function, script file, or operable\nprogram. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.\nAt line:1 char:1\n+ wrongcommand\n+ ~~~~~~~~~~~~\n+ CategoryInfo : ObjectNotFound: (wrongcommand:String) [], CommandNotFoundException\n+ FullyQualifiedErrorId : CommandNotFoundException\nwrongcommand : The term 'wrongcommand' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if\na path was included, verify that the path is correct and try again.\nAt line:1 char:1\n+ wrongcommand\n+ ~~~~~~~~~~~~\n+ CategoryInfo : ObjectNotFound: (wrongcommand:String) [], CommandNotFoundException\n+ FullyQualifiedErrorId : CommandNotFoundException\n\nPS E:\\scripts\\Powershell> Stop-Transcript\n**********************\nWindows PowerShell transcript end\nEnd time: 20200711124434\n**********************" }, { "code": null, "e": 5051, "s": 4917, "text": "You can notice in the above output that the user who executed the commands, computer name, start time, and end time is also recorded." } ]
Count nodes of linked list | Practice | GeeksforGeeks
Given a singly linked list. The task is to find the length of the linked list, where length is defined as the number of nodes in the linked list. Example 1: Input: LinkedList: 1->2->3->4->5 Output: 5 Explanation: Count of nodes in the linked list is 5, which is its length. Example 2: Input: LinkedList: 2->4->6->7->5->1->0 Output: 7 Explanation: Count of nodes in the linked list is 7. Hence, the output is 7. Your Task: Your task is to complete the given function getCount(), which takes a head reference as an argument and should return the length of the linked list. Expected Time Complexity : O(N) Expected Auxilliary Space : O(1) Constraints: 1 <= N <= 105 1 <= value <= 103 0 prabhukumarsawraj4 hours ago Using recursion to get result easy class Solution { public: //Function to count nodes of a linked list. int getCount(struct Node* head){ //Code here if(head==NULL) return 0; else return getCount(head->next)+1; } }; 0 ghostlearner212 days ago public static int getCount(Node head) { Node n = head; int count = 0; while(n!=null){ count++; n = n.next; } return count; } 0 svidushi16105 days ago class Solution: def getCount(self, head_node): count= 0 curr= head_node while curr != None: count +=1 curr= curr.next return count 0 mayank180919996 days ago int getCount(struct Node* head) { int count=0; struct Node*temp=head; while(temp!=NULL){ count++; temp=temp->next; } return count; } +1 mohitraj31254 weeks ago int getCount(struct Node* head){ //Code here int count=0; while(head!=NULL) { count++; head= head->next; } return count; } 0 ankitmaurya02251 month ago 0 sachinmishraravi1 month ago JAVA class Solution { //Function to count nodes of a linked list. public static int getCount(Node head) { Node current=head; int count=0; while(current!=null){ count=count+1; current=current.next; } //Code here return count; } } 0 ajinkyahimanshu0071 month ago Simple and Easy to understand Python Code: def getCount(self, head_node): count = 0 curr = head_node while curr: count += 1 curr = curr.next return count 0 atif836141 month ago basic problem of link list : int count=0; if(head==null){ return 0; } while(head!=null){ count++; head=head.next; } return count; } +1 arche1 month ago C++ Very Simple Recursive Solution int getCount(struct Node* head){ if(head==NULL) return 0; return 1 + getCount(head->next); } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 384, "s": 238, "text": "Given a singly linked list. The task is to find the length of the linked list, where length is defined as the number of nodes in the linked list." }, { "code": null, "e": 395, "s": 384, "text": "Example 1:" }, { "code": null, "e": 514, "s": 395, "text": "Input:\nLinkedList: 1->2->3->4->5\nOutput: 5\nExplanation: Count of nodes in the \nlinked list is 5, which is its length.\n" }, { "code": null, "e": 525, "s": 514, "text": "Example 2:" }, { "code": null, "e": 651, "s": 525, "text": "Input:\nLinkedList: 2->4->6->7->5->1->0\nOutput: 7\nExplanation: Count of nodes in the\nlinked list is 7. Hence, the output\nis 7." }, { "code": null, "e": 811, "s": 651, "text": "Your Task:\nYour task is to complete the given function getCount(), which takes a head reference as an argument and should return the length of the linked list." }, { "code": null, "e": 876, "s": 811, "text": "Expected Time Complexity : O(N)\nExpected Auxilliary Space : O(1)" }, { "code": null, "e": 921, "s": 876, "text": "Constraints:\n1 <= N <= 105\n1 <= value <= 103" }, { "code": null, "e": 925, "s": 923, "text": "0" }, { "code": null, "e": 954, "s": 925, "text": "prabhukumarsawraj4 hours ago" }, { "code": null, "e": 989, "s": 954, "text": "Using recursion to get result easy" }, { "code": null, "e": 1226, "s": 989, "text": "class Solution\n{\n public:\n //Function to count nodes of a linked list.\n int getCount(struct Node* head){\n \n //Code here\n if(head==NULL)\n return 0;\n else\n return getCount(head->next)+1;\n }\n};" }, { "code": null, "e": 1228, "s": 1226, "text": "0" }, { "code": null, "e": 1253, "s": 1228, "text": "ghostlearner212 days ago" }, { "code": null, "e": 1432, "s": 1253, "text": "public static int getCount(Node head) { Node n = head; int count = 0; while(n!=null){ count++; n = n.next; } return count; }" }, { "code": null, "e": 1434, "s": 1432, "text": "0" }, { "code": null, "e": 1457, "s": 1434, "text": "svidushi16105 days ago" }, { "code": null, "e": 1641, "s": 1457, "text": "class Solution: def getCount(self, head_node): count= 0 curr= head_node while curr != None: count +=1 curr= curr.next return count" }, { "code": null, "e": 1643, "s": 1641, "text": "0" }, { "code": null, "e": 1668, "s": 1643, "text": "mayank180919996 days ago" }, { "code": null, "e": 1871, "s": 1668, "text": "int getCount(struct Node* head)\n {\n int count=0;\n struct Node*temp=head;\n while(temp!=NULL){\n count++;\n temp=temp->next;\n }\n return count;\n }" }, { "code": null, "e": 1874, "s": 1871, "text": "+1" }, { "code": null, "e": 1898, "s": 1874, "text": "mohitraj31254 weeks ago" }, { "code": null, "e": 2083, "s": 1898, "text": " int getCount(struct Node* head){ //Code here int count=0; while(head!=NULL) { count++; head= head->next; } return count; }" }, { "code": null, "e": 2085, "s": 2083, "text": "0" }, { "code": null, "e": 2112, "s": 2085, "text": "ankitmaurya02251 month ago" }, { "code": null, "e": 2114, "s": 2112, "text": "0" }, { "code": null, "e": 2142, "s": 2114, "text": "sachinmishraravi1 month ago" }, { "code": null, "e": 2147, "s": 2142, "text": "JAVA" }, { "code": null, "e": 2451, "s": 2147, "text": "class Solution\n{\n //Function to count nodes of a linked list.\n public static int getCount(Node head)\n { Node current=head;\n int count=0;\n while(current!=null){\n count=count+1;\n current=current.next;\n }\n //Code here\n return count;\n }\n}" }, { "code": null, "e": 2455, "s": 2453, "text": "0" }, { "code": null, "e": 2485, "s": 2455, "text": "ajinkyahimanshu0071 month ago" }, { "code": null, "e": 2528, "s": 2485, "text": "Simple and Easy to understand Python Code:" }, { "code": null, "e": 2692, "s": 2530, "text": "def getCount(self, head_node): count = 0 curr = head_node while curr: count += 1 curr = curr.next return count" }, { "code": null, "e": 2694, "s": 2692, "text": "0" }, { "code": null, "e": 2715, "s": 2694, "text": "atif836141 month ago" }, { "code": null, "e": 2744, "s": 2715, "text": "basic problem of link list :" }, { "code": null, "e": 2909, "s": 2744, "text": "int count=0; if(head==null){ return 0; } while(head!=null){ count++; head=head.next; } return count; }" }, { "code": null, "e": 2912, "s": 2909, "text": "+1" }, { "code": null, "e": 2929, "s": 2912, "text": "arche1 month ago" }, { "code": null, "e": 2964, "s": 2929, "text": "C++ Very Simple Recursive Solution" }, { "code": null, "e": 3069, "s": 2964, "text": "int getCount(struct Node* head){ \n if(head==NULL) return 0;\n return 1 + getCount(head->next); \n}" }, { "code": null, "e": 3215, "s": 3069, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3251, "s": 3215, "text": " Login to access your submissions. " }, { "code": null, "e": 3261, "s": 3251, "text": "\nProblem\n" }, { "code": null, "e": 3271, "s": 3261, "text": "\nContest\n" }, { "code": null, "e": 3334, "s": 3271, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3482, "s": 3334, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3690, "s": 3482, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3796, "s": 3690, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Create a chart from JSON data using Fetch GET request (Fetch API) in JavaScript - GeeksforGeeks
29 Nov, 2021 In this article, we are going to create a simple chart by fetching JSON Data using Fetch() method of Fetch API. The Fetch API allows us to conduct HTTP requests in a simpler way. The fetch() method: The fetch method fetches a resource thereby returning a promise which is fulfilled once the response is available. Syntax: const response = fetch(resource [, init]) Parameters: resource: The path of the resource( can also be a local file) init: Any further options you want to add such as headers, body, method, etc. Approach: The steps can be described as below: Step 1: The first step is to call the fetch function by specifying the path of the resource. In this example, we will be using the free resource from the URL as follows: “https://datausa.io/api/data?drilldowns=Nation&measures=Population It contains the population of the U.S in different years. The Response object is shown below: Response {type: “cors”,URL: “https://datausa.io/api/data?drilldowns=Nation&measures=Population”,redirected: false,status: 200,ok: true,statusText: “OK”,headers: Headers,body: ReadableStream,bodyUsed: true}body: ReadableStream { locked: true }bodyUsed: trueheaders: Headers { }ok: trueredirected: falsestatus: 200statusText: “OK”type: “cors”url: “https://datausa.io/api/data?drilldowns=Nation&measures=Population”<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), ... } Step 2: We will then get a result in the stream of data. We are then viewing our JSON data which is as follows: Object { data: (7) [...], source: (1) [...] }data: Array(7) [ {...}, {...}, {...}, ... ]0: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2019, ...}​”ID Nation”: “01000US”​​​“ID Year”: 2019​​​Nation: “United States”​​​Population: 328239523​​​“Slug Nation”: “united-states”​​​Year: “2019”​​​<prototype>: Object { ... }​​1: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2018, ...}​​2: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2017, ...}​​3: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2016, ...}4: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2015, ...}5: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2014, ...}6: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2013, ...}length: 7​​<prototype>: Array []​source: Array [ {...} ]​<prototype>: Object { ... }​ As you can see we have an array of length 7. And each object has several properties. Out of these properties, we are just storing the two properties i.e., Year and Population into two different arrays by using a for loop. Step 3: The final step is we are creating a chart from the data received. For doing so, we are using chart.js which is an easy way to include charts on our website. Add CDN link in your head tag <script src=”https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js”> Below is the implementation of the above approach: HTML <html> <head> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"> </script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"> </script> <title>US Population Chart</title></head> <body> <canvas id="bar-chart" width="800" height="450"> </canvas> <script> getData(); async function getData() { const response = await fetch('https://datausa.io/api/data?drilldowns=Nation&measures=Population'); console.log(response); const data = await response.json(); console.log(data); length = data.data.length; console.log(length); labels = []; values = []; for (i = 0; i < length; i++) { labels.push(data.data[i].Year); values.push(data.data[i].Population); } new Chart(document.getElementById("bar-chart"), { type: 'bar', data: { labels: labels, datasets: [ { label: "Population (millions)", backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850", "#CD5C5C", "#40E0D0"], data: values } ] }, options: { legend: { display: false }, title: { display: true, text: 'U.S population' } } }); } </script></body> </html> javascript-object JavaScript-Questions 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 filter object array based on attributes? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 25300, "s": 25272, "text": "\n29 Nov, 2021" }, { "code": null, "e": 25479, "s": 25300, "text": "In this article, we are going to create a simple chart by fetching JSON Data using Fetch() method of Fetch API. The Fetch API allows us to conduct HTTP requests in a simpler way." }, { "code": null, "e": 25615, "s": 25479, "text": "The fetch() method: The fetch method fetches a resource thereby returning a promise which is fulfilled once the response is available. " }, { "code": null, "e": 25624, "s": 25615, "text": "Syntax: " }, { "code": null, "e": 25666, "s": 25624, "text": "const response = fetch(resource [, init])" }, { "code": null, "e": 25679, "s": 25666, "text": " Parameters:" }, { "code": null, "e": 25741, "s": 25679, "text": "resource: The path of the resource( can also be a local file)" }, { "code": null, "e": 25819, "s": 25741, "text": "init: Any further options you want to add such as headers, body, method, etc." }, { "code": null, "e": 25866, "s": 25819, "text": "Approach: The steps can be described as below:" }, { "code": null, "e": 26036, "s": 25866, "text": "Step 1: The first step is to call the fetch function by specifying the path of the resource. In this example, we will be using the free resource from the URL as follows:" }, { "code": null, "e": 26103, "s": 26036, "text": "“https://datausa.io/api/data?drilldowns=Nation&measures=Population" }, { "code": null, "e": 26197, "s": 26103, "text": "It contains the population of the U.S in different years. The Response object is shown below:" }, { "code": null, "e": 26706, "s": 26197, "text": "Response {type: “cors”,URL: “https://datausa.io/api/data?drilldowns=Nation&measures=Population”,redirected: false,status: 200,ok: true,statusText: “OK”,headers: Headers,body: ReadableStream,bodyUsed: true}body: ReadableStream { locked: true }bodyUsed: trueheaders: Headers { }ok: trueredirected: falsestatus: 200statusText: “OK”type: “cors”url: “https://datausa.io/api/data?drilldowns=Nation&measures=Population”<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), ... }" }, { "code": null, "e": 26818, "s": 26706, "text": "Step 2: We will then get a result in the stream of data. We are then viewing our JSON data which is as follows:" }, { "code": null, "e": 27720, "s": 26818, "text": "Object { data: (7) [...], source: (1) [...] }data: Array(7) [ {...}, {...}, {...}, ... ]0: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2019, ...}​”ID Nation”: “01000US”​​​“ID Year”: 2019​​​Nation: “United States”​​​Population: 328239523​​​“Slug Nation”: “united-states”​​​Year: “2019”​​​<prototype>: Object { ... }​​1: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2018, ...}​​2: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2017, ...}​​3: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2016, ...}4: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2015, ...}5: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2014, ...}6: Object {“ID Nation”: “01000US”,Nation: “United States”,“ID Year”: 2013, ...}length: 7​​<prototype>: Array []​source: Array [ {...} ]​<prototype>: Object { ... }​" }, { "code": null, "e": 27942, "s": 27720, "text": "As you can see we have an array of length 7. And each object has several properties. Out of these properties, we are just storing the two properties i.e., Year and Population into two different arrays by using a for loop." }, { "code": null, "e": 28137, "s": 27942, "text": "Step 3: The final step is we are creating a chart from the data received. For doing so, we are using chart.js which is an easy way to include charts on our website. Add CDN link in your head tag" }, { "code": null, "e": 28215, "s": 28137, "text": "<script src=”https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js”>" }, { "code": null, "e": 28266, "s": 28215, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28271, "s": 28266, "text": "HTML" }, { "code": "<html> <head> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-1.12.0.min.js\"> </script> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js\"> </script> <title>US Population Chart</title></head> <body> <canvas id=\"bar-chart\" width=\"800\" height=\"450\"> </canvas> <script> getData(); async function getData() { const response = await fetch('https://datausa.io/api/data?drilldowns=Nation&measures=Population'); console.log(response); const data = await response.json(); console.log(data); length = data.data.length; console.log(length); labels = []; values = []; for (i = 0; i < length; i++) { labels.push(data.data[i].Year); values.push(data.data[i].Population); } new Chart(document.getElementById(\"bar-chart\"), { type: 'bar', data: { labels: labels, datasets: [ { label: \"Population (millions)\", backgroundColor: [\"#3e95cd\", \"#8e5ea2\", \"#3cba9f\", \"#e8c3b9\", \"#c45850\", \"#CD5C5C\", \"#40E0D0\"], data: values } ] }, options: { legend: { display: false }, title: { display: true, text: 'U.S population' } } }); } </script></body> </html>", "e": 30347, "s": 28271, "text": null }, { "code": null, "e": 30365, "s": 30347, "text": "javascript-object" }, { "code": null, "e": 30386, "s": 30365, "text": "JavaScript-Questions" }, { "code": null, "e": 30397, "s": 30386, "text": "JavaScript" }, { "code": null, "e": 30414, "s": 30397, "text": "Web Technologies" }, { "code": null, "e": 30512, "s": 30414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30521, "s": 30512, "text": "Comments" }, { "code": null, "e": 30534, "s": 30521, "text": "Old Comments" }, { "code": null, "e": 30595, "s": 30534, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30636, "s": 30595, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30690, "s": 30636, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30730, "s": 30690, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30778, "s": 30730, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 30820, "s": 30778, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30853, "s": 30820, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30903, "s": 30853, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 30965, "s": 30903, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to free up the memory in JavaScript?
Regardless of the programming language, memory life cycle is pretty much always the same − Allocate the memory you need Use the allocated memory (read, write) Release the allocated memory when it is not needed anymore The second part is explicit in all languages. Use of allocated memory needs to be done by the developer. The first and last parts are explicit in low-level languages like C but are mostly implicit in high-level languages like JavaScript. Hence there is no explicit way to allocate or free up memory in JavaScript. Just initializing objects allocates memory for them. When the variable goes out of scope, it is automatically garbage collected(frees up memory taken by that object.) function test() { // Allocate and use the memory let x = { name: "John", age: 24 } console.log(x); return null; // As soon as the method goes out of scope, it is garbage collected // and it's memory freed. } test(); The cycle mentioned in the comments is carried out every time the method is called.
[ { "code": null, "e": 1153, "s": 1062, "text": "Regardless of the programming language, memory life cycle is pretty much always the same −" }, { "code": null, "e": 1182, "s": 1153, "text": "Allocate the memory you need" }, { "code": null, "e": 1221, "s": 1182, "text": "Use the allocated memory (read, write)" }, { "code": null, "e": 1280, "s": 1221, "text": "Release the allocated memory when it is not needed anymore" }, { "code": null, "e": 1385, "s": 1280, "text": "The second part is explicit in all languages. Use of allocated memory needs to be done by the developer." }, { "code": null, "e": 1518, "s": 1385, "text": "The first and last parts are explicit in low-level languages like C but are mostly implicit in high-level languages like JavaScript." }, { "code": null, "e": 1761, "s": 1518, "text": "Hence there is no explicit way to allocate or free up memory in JavaScript. Just initializing objects allocates memory for them. When the variable goes out of scope, it is automatically garbage collected(frees up memory taken by that object.)" }, { "code": null, "e": 2010, "s": 1761, "text": "function test() {\n // Allocate and use the memory\n let x = {\n name: \"John\",\n age: 24\n }\n console.log(x);\n return null;\n // As soon as the method goes out of scope, it is garbage collected\n // and it's memory freed.\n}\ntest();" }, { "code": null, "e": 2094, "s": 2010, "text": "The cycle mentioned in the comments is carried out every time the method is called." } ]
Computer Networks | Set 11 - GeeksforGeeks
27 Mar, 2017 Following questions have been asked in GATE CS 2006 exam. 1) Station A uses 32 byte packets to transmit messages to Station B using a sliding window protocol. The round trip delay between A and B is 80 milliseconds and the bottleneck bandwidth on the path between A and B is 128 kbps. What is the optimal window size that A should use?(A) 20(B) 40(C) 160(D) 320 Answer (B) Round Trip propagation delay = 80ms Frame size = 32*8 bits Bandwidth = 128kbps Transmission Time = 32*8/(128) ms = 2 ms Let n be the window size. UtiliZation = n/(1+2a) where a = Propagation time / transmission time = n/(1+80/2) For maximum utilization: n = 41 which is close to option (B) 2) Two computers C1 and C2 are configured as follows. C1 has IP address 203.197.2.53 and netmask 255.255.128.0. C2 has IP address 203.197.75.201 and netmask 255.255.192.0. which one of the following statements is true?(A) C1 and C2 both assume they are on the same network(B) C2 assumes C1 is on same network, but C1 assumes C2 is on a different network(C) C1 assumes C2 is on same network, but C2 assumes C1 is on a different network(D) C1 and C2 both assume they are on different networks. Answer (C) Network Id of C1 = bitwise '&' of IP of C1 and subnet mask of C1 = (203.197.2.53) & (255.255.128.0) = 203.197.0.0 C1 sees network ID of C2 as bitwise '&' of IP of C2 and subnet mask of C1 = (203.197.75.201) & (255.255.128.0) = 203.197.0.0 which is same as Network Id of C1. Network Id of C2 = bitwise '&' of IP of C2 and subnet mask of C2 = (203.197.75.201) & (255.255.192.0) = 203.197.64.0 C2 sees network ID of C1 as bitwise '&' of IP of C1 and subnet mask of C2 = (203.197.2.53) & (255.255.192.0) = 203.197.0.0 which is different from Network Id of C2. Therefore, C1 assumes C2 is on same network, but C2 assumes C1 is on a different network. 3) Station A needs to send a message consisting of 9 packets to Station B using a sliding window (window size 3) and go-back-n error control strategy. All packets are ready and immediately available for transmission. If every 5th packet that A transmits gets lost (but no acks from B ever get lost), then what is the number of packets that A will transmit for sending the message to B?(A) 12(B) 14(C) 16(D) 18 Answer (C)Total 16 packets are sent. See following table for sequence of events. Since go-back-n error control strategy is used, all packets after a lost packet are sent again. Sender Receiver 1 2 1 3 2 4 3 5 4 6 7 6 7 [Timeout for 5] 5 6 5 7 6 8 9 8 9 [Timeout for 7] 7 8 7 9 8 [Timeout for 9] 9 9 Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above GATE-CS-2006 Computer Networks GATE CS MCQ Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Data encryption standard (DES) | Set 1 Types of Network Topology UDP Server-Client implementation in C TCP 3-Way Handshake Process Differences between IPv4 and IPv6 ACID Properties in DBMS Page Replacement Algorithms in Operating Systems Types of Operating Systems Normal Forms in DBMS Semaphores in Process Synchronization
[ { "code": null, "e": 23936, "s": 23908, "text": "\n27 Mar, 2017" }, { "code": null, "e": 23994, "s": 23936, "text": "Following questions have been asked in GATE CS 2006 exam." }, { "code": null, "e": 24298, "s": 23994, "text": "1) Station A uses 32 byte packets to transmit messages to Station B using a sliding window protocol. The round trip delay between A and B is 80 milliseconds and the bottleneck bandwidth on the path between A and B is 128 kbps. What is the optimal window size that A should use?(A) 20(B) 40(C) 160(D) 320" }, { "code": null, "e": 24309, "s": 24298, "text": "Answer (B)" }, { "code": null, "e": 24616, "s": 24309, "text": "Round Trip propagation delay = 80ms \nFrame size = 32*8 bits\nBandwidth = 128kbps\nTransmission Time = 32*8/(128) ms = 2 ms\n\nLet n be the window size.\n\nUtiliZation = n/(1+2a) where a = Propagation time / transmission time\n = n/(1+80/2)\n\nFor maximum utilization: n = 41 which is close to option (B)\n" }, { "code": null, "e": 25108, "s": 24616, "text": "2) Two computers C1 and C2 are configured as follows. C1 has IP address 203.197.2.53 and netmask 255.255.128.0. C2 has IP address 203.197.75.201 and netmask 255.255.192.0. which one of the following statements is true?(A) C1 and C2 both assume they are on the same network(B) C2 assumes C1 is on same network, but C1 assumes C2 is on a different network(C) C1 assumes C2 is on same network, but C2 assumes C1 is on a different network(D) C1 and C2 both assume they are on different networks." }, { "code": null, "e": 25119, "s": 25108, "text": "Answer (C)" }, { "code": null, "e": 25815, "s": 25119, "text": "Network Id of C1 = bitwise '&' of IP of C1 and subnet mask of C1 \n = (203.197.2.53) & (255.255.128.0) \n = 203.197.0.0\nC1 sees network ID of C2 as bitwise '&' of IP of C2 and subnet mask of C1 \n = (203.197.75.201) & (255.255.128.0) \n = 203.197.0.0\nwhich is same as Network Id of C1.\n\nNetwork Id of C2 = bitwise '&' of IP of C2 and subnet mask of C2\n = (203.197.75.201) & (255.255.192.0) \n = 203.197.64.0\nC2 sees network ID of C1 as bitwise '&' of IP of C1 and subnet mask of C2\n = (203.197.2.53) & (255.255.192.0) \n = 203.197.0.0\nwhich is different from Network Id of C2.\n" }, { "code": null, "e": 25905, "s": 25815, "text": "Therefore, C1 assumes C2 is on same network, but C2 assumes C1 is on a different network." }, { "code": null, "e": 26315, "s": 25905, "text": "3) Station A needs to send a message consisting of 9 packets to Station B using a sliding window (window size 3) and go-back-n error control strategy. All packets are ready and immediately available for transmission. If every 5th packet that A transmits gets lost (but no acks from B ever get lost), then what is the number of packets that A will transmit for sending the message to B?(A) 12(B) 14(C) 16(D) 18" }, { "code": null, "e": 26492, "s": 26315, "text": "Answer (C)Total 16 packets are sent. See following table for sequence of events. Since go-back-n error control strategy is used, all packets after a lost packet are sent again." }, { "code": null, "e": 26894, "s": 26492, "text": "Sender Receiver\n 1 \n 2 1\n 3 2\n 4 3\n 5 4\n 6 \n 7 6\n 7 \n [Timeout for 5] \n\n 5\n 6 5\n 7 6\n 8\n 9 \n 8\n 9\n [Timeout for 7]\n\n 7 \n 8 7\n 9 8\n\n\n [Timeout for 9]\n 9 \n 9\n" }, { "code": null, "e": 27008, "s": 26894, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc." }, { "code": null, "e": 27156, "s": 27008, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above" }, { "code": null, "e": 27169, "s": 27156, "text": "GATE-CS-2006" }, { "code": null, "e": 27187, "s": 27169, "text": "Computer Networks" }, { "code": null, "e": 27195, "s": 27187, "text": "GATE CS" }, { "code": null, "e": 27199, "s": 27195, "text": "MCQ" }, { "code": null, "e": 27217, "s": 27199, "text": "Computer Networks" }, { "code": null, "e": 27315, "s": 27217, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27354, "s": 27315, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 27380, "s": 27354, "text": "Types of Network Topology" }, { "code": null, "e": 27418, "s": 27380, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27446, "s": 27418, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 27480, "s": 27446, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 27504, "s": 27480, "text": "ACID Properties in DBMS" }, { "code": null, "e": 27553, "s": 27504, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 27580, "s": 27553, "text": "Types of Operating Systems" }, { "code": null, "e": 27601, "s": 27580, "text": "Normal Forms in DBMS" } ]
Java Program for Cocktail Sort
Cocktail Sort works in contrast to bubble sort, wherein elements are iterated from left to right, and the largest element is first brought to its correct position and so on. In cocktail sort, elements are iterated over in both the directions (left and right) in an alternating fashion. Following is the program for Cocktail Sort − Live Demo public class Demo{ static int temp; static void Cocktail(int a[], int n){ boolean swap = true; int begin = 0,i; int end = n - 1; while (swap) { swap = false; for (i = begin; i < end; ++i){ if (a[i] > a[i + 1]){ temp = a[i]; a[i]=a[i+1]; a[i+1]=temp; swap = true; } } if (!swap) break; swap = false; for (i = end - 1; i >= begin; --i){ if (a[i] > a[i + 1]){ temp = a[i]; a[i]=a[i+1]; a[i+1]=temp; swap = true; } } ++begin; } } public static void main(String[] args) { int my_arr[] = {34, 78, 90, 32, 67, 12, 1, 0, 95}; Cocktail(my_arr, my_arr.length); System.out.println("The sorted array is "); for (int i = 0; i < my_arr.length; i++) System.out.print(my_arr[i]+" "); System.out.println(); } } The sorted array is 0 1 12 32 34 67 78 90 95 In the first step, the loop is run from left to right (similar to bubble sort) during which, the adjacent items are compared. If the left handed value is greater than the right handed value, the values are swapped. Once the first iteration is over, the largest element will be found at the end of the array. In the next step, the loop is run from right to left, by leaving the most recently sorted item. Here again, the adjacent elements are compared and the greater element is added to the end of the array.
[ { "code": null, "e": 1348, "s": 1062, "text": "Cocktail Sort works in contrast to bubble sort, wherein elements are iterated from left to right, and the largest element is first brought to its correct position and so on. In cocktail sort, elements are iterated over in both the directions (left and right) in an alternating fashion." }, { "code": null, "e": 1393, "s": 1348, "text": "Following is the program for Cocktail Sort −" }, { "code": null, "e": 1404, "s": 1393, "text": " Live Demo" }, { "code": null, "e": 2428, "s": 1404, "text": "public class Demo{\n static int temp;\n static void Cocktail(int a[], int n){\n boolean swap = true;\n int begin = 0,i;\n int end = n - 1;\n while (swap) {\n swap = false;\n for (i = begin; i < end; ++i){\n if (a[i] > a[i + 1]){\n temp = a[i];\n a[i]=a[i+1];\n a[i+1]=temp;\n swap = true;\n }\n }\n if (!swap)\n break;\n swap = false;\n for (i = end - 1; i >= begin; --i){\n if (a[i] > a[i + 1]){\n temp = a[i];\n a[i]=a[i+1];\n a[i+1]=temp;\n swap = true;\n }\n }\n ++begin;\n }\n }\n public static void main(String[] args) {\n int my_arr[] = {34, 78, 90, 32, 67, 12, 1, 0, 95};\n Cocktail(my_arr, my_arr.length);\n System.out.println(\"The sorted array is \");\n for (int i = 0; i < my_arr.length; i++)\n System.out.print(my_arr[i]+\" \");\n System.out.println();\n }\n}" }, { "code": null, "e": 2473, "s": 2428, "text": "The sorted array is\n0 1 12 32 34 67 78 90 95" }, { "code": null, "e": 2982, "s": 2473, "text": "In the first step, the loop is run from left to right (similar to bubble sort) during which, the adjacent items are compared. If the left handed value is greater than the right handed value, the values are swapped. Once the first iteration is over, the largest element will be found at the end of the array. In the next step, the loop is run from right to left, by leaving the most recently sorted item. Here again, the adjacent elements are compared and the greater element is added to the end of the array." } ]
MFC - Bitmap Button
A bitmap button displays a picture or a picture and text on its face. This is usually intended to make the button a little explicit. A bitmap button is created using the CBitmapButton class, which is derived from CButton. Here is the list of methods in CBitmapButton class. AutoLoad Associates a button in a dialog box with an object of the CBitmapButton class, loads the bitmap(s) by name, and sizes the button to fit the bitmap. LoadBitmaps Initializes the object by loading one or more named bitmap resources from the application's resource file and attaching the bitmaps to the object. SizeToContent It resizes the button to the size of the bitmaps. Here is the list of messages mapping for Bitmap Button control − Let us look into a simple example by creating a new project. Step 1 − Add a Bitmap from Add Resource dialog box. Step 2 − Select Bitmap and click New. Step 3 − Design your bitmap and change its ID to IDB_BITMAP_START as shown above. Step 4 − Add a button to your dialog box and also add a control Variable m_buttonStart for that button. Step 5 − Add a bitmap variable in your header file. You can now see the following two variables. CBitmap m_bitmapStart; CButton m_buttonStart; Step 6 − Modify your OnInitDialog() method as shown in the following code. m_bitmapStart.LoadBitmap(IDB_BITMAP_START); HBITMAP hBitmap = (HBITMAP)m_bitmapStart.GetSafeHandle(); m_buttonStart.SetBitmap(hBitmap); Step 7 − When the above code is compiled and executed, you will see the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2289, "s": 2067, "text": "A bitmap button displays a picture or a picture and text on its face. This is usually intended to make the button a little explicit. A bitmap button is created using the CBitmapButton class, which is derived from CButton." }, { "code": null, "e": 2341, "s": 2289, "text": "Here is the list of methods in CBitmapButton class." }, { "code": null, "e": 2350, "s": 2341, "text": "AutoLoad" }, { "code": null, "e": 2498, "s": 2350, "text": "Associates a button in a dialog box with an object of the CBitmapButton class, loads the bitmap(s) by name, and sizes the button to fit the bitmap." }, { "code": null, "e": 2510, "s": 2498, "text": "LoadBitmaps" }, { "code": null, "e": 2657, "s": 2510, "text": "Initializes the object by loading one or more named bitmap resources from the application's resource file and attaching the bitmaps to the object." }, { "code": null, "e": 2671, "s": 2657, "text": "SizeToContent" }, { "code": null, "e": 2721, "s": 2671, "text": "It resizes the button to the size of the bitmaps." }, { "code": null, "e": 2786, "s": 2721, "text": "Here is the list of messages mapping for Bitmap Button control −" }, { "code": null, "e": 2847, "s": 2786, "text": "Let us look into a simple example by creating a new project." }, { "code": null, "e": 2899, "s": 2847, "text": "Step 1 − Add a Bitmap from Add Resource dialog box." }, { "code": null, "e": 2937, "s": 2899, "text": "Step 2 − Select Bitmap and click New." }, { "code": null, "e": 3019, "s": 2937, "text": "Step 3 − Design your bitmap and change its ID to IDB_BITMAP_START as shown above." }, { "code": null, "e": 3123, "s": 3019, "text": "Step 4 − Add a button to your dialog box and also add a control Variable m_buttonStart for that button." }, { "code": null, "e": 3220, "s": 3123, "text": "Step 5 − Add a bitmap variable in your header file. You can now see the following two variables." }, { "code": null, "e": 3267, "s": 3220, "text": "CBitmap m_bitmapStart;\nCButton m_buttonStart;\n" }, { "code": null, "e": 3342, "s": 3267, "text": "Step 6 − Modify your OnInitDialog() method as shown in the following code." }, { "code": null, "e": 3478, "s": 3342, "text": "m_bitmapStart.LoadBitmap(IDB_BITMAP_START);\nHBITMAP hBitmap = (HBITMAP)m_bitmapStart.GetSafeHandle();\nm_buttonStart.SetBitmap(hBitmap);" }, { "code": null, "e": 3568, "s": 3478, "text": "Step 7 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 3575, "s": 3568, "text": " Print" }, { "code": null, "e": 3586, "s": 3575, "text": " Add Notes" } ]
How to build and use custom python packages for data science project | by Priya Brata Sen | Towards Data Science
In data science projects, we use similar steps depending on the nature of the problem. Usually, a data science project consists of problem identification, data collection and preparation, feature engineering, training and testing model, and deployment. In these steps, several functions are used. A data scientist needs to use those functions over and over again in different projects. For example, a data scientist imports different models to train and then fits the model with training data and then predicts based on the fitted model. To evaluate the model, he/she needs to use some form of evaluation metrics also such as Mean Absolute Percentage Error(MAPE). Therefore, if the codes used repeatedly can be saved somewhere and reused all the time, it will save a lot of time and make the code much cleaner than last time. This is where building custom packages can help a data scientist create reusable codes. Package and Module: Package in python is a collection of modules. On the other hand, The python module is a file that consists of python statements and definitions. Python has its own packages which we import and use all the time in our code. Similarly, we can create our own modules and save them as a package so that we can use them over and over again by importing them into our code. This can help to manage codes better and to increase the reusability of the codes. This post will show how we can create a custom package that consists of one module and use it in our regression problem. Building our custom package: In this problem, we will use xgboost and random forest regression models to train the model for demonstration purposes. We will then evaluate the model accuracy using mean absolute percentage error (MAPE). Finally, we will try to optimize the accuracy using grid search for both the model. Therefore, we will create all those functions to train and evaluate models as well as to optimize the hyper-parameters of the models. We will put all those functions in a python file which will be our module and then we will create a package by inserting that module. We can keep adding modules in that package going forward. Below are the functions that we will add to our module/ python file. import xgboost as xgbfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_percentage_error#functions to train random forest regression modeldef model_rf(x_train,y_train): #Function fits the random forest regression model = RandomForestRegressor(random_state=0) return model.fit(x_train,y_train)#functions to train xgboost regression modeldef model_xgb(x_train,y_train): #Function fits the xgboost regressor model=xgb.XGBRegressor(objective ='reg:squarederror') return model.fit(x_train,y_train)#functions to calculate MAPE valuedef result(model,x_test,y_true): #Funtion takes a fitted model and predicts based on x_test values and calculates the MAPE y_pred=model.predict(x_test) mape=mean_absolute_percentage_error(y_true, y_pred)*100 return mape#functions to do grid search to optimize model hyper-parameters def optimization(model,params,cv,x_train,y_train): # setup the grid search grid_search = GridSearchCV(model, param_grid=params, cv=cv, verbose=1, n_jobs=1, return_train_score=True) return grid_search.fit(x_train, y_train) From the above code, we can see that we imported all the necessary libraries and then created 4 functions. The model_rf function creates a random forest regression object and then fits the training data. model_xgb function creates a xgboost regression object and then fits training data. The result function takes a fitted model, x_test, and y_true value. It predicts the y values using x_test and then calculates the MAPE comparing y_true and prediction value. Let’s save the file with the name module.py and put it in a folder named my_module. We can use any name we want. Let’s now create a blank python file and name it as __init__.py. So, this is very important. Python will read a folder as a package when it has an ‘__init__.py’ file in it. So, we create the file and save it in the same folder my_module. This is all we need. Now, we want to put the folder in our python directory so that every time we need it, we can import it as a built-in python package. So, we need to go to our directory and put our my_module folder in the site-packages folder. I am using anaconda3. So, I will go to that folder and then find my site packages for anaconda distribution inside the lib folder as shown below. After that, I just pasted my my_module folder inside the site-packages folder. As soon as, I dropped that I can now import the my_module as a package inside my IDE. After that, I can use all those functions in the module created inside the my_module package. In the above picture, we can see that I have imported a module from the my_module package inside my Jupiter notebook. After that, I called the help function to see what we have inside the module. We can see that it is showing all the four function that is saved inside module file. It also shows the path where we have that module on our computer. Now, we can use these functions in our problem again and again instead of writing exclusively or copy-pasting. We can create more functions for further usage inside our module file or we can create different module files inside our my_module package. Let’s use our custom package to solve a machine learning problem Problem: Zoo management is trying to understand the number of llamas that will be available in different habitats. The projection will help them to plan for the foods so that they can feed the llamas properly. We have 20 months of historical data on the number of llamas in different habitats and also some weather features. The data files can be found in the following link github.com Data Preprocessing: In this step, we just import the data and do some preprocessing to prepare the data for our machine learning model. #Importing some packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt import seaborn as sns import datetime as dtfrom my_module import module# Importing the two files and merging them togetherdf1=pd.read_csv('llama_forecast_train.csv')df2=pd.read_csv('historical_weather.csv')df2.rename(columns={'HOUR':'DAY'},inplace='True')df1=pd.merge(df1,df2,on=['DAY'], how= "left")#Breaking the date time variablesdf1['Date']=pd.to_datetime(df1['DAY'])df1.sort_values(by='Date',ascending=True,inplace=True)df1['Year']=df1['Date'].dt.yeardf1['Month']=df1['Date'].dt.monthdf1['Week']=df1['Date'].dt.weekdf1['Day']=df1['Date'].dt.daydf1['Week Day']=df1['Date'].dt.dayofweekdf1['Year Day']=df1['Date'].dt.dayofyeardf1.drop(['Date','DAY'],axis=1,inplace=True)#Creating dummies for the habitat names becasue it is a qualitative variabledf3=pd.concat([df1, pd.get_dummies(df1[['HABITAT NAME']])], axis=1).drop(['HABITAT NAME'],axis=1)df3=df3.reset_index(drop=True)df3.head() Model Building: Now, we split the data into train and test. In the second section, we fitted both the random forest and xgboost regression models with our training data. We can see here that we called model_rf and model_xgb functions from our module which we imported from our my_module custom package. There is no need to create the regression object and then fit them with training data. The imported function will do this job # Splitting data in tarin test splity=df3['AVAILABLE LLAMAS']x=df3.drop(['AVAILABLE LLAMAS'],axis=1)b=int(len(df1)*.75)x_train, x_test=x.iloc[0:b, :], x.iloc[b:-1, :]y_train, y_test=y.iloc[0:b], y.iloc[b:-1]# train both random forest and xgboost modelrf=module.model_rf(x_train,y_train)xgboost=module.model_xgb(x_train,y_train) Model Evaluation: Let’s calculate the MAPE for both the random forest and the xgboost model using the result function from our custom package. We just pass the model and the test values for both x and y print('MAPE for random forest:',module.result(rf, x_test, y_test))print('MAPE for xgboost:',module.result(xgboost, x_test, y_test)) We can see the MAPE for the random forest is 20.01% and xgboost is 20.07%. Let’s use grid search to improve the results. Hyper-parameter Optimization: In this section, we will use the optimization function from our module to tune hyperparameters for both models. #Splitting data for hyperparameter tuningtss=TimeSeriesSplit(n_splits=3)# define the grid for the xgboostparams_xgb = { "learning_rate": [0.01, 0.1], "max_depth": [2, 4, 6], "n_estimators": [10, 100,150], "subsample": [0.8, 1], "min_child_weight": [1, 3], "reg_lambda": [1, 3], "reg_alpha": [1, 3]}# define the grid random forestparams_rf = { "n_estimators": [50, 100, 150], "max_features": [0.33, 0.66, 1.0], "min_samples_split": [2, 8, 14], "min_samples_leaf": [1, 5, 10], "bootstrap": [True, False]}# fit the new models with the optimized hyper-parametersgrid_xgb=module.optimization(xgboost, params_xgb, tss, x_train, y_train)grid_rf=module.optimization(rf, params_rf, tss, x_train, y_train) In the above block, we first created two-parameter grids. These will be passed in the param_grid parameter of our grid search function. Finally, we call our optimization function which mainly calculates the best values for the hyperparameters of the models and fits the refined models. Again, we are able to avoid writing long code for the hyperparameter tuning functions. We just used the function from our module. Below are the results of the tuned model print('MAPE for the tuned xgboost model:',module.result(grid_xgb, x_test, y_test))print('MAPE for the tuned random forest model:',module.result(grid_rf, x_test, y_test)) Conclusion: From the above example, we can see that how easily we can create our own python data science packages and use them in our projects repeatedly. This process will also help to keep your code clean and save a lot of time. It is very important to place the custom package inside the site package of the python directory so that we can use our custom package just like the built-in packages in python.
[ { "code": null, "e": 961, "s": 47, "text": "In data science projects, we use similar steps depending on the nature of the problem. Usually, a data science project consists of problem identification, data collection and preparation, feature engineering, training and testing model, and deployment. In these steps, several functions are used. A data scientist needs to use those functions over and over again in different projects. For example, a data scientist imports different models to train and then fits the model with training data and then predicts based on the fitted model. To evaluate the model, he/she needs to use some form of evaluation metrics also such as Mean Absolute Percentage Error(MAPE). Therefore, if the codes used repeatedly can be saved somewhere and reused all the time, it will save a lot of time and make the code much cleaner than last time. This is where building custom packages can help a data scientist create reusable codes." }, { "code": null, "e": 981, "s": 961, "text": "Package and Module:" }, { "code": null, "e": 1553, "s": 981, "text": "Package in python is a collection of modules. On the other hand, The python module is a file that consists of python statements and definitions. Python has its own packages which we import and use all the time in our code. Similarly, we can create our own modules and save them as a package so that we can use them over and over again by importing them into our code. This can help to manage codes better and to increase the reusability of the codes. This post will show how we can create a custom package that consists of one module and use it in our regression problem." }, { "code": null, "e": 1582, "s": 1553, "text": "Building our custom package:" }, { "code": null, "e": 2267, "s": 1582, "text": "In this problem, we will use xgboost and random forest regression models to train the model for demonstration purposes. We will then evaluate the model accuracy using mean absolute percentage error (MAPE). Finally, we will try to optimize the accuracy using grid search for both the model. Therefore, we will create all those functions to train and evaluate models as well as to optimize the hyper-parameters of the models. We will put all those functions in a python file which will be our module and then we will create a package by inserting that module. We can keep adding modules in that package going forward. Below are the functions that we will add to our module/ python file." }, { "code": null, "e": 3499, "s": 2267, "text": "import xgboost as xgbfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_percentage_error#functions to train random forest regression modeldef model_rf(x_train,y_train): #Function fits the random forest regression model = RandomForestRegressor(random_state=0) return model.fit(x_train,y_train)#functions to train xgboost regression modeldef model_xgb(x_train,y_train): #Function fits the xgboost regressor model=xgb.XGBRegressor(objective ='reg:squarederror') return model.fit(x_train,y_train)#functions to calculate MAPE valuedef result(model,x_test,y_true): #Funtion takes a fitted model and predicts based on x_test values and calculates the MAPE y_pred=model.predict(x_test) mape=mean_absolute_percentage_error(y_true, y_pred)*100 return mape#functions to do grid search to optimize model hyper-parameters def optimization(model,params,cv,x_train,y_train): # setup the grid search grid_search = GridSearchCV(model, param_grid=params, cv=cv, verbose=1, n_jobs=1, return_train_score=True) return grid_search.fit(x_train, y_train)" }, { "code": null, "e": 3961, "s": 3499, "text": "From the above code, we can see that we imported all the necessary libraries and then created 4 functions. The model_rf function creates a random forest regression object and then fits the training data. model_xgb function creates a xgboost regression object and then fits training data. The result function takes a fitted model, x_test, and y_true value. It predicts the y values using x_test and then calculates the MAPE comparing y_true and prediction value." }, { "code": null, "e": 4074, "s": 3961, "text": "Let’s save the file with the name module.py and put it in a folder named my_module. We can use any name we want." }, { "code": null, "e": 4312, "s": 4074, "text": "Let’s now create a blank python file and name it as __init__.py. So, this is very important. Python will read a folder as a package when it has an ‘__init__.py’ file in it. So, we create the file and save it in the same folder my_module." }, { "code": null, "e": 4705, "s": 4312, "text": "This is all we need. Now, we want to put the folder in our python directory so that every time we need it, we can import it as a built-in python package. So, we need to go to our directory and put our my_module folder in the site-packages folder. I am using anaconda3. So, I will go to that folder and then find my site packages for anaconda distribution inside the lib folder as shown below." }, { "code": null, "e": 4964, "s": 4705, "text": "After that, I just pasted my my_module folder inside the site-packages folder. As soon as, I dropped that I can now import the my_module as a package inside my IDE. After that, I can use all those functions in the module created inside the my_module package." }, { "code": null, "e": 5628, "s": 4964, "text": "In the above picture, we can see that I have imported a module from the my_module package inside my Jupiter notebook. After that, I called the help function to see what we have inside the module. We can see that it is showing all the four function that is saved inside module file. It also shows the path where we have that module on our computer. Now, we can use these functions in our problem again and again instead of writing exclusively or copy-pasting. We can create more functions for further usage inside our module file or we can create different module files inside our my_module package. Let’s use our custom package to solve a machine learning problem" }, { "code": null, "e": 5637, "s": 5628, "text": "Problem:" }, { "code": null, "e": 6003, "s": 5637, "text": "Zoo management is trying to understand the number of llamas that will be available in different habitats. The projection will help them to plan for the foods so that they can feed the llamas properly. We have 20 months of historical data on the number of llamas in different habitats and also some weather features. The data files can be found in the following link" }, { "code": null, "e": 6014, "s": 6003, "text": "github.com" }, { "code": null, "e": 6034, "s": 6014, "text": "Data Preprocessing:" }, { "code": null, "e": 6150, "s": 6034, "text": "In this step, we just import the data and do some preprocessing to prepare the data for our machine learning model." }, { "code": null, "e": 7130, "s": 6150, "text": "#Importing some packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt import seaborn as sns import datetime as dtfrom my_module import module# Importing the two files and merging them togetherdf1=pd.read_csv('llama_forecast_train.csv')df2=pd.read_csv('historical_weather.csv')df2.rename(columns={'HOUR':'DAY'},inplace='True')df1=pd.merge(df1,df2,on=['DAY'], how= \"left\")#Breaking the date time variablesdf1['Date']=pd.to_datetime(df1['DAY'])df1.sort_values(by='Date',ascending=True,inplace=True)df1['Year']=df1['Date'].dt.yeardf1['Month']=df1['Date'].dt.monthdf1['Week']=df1['Date'].dt.weekdf1['Day']=df1['Date'].dt.daydf1['Week Day']=df1['Date'].dt.dayofweekdf1['Year Day']=df1['Date'].dt.dayofyeardf1.drop(['Date','DAY'],axis=1,inplace=True)#Creating dummies for the habitat names becasue it is a qualitative variabledf3=pd.concat([df1, pd.get_dummies(df1[['HABITAT NAME']])], axis=1).drop(['HABITAT NAME'],axis=1)df3=df3.reset_index(drop=True)df3.head()" }, { "code": null, "e": 7146, "s": 7130, "text": "Model Building:" }, { "code": null, "e": 7559, "s": 7146, "text": "Now, we split the data into train and test. In the second section, we fitted both the random forest and xgboost regression models with our training data. We can see here that we called model_rf and model_xgb functions from our module which we imported from our my_module custom package. There is no need to create the regression object and then fit them with training data. The imported function will do this job" }, { "code": null, "e": 7887, "s": 7559, "text": "# Splitting data in tarin test splity=df3['AVAILABLE LLAMAS']x=df3.drop(['AVAILABLE LLAMAS'],axis=1)b=int(len(df1)*.75)x_train, x_test=x.iloc[0:b, :], x.iloc[b:-1, :]y_train, y_test=y.iloc[0:b], y.iloc[b:-1]# train both random forest and xgboost modelrf=module.model_rf(x_train,y_train)xgboost=module.model_xgb(x_train,y_train)" }, { "code": null, "e": 7905, "s": 7887, "text": "Model Evaluation:" }, { "code": null, "e": 8090, "s": 7905, "text": "Let’s calculate the MAPE for both the random forest and the xgboost model using the result function from our custom package. We just pass the model and the test values for both x and y" }, { "code": null, "e": 8222, "s": 8090, "text": "print('MAPE for random forest:',module.result(rf, x_test, y_test))print('MAPE for xgboost:',module.result(xgboost, x_test, y_test))" }, { "code": null, "e": 8343, "s": 8222, "text": "We can see the MAPE for the random forest is 20.01% and xgboost is 20.07%. Let’s use grid search to improve the results." }, { "code": null, "e": 8373, "s": 8343, "text": "Hyper-parameter Optimization:" }, { "code": null, "e": 8485, "s": 8373, "text": "In this section, we will use the optimization function from our module to tune hyperparameters for both models." }, { "code": null, "e": 9217, "s": 8485, "text": "#Splitting data for hyperparameter tuningtss=TimeSeriesSplit(n_splits=3)# define the grid for the xgboostparams_xgb = { \"learning_rate\": [0.01, 0.1], \"max_depth\": [2, 4, 6], \"n_estimators\": [10, 100,150], \"subsample\": [0.8, 1], \"min_child_weight\": [1, 3], \"reg_lambda\": [1, 3], \"reg_alpha\": [1, 3]}# define the grid random forestparams_rf = { \"n_estimators\": [50, 100, 150], \"max_features\": [0.33, 0.66, 1.0], \"min_samples_split\": [2, 8, 14], \"min_samples_leaf\": [1, 5, 10], \"bootstrap\": [True, False]}# fit the new models with the optimized hyper-parametersgrid_xgb=module.optimization(xgboost, params_xgb, tss, x_train, y_train)grid_rf=module.optimization(rf, params_rf, tss, x_train, y_train)" }, { "code": null, "e": 9674, "s": 9217, "text": "In the above block, we first created two-parameter grids. These will be passed in the param_grid parameter of our grid search function. Finally, we call our optimization function which mainly calculates the best values for the hyperparameters of the models and fits the refined models. Again, we are able to avoid writing long code for the hyperparameter tuning functions. We just used the function from our module. Below are the results of the tuned model" }, { "code": null, "e": 9844, "s": 9674, "text": "print('MAPE for the tuned xgboost model:',module.result(grid_xgb, x_test, y_test))print('MAPE for the tuned random forest model:',module.result(grid_rf, x_test, y_test))" }, { "code": null, "e": 9856, "s": 9844, "text": "Conclusion:" } ]
Change the position of cursor in Tkinter's Entry widget - GeeksforGeeks
05 Apr, 2021 A widget in tkinter, which is used to enter a display a single line of text is called an entry widget. Have you created an entry widget in tkinter which contains a lot of information? Is a lot of text causing an issue to you to move at any other position in it? Don’t worry, we have a solution to this problem. What you need to do is to just set a button which when clicked will take you to the desired location in the entry widget. Step 1: First, import the library tkinter. from tkinter import * Step 2: Now, create a GUI app using tkinter. app = Tk() Step 3: Then, create a function with an argument as None to move the cursor wherever you want in the entry widget. def shift_cursor(event=None): position = entry_label.index(INSERT) entry_label.icursor(#Specify the position \ where you want to move the cursor) Step 4: Next, create and display an entry widget in which you want to change the position. entry_label=Entry(app) entry_label.grid(column=#Specify the column value, row=#Specify the row value, padx=#Specify the padding value of x, pady=#Specify the padding value of y) Step 5: Once an entry widget is declared, set the focus to the entry widget specified. entry_label.focus() Step 6: Further, create and display a button which when clicked will change the position of the cursor in the entry widget. button1 = Button(app, text="#Text you want to display in button", command=shift_cursor) button1.grid(column=#Specify the column value, row=#Specify the row value, padx=#Specify the padding value of x, pady=#Specify the padding value of y) Step 7: Finally, make an infinite loop for displaying the app on the screen. app.mainloop() Example: In this program, we will change the position of the cursor one character left by clicking on the button ‘Shift cursor left‘ while changing the position of the cursor one character right by clicking on the button ‘Shift cursor right.’ Python # Python program to change position# of cursor in Entry widget # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Create a function to move cursor one character# leftdef shift_cursor1(event=None): position = entry_label.index(INSERT) # Changing position of cursor one character left entry_label.icursor(position - 1) # Create a function to move the cursor one character# rightdef shift_cursor2(event=None): position = entry_label.index(INSERT) # Changing position of cursor one character right entry_label.icursor(position + 1) # Create and display the button to shift cursor leftbutton1 = Button(app, text="Shift cursor left", command=shift_cursor1)button1.grid(row=1, column=1, padx=10, pady=10) # Create and display the button to shift the cursor rightbutton2 = Button(app, text="Shift cursor right", command=shift_cursor2)button2.grid(row=1, column=0, padx=10, pady=10) # Create and display the textboxentry_label = Entry(app)entry_label.grid(row=0, column=0, padx=10, pady=10) # Set the focus in the textboxentry_label.focus() # Make the infinite loop for displaying the appapp.mainloop() Output: Picked Python-tkinter 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": 24316, "s": 24288, "text": "\n05 Apr, 2021" }, { "code": null, "e": 24749, "s": 24316, "text": "A widget in tkinter, which is used to enter a display a single line of text is called an entry widget. Have you created an entry widget in tkinter which contains a lot of information? Is a lot of text causing an issue to you to move at any other position in it? Don’t worry, we have a solution to this problem. What you need to do is to just set a button which when clicked will take you to the desired location in the entry widget." }, { "code": null, "e": 24792, "s": 24749, "text": "Step 1: First, import the library tkinter." }, { "code": null, "e": 24814, "s": 24792, "text": "from tkinter import *" }, { "code": null, "e": 24859, "s": 24814, "text": "Step 2: Now, create a GUI app using tkinter." }, { "code": null, "e": 24870, "s": 24859, "text": "app = Tk()" }, { "code": null, "e": 24985, "s": 24870, "text": "Step 3: Then, create a function with an argument as None to move the cursor wherever you want in the entry widget." }, { "code": null, "e": 25140, "s": 24985, "text": "def shift_cursor(event=None):\n position = entry_label.index(INSERT)\n entry_label.icursor(#Specify the position \\\n where you want to move the cursor)" }, { "code": null, "e": 25231, "s": 25140, "text": "Step 4: Next, create and display an entry widget in which you want to change the position." }, { "code": null, "e": 25463, "s": 25231, "text": "entry_label=Entry(app)\nentry_label.grid(column=#Specify the column value, \n row=#Specify the row value, \n padx=#Specify the padding value of x, \n pady=#Specify the padding value of y)" }, { "code": null, "e": 25550, "s": 25463, "text": "Step 5: Once an entry widget is declared, set the focus to the entry widget specified." }, { "code": null, "e": 25570, "s": 25550, "text": "entry_label.focus()" }, { "code": null, "e": 25694, "s": 25570, "text": "Step 6: Further, create and display a button which when clicked will change the position of the cursor in the entry widget." }, { "code": null, "e": 26029, "s": 25694, "text": "button1 = Button(app, \n text=\"#Text you want to display in button\", \n command=shift_cursor)\n \nbutton1.grid(column=#Specify the column value, \n row=#Specify the row value, \n padx=#Specify the padding value of x, \n pady=#Specify the padding value of y)" }, { "code": null, "e": 26106, "s": 26029, "text": "Step 7: Finally, make an infinite loop for displaying the app on the screen." }, { "code": null, "e": 26121, "s": 26106, "text": "app.mainloop()" }, { "code": null, "e": 26130, "s": 26121, "text": "Example:" }, { "code": null, "e": 26365, "s": 26130, "text": "In this program, we will change the position of the cursor one character left by clicking on the button ‘Shift cursor left‘ while changing the position of the cursor one character right by clicking on the button ‘Shift cursor right.’ " }, { "code": null, "e": 26372, "s": 26365, "text": "Python" }, { "code": "# Python program to change position# of cursor in Entry widget # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Create a function to move cursor one character# leftdef shift_cursor1(event=None): position = entry_label.index(INSERT) # Changing position of cursor one character left entry_label.icursor(position - 1) # Create a function to move the cursor one character# rightdef shift_cursor2(event=None): position = entry_label.index(INSERT) # Changing position of cursor one character right entry_label.icursor(position + 1) # Create and display the button to shift cursor leftbutton1 = Button(app, text=\"Shift cursor left\", command=shift_cursor1)button1.grid(row=1, column=1, padx=10, pady=10) # Create and display the button to shift the cursor rightbutton2 = Button(app, text=\"Shift cursor right\", command=shift_cursor2)button2.grid(row=1, column=0, padx=10, pady=10) # Create and display the textboxentry_label = Entry(app)entry_label.grid(row=0, column=0, padx=10, pady=10) # Set the focus in the textboxentry_label.focus() # Make the infinite loop for displaying the appapp.mainloop()", "e": 27529, "s": 26372, "text": null }, { "code": null, "e": 27537, "s": 27529, "text": "Output:" }, { "code": null, "e": 27544, "s": 27537, "text": "Picked" }, { "code": null, "e": 27559, "s": 27544, "text": "Python-tkinter" }, { "code": null, "e": 27566, "s": 27559, "text": "Python" }, { "code": null, "e": 27664, "s": 27566, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27673, "s": 27664, "text": "Comments" }, { "code": null, "e": 27686, "s": 27673, "text": "Old Comments" }, { "code": null, "e": 27718, "s": 27686, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27774, "s": 27718, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27829, "s": 27774, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27871, "s": 27829, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27913, "s": 27871, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27944, "s": 27913, "text": "Python | os.path.join() method" }, { "code": null, "e": 27983, "s": 27944, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28012, "s": 27983, "text": "Create a directory in Python" }, { "code": null, "e": 28034, "s": 28012, "text": "Defaultdict in Python" } ]
Convert an Integer to UTF8 in R Programming - intToUtf8() Function - GeeksforGeeks
16 Jun, 2020 intToUtf8() function in R Language is used to convert an integer into UTF8 value. Syntax: intToUtf8(x, multiple) Parameters:x: Integer or integer vectormultiple: Boolean value to convert into single or multiple strings Example 1: # R program to convert an integer to UTF8 # Calling the intToUtf8() functionintToUtf8(4)intToUtf8(10)intToUtf8(58) Output: [1] "\004" [1] "\n" [1] ":" Example 2: # R program to convert an integer to UTF8 # Creating a vectorx <- c(49, 100, 111) # Calling the intToUtf8() functionintToUtf8(x)intToUtf8(x, multiple = TRUE) Output: [1] "1do" [1] "1" "d" "o" R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Remove rows with NA in one column of R DataFrame Group by function in R using Dplyr K-Means Clustering in R Programming How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 24476, "s": 24448, "text": "\n16 Jun, 2020" }, { "code": null, "e": 24558, "s": 24476, "text": "intToUtf8() function in R Language is used to convert an integer into UTF8 value." }, { "code": null, "e": 24589, "s": 24558, "text": "Syntax: intToUtf8(x, multiple)" }, { "code": null, "e": 24695, "s": 24589, "text": "Parameters:x: Integer or integer vectormultiple: Boolean value to convert into single or multiple strings" }, { "code": null, "e": 24706, "s": 24695, "text": "Example 1:" }, { "code": "# R program to convert an integer to UTF8 # Calling the intToUtf8() functionintToUtf8(4)intToUtf8(10)intToUtf8(58)", "e": 24822, "s": 24706, "text": null }, { "code": null, "e": 24830, "s": 24822, "text": "Output:" }, { "code": null, "e": 24859, "s": 24830, "text": "[1] \"\\004\"\n[1] \"\\n\"\n[1] \":\"\n" }, { "code": null, "e": 24870, "s": 24859, "text": "Example 2:" }, { "code": "# R program to convert an integer to UTF8 # Creating a vectorx <- c(49, 100, 111) # Calling the intToUtf8() functionintToUtf8(x)intToUtf8(x, multiple = TRUE)", "e": 25030, "s": 24870, "text": null }, { "code": null, "e": 25038, "s": 25030, "text": "Output:" }, { "code": null, "e": 25065, "s": 25038, "text": "[1] \"1do\"\n[1] \"1\" \"d\" \"o\"\n" }, { "code": null, "e": 25081, "s": 25065, "text": "R Math-Function" }, { "code": null, "e": 25092, "s": 25081, "text": "R Language" }, { "code": null, "e": 25190, "s": 25092, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25248, "s": 25190, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 25300, "s": 25248, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 25332, "s": 25300, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 25384, "s": 25332, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25428, "s": 25384, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 25466, "s": 25428, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25515, "s": 25466, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 25550, "s": 25515, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25586, "s": 25550, "text": "K-Means Clustering in R Programming" } ]
CSS | Ordering Flex Items - GeeksforGeeks
18 Nov, 2019 The order property of CSS can be used for ordering flex items. It specifies the order of a flex item with respect to the other flex items. The element has to be a flexible item for the order property to work. The elements are displayed in ascending order of their order values. If two elements have the same order value then they are displayed on the basis of their occurrence in the source code. Syntax: order: integer | initial | inherit Property Values: Integer: It denotes the order of the flex items. The default value of a flex item is 0. Initial: It sets the property to its default value. Inherit: It means that the associated element takes the specified value of its parent element order property. Example 1: <!DOCTYPE><html> <head> <title> CSS | Ordering Flex Items </title> <style> #GFG { width: 400px; height: 100px; border: 1px solid #d3d3d3; display: -webkit-flex; /* Safari */ display: flex; } #GFG div { width: 70px; height: 70px; } /* Safari 6.1+ */ div#second {-webkit-order: 2;} div#fourth {-webkit-order: 4;} div#third {-webkit-order: 3;} div#first {-webkit-order: 1;} /* Normal syntax */ div#second {order: 2;} div#fourth {order: 4;} div#third {order: 3;} div#first {order: 1;} </style></head> <body> <div id="GFG"> <div style="background-color:yellow;" id="second"></div> <div style="background-color:blue;" id="fourth"></div> <div style="background-color:green;" id="third"></div> <div style="background-color:red;" id="first"></div> </div></body> </html> Output: Example 2: <!DOCTYPE><html> <head> <title> CSS | Ordering Flex Items </title> <style> #GFG { width: 400px; height: 100px; border: 1px solid #d3d3d3; display: -webkit-flex; /* Safari */ display: flex; } #GFG div { width: 70px; height: 70px; } /* Safari 6.1+ */ div#second {-webkit-order: 2;} div#fourth {-webkit-order: 4;} div#third {-webkit-order: 3;} div#first {-webkit-order: 1;} /* Normal syntax */ div#second {order: 2;} div#fourth {order: 4;} div#third {order: 3;} div#first {order: 1;} </style></head> <body> <div id="GFG"> <div style="background-color:green;" id="second"></div> <div style="background-color:pink;" id="fourth"></div> <div style="background-color:black;" id="third"></div> <div style="background-color:violet;" id="first"></div> </div></body> </html> Output: Supported Browsers: The browsers supported by Ordering Flex Items are listed below: Google Chrome 29.0, 21.0 -webkit- Mozilla Firefox 28.0, 18.0 -moz- Internet Explorer 11.0 Safari 9.0, 6.1 -webkit- Opera 17.0 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? 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 Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26004, "s": 25976, "text": "\n18 Nov, 2019" }, { "code": null, "e": 26401, "s": 26004, "text": "The order property of CSS can be used for ordering flex items. It specifies the order of a flex item with respect to the other flex items. The element has to be a flexible item for the order property to work. The elements are displayed in ascending order of their order values. If two elements have the same order value then they are displayed on the basis of their occurrence in the source code." }, { "code": null, "e": 26409, "s": 26401, "text": "Syntax:" }, { "code": null, "e": 26444, "s": 26409, "text": "order: integer | initial | inherit" }, { "code": null, "e": 26461, "s": 26444, "text": "Property Values:" }, { "code": null, "e": 26549, "s": 26461, "text": "Integer: It denotes the order of the flex items. The default value of a flex item is 0." }, { "code": null, "e": 26601, "s": 26549, "text": "Initial: It sets the property to its default value." }, { "code": null, "e": 26711, "s": 26601, "text": "Inherit: It means that the associated element takes the specified value of its parent element order property." }, { "code": null, "e": 26722, "s": 26711, "text": "Example 1:" }, { "code": "<!DOCTYPE><html> <head> <title> CSS | Ordering Flex Items </title> <style> #GFG { width: 400px; height: 100px; border: 1px solid #d3d3d3; display: -webkit-flex; /* Safari */ display: flex; } #GFG div { width: 70px; height: 70px; } /* Safari 6.1+ */ div#second {-webkit-order: 2;} div#fourth {-webkit-order: 4;} div#third {-webkit-order: 3;} div#first {-webkit-order: 1;} /* Normal syntax */ div#second {order: 2;} div#fourth {order: 4;} div#third {order: 3;} div#first {order: 1;} </style></head> <body> <div id=\"GFG\"> <div style=\"background-color:yellow;\" id=\"second\"></div> <div style=\"background-color:blue;\" id=\"fourth\"></div> <div style=\"background-color:green;\" id=\"third\"></div> <div style=\"background-color:red;\" id=\"first\"></div> </div></body> </html>", "e": 27732, "s": 26722, "text": null }, { "code": null, "e": 27740, "s": 27732, "text": "Output:" }, { "code": null, "e": 27751, "s": 27740, "text": "Example 2:" }, { "code": "<!DOCTYPE><html> <head> <title> CSS | Ordering Flex Items </title> <style> #GFG { width: 400px; height: 100px; border: 1px solid #d3d3d3; display: -webkit-flex; /* Safari */ display: flex; } #GFG div { width: 70px; height: 70px; } /* Safari 6.1+ */ div#second {-webkit-order: 2;} div#fourth {-webkit-order: 4;} div#third {-webkit-order: 3;} div#first {-webkit-order: 1;} /* Normal syntax */ div#second {order: 2;} div#fourth {order: 4;} div#third {order: 3;} div#first {order: 1;} </style></head> <body> <div id=\"GFG\"> <div style=\"background-color:green;\" id=\"second\"></div> <div style=\"background-color:pink;\" id=\"fourth\"></div> <div style=\"background-color:black;\" id=\"third\"></div> <div style=\"background-color:violet;\" id=\"first\"></div> </div></body> </html>", "e": 28767, "s": 27751, "text": null }, { "code": null, "e": 28775, "s": 28767, "text": "Output:" }, { "code": null, "e": 28859, "s": 28775, "text": "Supported Browsers: The browsers supported by Ordering Flex Items are listed below:" }, { "code": null, "e": 28893, "s": 28859, "text": "Google Chrome 29.0, 21.0 -webkit-" }, { "code": null, "e": 28926, "s": 28893, "text": "Mozilla Firefox 28.0, 18.0 -moz-" }, { "code": null, "e": 28949, "s": 28926, "text": "Internet Explorer 11.0" }, { "code": null, "e": 28974, "s": 28949, "text": "Safari 9.0, 6.1 -webkit-" }, { "code": null, "e": 28985, "s": 28974, "text": "Opera 17.0" }, { "code": null, "e": 29000, "s": 28985, "text": "CSS-Properties" }, { "code": null, "e": 29007, "s": 29000, "text": "Picked" }, { "code": null, "e": 29011, "s": 29007, "text": "CSS" }, { "code": null, "e": 29028, "s": 29011, "text": "Web Technologies" }, { "code": null, "e": 29126, "s": 29028, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29163, "s": 29126, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 29227, "s": 29163, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 29268, "s": 29227, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 29305, "s": 29268, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29366, "s": 29305, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 29408, "s": 29366, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29441, "s": 29408, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29484, "s": 29441, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29529, "s": 29484, "text": "Convert a string to an integer in JavaScript" } ]
A Beginner’s guide to XGBoost. This article will have trees.... lots of... | by George Seif | Towards Data Science
Want to be inspired? Come join my Super Quotes newsletter. 😎 XGBoost is an open source library providing a high-performance implementation of gradient boosted decision trees. An underlying C++ codebase combined with a Python interface sitting on top makes for an extremely powerful yet easy to implement package. The performance of XGBoost is no joke — it’s become the go-to library for winning many Kaggle competitions. Its gradient boosting implementation is second to none and there’s only more to come as the library continues to garner praise. In this post we’re going to go through the basics of the XGBoost library. We’ll start with a practical explanation of how gradient boosting actually works and then go through a Python example of how XGBoost makes it oh-so quick and easy to do it. With a regular machine learning model, like a decision tree, we’d simply train a single model on our dataset and use that for prediction. We might play around with the parameters for a bit or augment the data, but in the end we are still using a single model. Even if we build an ensemble, all of the models are trained and applied to our data separately. Boosting, on the other hand, takes a more iterative approach. It’s still technically an ensemble technique in that many models are combined together to perform the final one, but takes a more clever approach. Rather than training all of the models in isolation of one another, boosting trains models in succession, with each new model being trained to correct the errors made by the previous ones. Models are added sequentially until no further improvements can be made. The advantage of this iterative approach is that the new models being added are focused on correcting the mistakes which were caused by other models. In a standard ensemble method where models are trained in isolation, all of the models might simply end up making the same mistakes! Gradient Boosting specifically is an approach where new models are trained to predict the residuals (i.e errors) of prior models. I’ve outlined the approach in the diagram below. Let’s start using this beast of a library — XGBoost. The first thing we want to do is install the library which is most easily done via pip. It can also be safer to do this in a Python virtual environment. pip install xgboost For the rest of our tutorial we’re going to be using the iris flowers dataset. We can use Scikit Learn to get that loaded up in Python. At the same time, we’ll also import our newly installed XGBoost library. from sklearn import datasetsimport xgboost as xgbiris = datasets.load_iris()X = iris.datay = iris.target Let’s get all of our data set up. We’ll start off by creating a train-test split so we can see just how well XGBoost performs. We’ll go with an 80%-20% split this time. from sklearn.model_selection import train_test_splitX_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2) In order for XGBoost to be able to use our data, we’ll need to transform it into a specific format that XGBoost can handle. That format is called DMatrix. It’s a very simple one-linear to transform a numpy array of data to DMatrix format: D_train = xgb.DMatrix(X_train, label=Y_train)D_test = xgb.DMatrix(X_test, label=Y_test) Now that our data is all loaded up, we can define the parameters of our gradient boosting ensemble. We’ve set up some of the most important ones below to get us started. For more complicated tasks and models, the full list of possible parameters is available on the official XGBoost website. param = { 'eta': 0.3, 'max_depth': 3, 'objective': 'multi:softprob', 'num_class': 3} steps = 20 # The number of training iterations The simplest parameters are the max_depth (maximum depth of the decision trees being trained), objective (the loss function being used), and num_class (the number of classes in the dataset). The eta algorithm requires special attention. From our theory, Gradient Boosting involves creating and adding decision trees to an ensemble model sequentially. New trees are created to correct the residual errors in the predictions from the existing ensemble. Due to the nature of an ensemble, i.e having several models put together to form what is essentially a very large complicated one, makes this technique prone to overfitting. The eta parameter gives us a chance to prevent this overfitting The eta can be thought of more intuitively as a learning rate. Rather than simply adding the predictions of new trees to the ensemble with full weight, the eta will be multiplied by the residuals being adding to reduce their weight. This effectively reduces the complexity of the overall model. It is common to have small values in the range of 0.1 to 0.3. The smaller weighting of these residuals will still help us train a powerful model, but won’t let that model run away into deep complexity where overfitting is more likely to happen. We can finally train our model similar to how we do so with Scikit Learn: model = xgb.train(param, D_train, steps) Let’s now run an evaluation. Again the process is very similar to that of training models in Scikit Learn: import numpy as npfrom sklearn.metrics import precision_score, recall_score, accuracy_scorepreds = model.predict(D_test)best_preds = np.asarray([np.argmax(line) for line in preds])print("Precision = {}".format(precision_score(Y_test, best_preds, average='macro')))print("Recall = {}".format(recall_score(Y_test, best_preds, average='macro')))print("Accuracy = {}".format(accuracy_score(Y_test, best_preds))) Awesome! If you’ve followed all the steps up to this point, you should get at least 90% accuracy! That just about sums up the basics of XGBoost. But there are some more cool features that’ll help you get the most out of your models. The gamma parameter can also help with controlling overfitting. It specifies the minimum reduction in the loss required to make a further partition on a leaf node of the tree. I.e if creating a new node doesn’t reduce the loss by a certain amount, then we won’t create it at all. The booster parameter allows you to set the type of model you will use when building the ensemble. The default is gbtree which builds an ensemble of decision trees. If your data isn’t too complicated, you can go with the faster and simpler gblinear option which builds an ensemble of linear models. Setting the optimal hyperparameters of any ML model can be a challenge. So why not let Scikit Learn do it for you? We can combine Scikit Learn’s grid search with an XGBoost classifier quite easily: from sklearn.model_selection import GridSearchCVclf = xgb.XGBClassifier()parameters = { "eta" : [0.05, 0.10, 0.15, 0.20, 0.25, 0.30 ] , "max_depth" : [ 3, 4, 5, 6, 8, 10, 12, 15], "min_child_weight" : [ 1, 3, 5, 7 ], "gamma" : [ 0.0, 0.1, 0.2 , 0.3, 0.4 ], "colsample_bytree" : [ 0.3, 0.4, 0.5 , 0.7 ] }grid = GridSearchCV(clf, parameters, n_jobs=4, scoring="neg_log_loss", cv=3)grid.fit(X_train, Y_train) Only do that on a big dataset if you have time to kill — doing a grid search is essentially training an ensemble of decision trees many times over! Once your XGBoost model is trained, you can dump a human readable description of it into a text file: model.dump_model('dump.raw.txt') That’s a wrap! Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too!
[ { "code": null, "e": 233, "s": 172, "text": "Want to be inspired? Come join my Super Quotes newsletter. 😎" }, { "code": null, "e": 485, "s": 233, "text": "XGBoost is an open source library providing a high-performance implementation of gradient boosted decision trees. An underlying C++ codebase combined with a Python interface sitting on top makes for an extremely powerful yet easy to implement package." }, { "code": null, "e": 721, "s": 485, "text": "The performance of XGBoost is no joke — it’s become the go-to library for winning many Kaggle competitions. Its gradient boosting implementation is second to none and there’s only more to come as the library continues to garner praise." }, { "code": null, "e": 968, "s": 721, "text": "In this post we’re going to go through the basics of the XGBoost library. We’ll start with a practical explanation of how gradient boosting actually works and then go through a Python example of how XGBoost makes it oh-so quick and easy to do it." }, { "code": null, "e": 1324, "s": 968, "text": "With a regular machine learning model, like a decision tree, we’d simply train a single model on our dataset and use that for prediction. We might play around with the parameters for a bit or augment the data, but in the end we are still using a single model. Even if we build an ensemble, all of the models are trained and applied to our data separately." }, { "code": null, "e": 1533, "s": 1324, "text": "Boosting, on the other hand, takes a more iterative approach. It’s still technically an ensemble technique in that many models are combined together to perform the final one, but takes a more clever approach." }, { "code": null, "e": 1795, "s": 1533, "text": "Rather than training all of the models in isolation of one another, boosting trains models in succession, with each new model being trained to correct the errors made by the previous ones. Models are added sequentially until no further improvements can be made." }, { "code": null, "e": 2078, "s": 1795, "text": "The advantage of this iterative approach is that the new models being added are focused on correcting the mistakes which were caused by other models. In a standard ensemble method where models are trained in isolation, all of the models might simply end up making the same mistakes!" }, { "code": null, "e": 2257, "s": 2078, "text": "Gradient Boosting specifically is an approach where new models are trained to predict the residuals (i.e errors) of prior models. I’ve outlined the approach in the diagram below." }, { "code": null, "e": 2310, "s": 2257, "text": "Let’s start using this beast of a library — XGBoost." }, { "code": null, "e": 2463, "s": 2310, "text": "The first thing we want to do is install the library which is most easily done via pip. It can also be safer to do this in a Python virtual environment." }, { "code": null, "e": 2483, "s": 2463, "text": "pip install xgboost" }, { "code": null, "e": 2692, "s": 2483, "text": "For the rest of our tutorial we’re going to be using the iris flowers dataset. We can use Scikit Learn to get that loaded up in Python. At the same time, we’ll also import our newly installed XGBoost library." }, { "code": null, "e": 2797, "s": 2692, "text": "from sklearn import datasetsimport xgboost as xgbiris = datasets.load_iris()X = iris.datay = iris.target" }, { "code": null, "e": 2966, "s": 2797, "text": "Let’s get all of our data set up. We’ll start off by creating a train-test split so we can see just how well XGBoost performs. We’ll go with an 80%-20% split this time." }, { "code": null, "e": 3091, "s": 2966, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2)" }, { "code": null, "e": 3330, "s": 3091, "text": "In order for XGBoost to be able to use our data, we’ll need to transform it into a specific format that XGBoost can handle. That format is called DMatrix. It’s a very simple one-linear to transform a numpy array of data to DMatrix format:" }, { "code": null, "e": 3418, "s": 3330, "text": "D_train = xgb.DMatrix(X_train, label=Y_train)D_test = xgb.DMatrix(X_test, label=Y_test)" }, { "code": null, "e": 3710, "s": 3418, "text": "Now that our data is all loaded up, we can define the parameters of our gradient boosting ensemble. We’ve set up some of the most important ones below to get us started. For more complicated tasks and models, the full list of possible parameters is available on the official XGBoost website." }, { "code": null, "e": 3860, "s": 3710, "text": "param = { 'eta': 0.3, 'max_depth': 3, 'objective': 'multi:softprob', 'num_class': 3} steps = 20 # The number of training iterations" }, { "code": null, "e": 4097, "s": 3860, "text": "The simplest parameters are the max_depth (maximum depth of the decision trees being trained), objective (the loss function being used), and num_class (the number of classes in the dataset). The eta algorithm requires special attention." }, { "code": null, "e": 4311, "s": 4097, "text": "From our theory, Gradient Boosting involves creating and adding decision trees to an ensemble model sequentially. New trees are created to correct the residual errors in the predictions from the existing ensemble." }, { "code": null, "e": 4549, "s": 4311, "text": "Due to the nature of an ensemble, i.e having several models put together to form what is essentially a very large complicated one, makes this technique prone to overfitting. The eta parameter gives us a chance to prevent this overfitting" }, { "code": null, "e": 4844, "s": 4549, "text": "The eta can be thought of more intuitively as a learning rate. Rather than simply adding the predictions of new trees to the ensemble with full weight, the eta will be multiplied by the residuals being adding to reduce their weight. This effectively reduces the complexity of the overall model." }, { "code": null, "e": 5089, "s": 4844, "text": "It is common to have small values in the range of 0.1 to 0.3. The smaller weighting of these residuals will still help us train a powerful model, but won’t let that model run away into deep complexity where overfitting is more likely to happen." }, { "code": null, "e": 5163, "s": 5089, "text": "We can finally train our model similar to how we do so with Scikit Learn:" }, { "code": null, "e": 5204, "s": 5163, "text": "model = xgb.train(param, D_train, steps)" }, { "code": null, "e": 5311, "s": 5204, "text": "Let’s now run an evaluation. Again the process is very similar to that of training models in Scikit Learn:" }, { "code": null, "e": 5719, "s": 5311, "text": "import numpy as npfrom sklearn.metrics import precision_score, recall_score, accuracy_scorepreds = model.predict(D_test)best_preds = np.asarray([np.argmax(line) for line in preds])print(\"Precision = {}\".format(precision_score(Y_test, best_preds, average='macro')))print(\"Recall = {}\".format(recall_score(Y_test, best_preds, average='macro')))print(\"Accuracy = {}\".format(accuracy_score(Y_test, best_preds)))" }, { "code": null, "e": 5728, "s": 5719, "text": "Awesome!" }, { "code": null, "e": 5817, "s": 5728, "text": "If you’ve followed all the steps up to this point, you should get at least 90% accuracy!" }, { "code": null, "e": 5952, "s": 5817, "text": "That just about sums up the basics of XGBoost. But there are some more cool features that’ll help you get the most out of your models." }, { "code": null, "e": 6232, "s": 5952, "text": "The gamma parameter can also help with controlling overfitting. It specifies the minimum reduction in the loss required to make a further partition on a leaf node of the tree. I.e if creating a new node doesn’t reduce the loss by a certain amount, then we won’t create it at all." }, { "code": null, "e": 6531, "s": 6232, "text": "The booster parameter allows you to set the type of model you will use when building the ensemble. The default is gbtree which builds an ensemble of decision trees. If your data isn’t too complicated, you can go with the faster and simpler gblinear option which builds an ensemble of linear models." }, { "code": null, "e": 6729, "s": 6531, "text": "Setting the optimal hyperparameters of any ML model can be a challenge. So why not let Scikit Learn do it for you? We can combine Scikit Learn’s grid search with an XGBoost classifier quite easily:" }, { "code": null, "e": 7237, "s": 6729, "text": "from sklearn.model_selection import GridSearchCVclf = xgb.XGBClassifier()parameters = { \"eta\" : [0.05, 0.10, 0.15, 0.20, 0.25, 0.30 ] , \"max_depth\" : [ 3, 4, 5, 6, 8, 10, 12, 15], \"min_child_weight\" : [ 1, 3, 5, 7 ], \"gamma\" : [ 0.0, 0.1, 0.2 , 0.3, 0.4 ], \"colsample_bytree\" : [ 0.3, 0.4, 0.5 , 0.7 ] }grid = GridSearchCV(clf, parameters, n_jobs=4, scoring=\"neg_log_loss\", cv=3)grid.fit(X_train, Y_train)" }, { "code": null, "e": 7385, "s": 7237, "text": "Only do that on a big dataset if you have time to kill — doing a grid search is essentially training an ensemble of decision trees many times over!" }, { "code": null, "e": 7487, "s": 7385, "text": "Once your XGBoost model is trained, you can dump a human readable description of it into a text file:" }, { "code": null, "e": 7520, "s": 7487, "text": "model.dump_model('dump.raw.txt')" }, { "code": null, "e": 7535, "s": 7520, "text": "That’s a wrap!" } ]
GATE | GATE CS 1996 | Question 15 - GeeksforGeeks
31 Oct, 2017 Which of the following sequences denotes the post order traversal sequence of the given tree? a / \ b e / \ / c d f / g (A) f e g c d b a(B) g c b d a f e(C) g c d b f e a(D) f e d g c b aAnswer: (C)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post GATE CS 1996 GATE-GATE CS 1996 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2004 | Question 3 GATE | GATE CS 2010 | Question 24 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2019 | Question 27 GATE | GATE CS 2021 | Set 1 | Question 47 GATE | GATE CS 2011 | Question 7
[ { "code": null, "e": 24078, "s": 24050, "text": "\n31 Oct, 2017" }, { "code": null, "e": 24172, "s": 24078, "text": "Which of the following sequences denotes the post order traversal sequence of the given tree?" }, { "code": null, "e": 24245, "s": 24172, "text": " a\n / \\\n b e\n / \\ /\n c d f\n /\n g\n" }, { "code": null, "e": 24423, "s": 24245, "text": "(A) f e g c d b a(B) g c b d a f e(C) g c d b f e a(D) f e d g c b aAnswer: (C)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post" }, { "code": null, "e": 24436, "s": 24423, "text": "GATE CS 1996" }, { "code": null, "e": 24454, "s": 24436, "text": "GATE-GATE CS 1996" }, { "code": null, "e": 24459, "s": 24454, "text": "GATE" }, { "code": null, "e": 24557, "s": 24459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24591, "s": 24557, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 24633, "s": 24591, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 24675, "s": 24633, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 24709, "s": 24675, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 24742, "s": 24709, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 24776, "s": 24742, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 24810, "s": 24776, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 24844, "s": 24810, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 24886, "s": 24844, "text": "GATE | GATE CS 2021 | Set 1 | Question 47" } ]
Install Apache Kafka on Windows 10 - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws This guide helps you to understand how to install Apache Kafka on Windows 10 operating system and executing some of the basic commands on Kafka console. Apache Kafka is a distributed, fast and scalable messaging queue platform, which is capable of publishing and subscribing to streams of records, similar to a message queue or enterprise messaging system. Install JRE before you further. Download the latest Apache Kafka from the official Apache website for me it is 2.11.2.0.0 release. Click on above highlighted binary downloads and it will be redirected to Apache Foundations main downloads page like below. Select the above-mentioned apache mirror to download Kafka, it will be downloaded as a .tgz. Extract it and you will see the below folder structure. /bin directory represents all the binary files which are helpful to start Kafka server different operating systems. As we are working with the windows machine, there will be a folder named windows under /bin directory, which has all the windows related stuff. /config directory contains all configuration details about Kafka server, zookeeper, and logs. All configurations have their default values if you wanted to change any config details like port you can freely go and change accordingly. # The directory where the snapshot is stored. dataDir=/tmp/zookeeper # the port at which the clients will connect clientPort=2181 # disable the per-ip limit on the number of connections since this is a non-production config maxClientCnxns=0 server.properties ############################# Zookeeper ############################# # Zookeeper connection string (see zookeeper docs for details). # This is a comma separated host:port pairs, each corresponding to a zk # server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". # You can also append an optional chroot string to the urls to specify the # root directory for all kafka znodes. zookeeper.connect=localhost:2181 # Timeout in ms for connecting to zookeeper zookeeper.connection.timeout.ms=6000 ############################# Log Basics ############################# # A comma separated list of directories under which to store log files log.dirs=/tmp/kafka-logs /libs directory contain all dependency executables like java, jetty, log4j and etc. If you are okay with the above default configurations, you are ready to start zookeeper and Kafka server. Go to Kafka_X.XX-X.X.X\bin\windows\ D:\Softwares\kafka_2.11-2.0.0\bin\windows>zookeeper-server-start.bat ../../config/zookeeper.properties [2018-11-17 03:20:58,713] INFO Reading configuration from: ..\..\config\zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig) [2018-11-17 03:20:58,713] INFO autopurge.snapRetainCount set to 3 (org.apache.zookeeper.server.DatadirCleanupManager) [2018-11-17 03:20:58,713] INFO autopurge.purgeInterval set to 0 (org.apache.zookeeper.server.DatadirCleanupManager) [2018-11-17 03:20:58,713] INFO Purge task is not scheduled. (org.apache.zookeeper.server.DatadirCleanupManager) [2018-11-17 03:20:58,713] WARN Either no config or no quorum defined in config, running in standalone mode (org.apache.zookeeper.server.quorum.QuorumPeerMain) [2018-11-17 03:20:58,744] INFO Reading configuration from: ..\..\config\zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig) [2018-11-17 03:20:58,744] INFO Starting server (org.apache.zookeeper.server.ZooKeeperServerMain) [2018-11-17 03:21:03,261] INFO Server environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.server.ZooKeeperServer) ............. ............. [2018-11-17 03:21:03,345] INFO Using org.apache.zookeeper.server.NIOServerCnxnFactory as server connection factory (org.apache.zookeeper.server.ServerCnxnFactory) [2018-11-17 03:21:03,345] INFO binding to port 0.0.0.0/0.0.0.0:2181 (org.apache.zookeeper.server.NIOServerCnxnFactory) [2018-11-17 03:21:35,434] INFO Accepted socket connection from /127.0.0.1:63924 (org.apache.zookeeper.server.NIOServerCnxnFactory) [2018-11-17 03:21:35,450] INFO Client attempting to establish new session at /127.0.0.1:63924 (org.apache.zookeeper.server.ZooKeeperServer) [2018-11-17 03:21:35,450] INFO Creating new log file: log.5 (org.apache.zookeeper.server.persistence.FileTxnLog) [2018-11-17 03:21:35,535] INFO Established session 0x1000238240f0000 with negotiated timeout 6000 for client /127.0.0.1:63924 (org.apache.zookeeper.server.ZooKeeperServer) D:\Softwares\kafka_2.11-2.0.0\bin\windows>kafka-server-start.bat ../../config/server.properties [2018-11-17 03:21:30,291] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$) [2018-11-17 03:21:30,777] INFO starting (kafka.server.KafkaServer) [2018-11-17 03:21:30,777] INFO Connecting to zookeeper on localhost:2181 (kafka.server.KafkaServer) [2018-11-17 03:21:30,831] INFO [ZooKeeperClient] Initializing a new session to localhost:2181. (kafka.zookeeper.ZooKeeperClient) [2018-11-17 03:21:35,350] INFO Client environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.ZooKeeper) [2018-11-17 03:21:35,350] INFO Client environment:host.name=DESKTOP-RN4SMHT (org.apache.zookeeper.ZooKeeper) [2018-11-17 03:21:35,350] INFO Client environment:java.version=9.0.4 (org.apache.zookeeper.ZooKeeper) [2018-11-17 03:21:35,350] INFO Client environment:java.vendor=Oracle Corporation (org.apache.zookeeper.ZooKeeper) [2018-11-17 03:21:35,350] INFO Client environment:java.home=C:\Program Files\Java\jdk-9.0.4 (org.apache.zookeeper.ZooKeeper) ................ ................ [2018-11-17 03:21:43,100] INFO [ProducerId Manager 0]: Acquired new producerId block (brokerId:0,blockStartProducerId:0,blockEndProducerId:999) by writing to Zk with path version 1 (kafka.coordinator.transaction.ProducerIdManager) [2018-11-17 03:21:43,138] INFO [TransactionCoordinator id=0] Starting up. (kafka.coordinator.transaction.TransactionCoordinator) [2018-11-17 03:21:43,154] INFO [TransactionCoordinator id=0] Startup complete. (kafka.coordinator.transaction.TransactionCoordinator) [2018-11-17 03:21:43,154] INFO [Transaction Marker Channel Manager 0]: Starting (kafka.coordinator.transaction.TransactionMarkerChannelManager) [2018-11-17 03:21:43,200] INFO [/config/changes-event-process-thread]: Starting (kafka.common.ZkNodeChangeNotificationListener$ChangeEventProcessThread) [2018-11-17 03:21:43,235] INFO [SocketServer brokerId=0] Started processors for 1 acceptors (kafka.network.SocketServer) [2018-11-17 03:21:43,238] INFO Kafka version : 2.0.0 (org.apache.kafka.common.utils.AppInfoParser) [2018-11-17 03:21:43,238] INFO Kafka commitId : 3402a8361b734732 (org.apache.kafka.common.utils.AppInfoParser) [2018-11-17 03:21:43,238] INFO [KafkaServer id=0] started (kafka.server.KafkaServer) Note: Should start the zookeeper prior to Kafka server. You can see the logs, we have successfully started the Zookeeper and Kafka servers. Then why can’t we create a simple topic and try to exchange some messages between producer and consumer let’s start to do that D:\Softwares\kafka_2.11-2.0.0\bin\windows>kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic items-topic Created topic "items-topic". D:\Softwares\kafka_2.11-2.0.0\bin\windows>kafka-console-producer.bat --broker-list localhost:9092 --topic items-topic >hai chandra >hello D:\Softwares\kafka_2.11-2.0.0\bin\windows>kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic items-topic --from-beginning hai chandra hello If you see these messages on consumer console, you all done. Then you can play with producer and consumer terminal bypassing some Kafka messages. Apache Kafka quick start Happy Learning 🙂 Spring Boot Kafka Producer Example Spring Boot Kafka Consume JSON Messages Example Setup/Install Redis Server on Windows 10 How to install Apache Kafka on Ubuntu 18.04 Install Mysql on Windows 10 Step by Step Install Apache Solr on Windows 10 Sending Spring Boot Kafka JSON Message to Kafka Topic How to Install Ant on Windows 10 How install Python on Windows 10 How to install Elasticsearch on Windows 10 How to install PuTTY on windows 10 How to install RabbitMQ on Windows 10 How to install Gradle on Windows 10 How to install SOAPUI on Windows 10 How to Install Git windows 10 Operating System Spring Boot Kafka Producer Example Spring Boot Kafka Consume JSON Messages Example Setup/Install Redis Server on Windows 10 How to install Apache Kafka on Ubuntu 18.04 Install Mysql on Windows 10 Step by Step Install Apache Solr on Windows 10 Sending Spring Boot Kafka JSON Message to Kafka Topic How to Install Ant on Windows 10 How install Python on Windows 10 How to install Elasticsearch on Windows 10 How to install PuTTY on windows 10 How to install RabbitMQ on Windows 10 How to install Gradle on Windows 10 How to install SOAPUI on Windows 10 How to Install Git windows 10 Operating System charan March 25, 2019 at 10:29 am - Reply Thank you very much chandrashekar, Followed your post as it is and it works like a magic . 🙂 saved lot of time. NRaj June 11, 2019 at 4:16 pm - Reply Thanks for your post , it was very helpful for me as a beginner my gray area is for topic creation zookeeper is used and producer brokerlist and consumer bootstrap is used if these difference /important of using this is explained it would be helpful even more Roshan June 28, 2019 at 8:29 pm - Reply Thanks Chandrashekhar for this detailed post on installing Kafka components on windows 10 machine. If Message Producer (code) and Consumer (code) are running from localhost, then the messages are circulating correctly. But when I run Producer sample code from another machine (other than kafka server hosted machine) then you need add below line in the server.properties file and restart the kafka server, otherwise message doesn’t reach to kafka instance. advertised.listeners=PLAINTEXT://<>:9092 I used .net code with Confluent.Kafka [Confluent’s .NET Client for Apache Kafka] for creating sample. charan March 25, 2019 at 10:29 am - Reply Thank you very much chandrashekar, Followed your post as it is and it works like a magic . 🙂 saved lot of time. Thank you very much chandrashekar, Followed your post as it is and it works like a magic . 🙂 saved lot of time. NRaj June 11, 2019 at 4:16 pm - Reply Thanks for your post , it was very helpful for me as a beginner my gray area is for topic creation zookeeper is used and producer brokerlist and consumer bootstrap is used if these difference /important of using this is explained it would be helpful even more Thanks for your post , it was very helpful for me as a beginner my gray area is for topic creation zookeeper is used and producer brokerlist and consumer bootstrap is used if these difference /important of using this is explained it would be helpful even more Roshan June 28, 2019 at 8:29 pm - Reply Thanks Chandrashekhar for this detailed post on installing Kafka components on windows 10 machine. If Message Producer (code) and Consumer (code) are running from localhost, then the messages are circulating correctly. But when I run Producer sample code from another machine (other than kafka server hosted machine) then you need add below line in the server.properties file and restart the kafka server, otherwise message doesn’t reach to kafka instance. advertised.listeners=PLAINTEXT://<>:9092 I used .net code with Confluent.Kafka [Confluent’s .NET Client for Apache Kafka] for creating sample. Thanks Chandrashekhar for this detailed post on installing Kafka components on windows 10 machine. If Message Producer (code) and Consumer (code) are running from localhost, then the messages are circulating correctly. But when I run Producer sample code from another machine (other than kafka server hosted machine) then you need add below line in the server.properties file and restart the kafka server, otherwise message doesn’t reach to kafka instance. advertised.listeners=PLAINTEXT://<>:9092 I used .net code with Confluent.Kafka [Confluent’s .NET Client for Apache Kafka] for creating sample.
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 551, "s": 398, "text": "This guide helps you to understand how to install Apache Kafka on Windows 10 operating system and executing some of the basic commands on Kafka console." }, { "code": null, "e": 755, "s": 551, "text": "Apache Kafka is a distributed, fast and scalable messaging queue platform, which is capable of publishing and subscribing to streams of records, similar to a message queue or enterprise messaging system." }, { "code": null, "e": 787, "s": 755, "text": "Install JRE before you further." }, { "code": null, "e": 886, "s": 787, "text": "Download the latest Apache Kafka from the official Apache website for me it is 2.11.2.0.0 release." }, { "code": null, "e": 1012, "s": 888, "text": "Click on above highlighted binary downloads and it will be redirected to Apache Foundations main downloads page like below." }, { "code": null, "e": 1161, "s": 1012, "text": "Select the above-mentioned apache mirror to download Kafka, it will be downloaded as a .tgz. Extract it and you will see the below folder structure." }, { "code": null, "e": 1421, "s": 1161, "text": "/bin directory represents all the binary files which are helpful to start Kafka server different operating systems. As we are working with the windows machine, there will be a folder named windows under /bin directory, which has all the windows related stuff." }, { "code": null, "e": 1655, "s": 1421, "text": "/config directory contains all configuration details about Kafka server, zookeeper, and logs. All configurations have their default values if you wanted to change any config details like port you can freely go and change accordingly." }, { "code": null, "e": 1896, "s": 1655, "text": "# The directory where the snapshot is stored.\ndataDir=/tmp/zookeeper\n# the port at which the clients will connect\nclientPort=2181\n# disable the per-ip limit on the number of connections since this is a non-production config\nmaxClientCnxns=0" }, { "code": null, "e": 1914, "s": 1896, "text": "server.properties" }, { "code": null, "e": 2582, "s": 1914, "text": "############################# Zookeeper #############################\n\n# Zookeeper connection string (see zookeeper docs for details).\n# This is a comma separated host:port pairs, each corresponding to a zk\n# server. e.g. \"127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002\".\n# You can also append an optional chroot string to the urls to specify the\n# root directory for all kafka znodes.\nzookeeper.connect=localhost:2181\n\n# Timeout in ms for connecting to zookeeper\nzookeeper.connection.timeout.ms=6000\n\n############################# Log Basics #############################\n\n# A comma separated list of directories under which to store log files\nlog.dirs=/tmp/kafka-logs" }, { "code": null, "e": 2666, "s": 2582, "text": "/libs directory contain all dependency executables like java, jetty, log4j and etc." }, { "code": null, "e": 2772, "s": 2666, "text": "If you are okay with the above default configurations, you are ready to start zookeeper and Kafka server." }, { "code": null, "e": 2808, "s": 2772, "text": "Go to Kafka_X.XX-X.X.X\\bin\\windows\\" }, { "code": null, "e": 4867, "s": 2808, "text": "D:\\Softwares\\kafka_2.11-2.0.0\\bin\\windows>zookeeper-server-start.bat ../../config/zookeeper.properties\n[2018-11-17 03:20:58,713] INFO Reading configuration from: ..\\..\\config\\zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig)\n[2018-11-17 03:20:58,713] INFO autopurge.snapRetainCount set to 3 (org.apache.zookeeper.server.DatadirCleanupManager)\n[2018-11-17 03:20:58,713] INFO autopurge.purgeInterval set to 0 (org.apache.zookeeper.server.DatadirCleanupManager)\n[2018-11-17 03:20:58,713] INFO Purge task is not scheduled. (org.apache.zookeeper.server.DatadirCleanupManager)\n[2018-11-17 03:20:58,713] WARN Either no config or no quorum defined in config, running in standalone mode (org.apache.zookeeper.server.quorum.QuorumPeerMain)\n[2018-11-17 03:20:58,744] INFO Reading configuration from: ..\\..\\config\\zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig)\n[2018-11-17 03:20:58,744] INFO Starting server (org.apache.zookeeper.server.ZooKeeperServerMain)\n[2018-11-17 03:21:03,261] INFO Server environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.server.ZooKeeperServer)\n.............\n.............\n[2018-11-17 03:21:03,345] INFO Using org.apache.zookeeper.server.NIOServerCnxnFactory as server connection factory (org.apache.zookeeper.server.ServerCnxnFactory)\n[2018-11-17 03:21:03,345] INFO binding to port 0.0.0.0/0.0.0.0:2181 (org.apache.zookeeper.server.NIOServerCnxnFactory)\n[2018-11-17 03:21:35,434] INFO Accepted socket connection from /127.0.0.1:63924 (org.apache.zookeeper.server.NIOServerCnxnFactory)\n[2018-11-17 03:21:35,450] INFO Client attempting to establish new session at /127.0.0.1:63924 (org.apache.zookeeper.server.ZooKeeperServer)\n[2018-11-17 03:21:35,450] INFO Creating new log file: log.5 (org.apache.zookeeper.server.persistence.FileTxnLog)\n[2018-11-17 03:21:35,535] INFO Established session 0x1000238240f0000 with negotiated timeout 6000 for client /127.0.0.1:63924 (org.apache.zookeeper.server.ZooKeeperServer)" }, { "code": null, "e": 7254, "s": 4867, "text": "D:\\Softwares\\kafka_2.11-2.0.0\\bin\\windows>kafka-server-start.bat ../../config/server.properties\n[2018-11-17 03:21:30,291] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$)\n[2018-11-17 03:21:30,777] INFO starting (kafka.server.KafkaServer)\n[2018-11-17 03:21:30,777] INFO Connecting to zookeeper on localhost:2181 (kafka.server.KafkaServer)\n[2018-11-17 03:21:30,831] INFO [ZooKeeperClient] Initializing a new session to localhost:2181. (kafka.zookeeper.ZooKeeperClient)\n[2018-11-17 03:21:35,350] INFO Client environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.ZooKeeper)\n[2018-11-17 03:21:35,350] INFO Client environment:host.name=DESKTOP-RN4SMHT (org.apache.zookeeper.ZooKeeper)\n[2018-11-17 03:21:35,350] INFO Client environment:java.version=9.0.4 (org.apache.zookeeper.ZooKeeper)\n[2018-11-17 03:21:35,350] INFO Client environment:java.vendor=Oracle Corporation (org.apache.zookeeper.ZooKeeper)\n[2018-11-17 03:21:35,350] INFO Client environment:java.home=C:\\Program Files\\Java\\jdk-9.0.4 (org.apache.zookeeper.ZooKeeper)\n................\n................\n[2018-11-17 03:21:43,100] INFO [ProducerId Manager 0]: Acquired new producerId block (brokerId:0,blockStartProducerId:0,blockEndProducerId:999) by writing to Zk with path version 1 (kafka.coordinator.transaction.ProducerIdManager)\n[2018-11-17 03:21:43,138] INFO [TransactionCoordinator id=0] Starting up. (kafka.coordinator.transaction.TransactionCoordinator)\n[2018-11-17 03:21:43,154] INFO [TransactionCoordinator id=0] Startup complete. (kafka.coordinator.transaction.TransactionCoordinator)\n[2018-11-17 03:21:43,154] INFO [Transaction Marker Channel Manager 0]: Starting (kafka.coordinator.transaction.TransactionMarkerChannelManager)\n[2018-11-17 03:21:43,200] INFO [/config/changes-event-process-thread]: Starting (kafka.common.ZkNodeChangeNotificationListener$ChangeEventProcessThread)\n[2018-11-17 03:21:43,235] INFO [SocketServer brokerId=0] Started processors for 1 acceptors (kafka.network.SocketServer)\n[2018-11-17 03:21:43,238] INFO Kafka version : 2.0.0 (org.apache.kafka.common.utils.AppInfoParser)\n[2018-11-17 03:21:43,238] INFO Kafka commitId : 3402a8361b734732 (org.apache.kafka.common.utils.AppInfoParser)\n[2018-11-17 03:21:43,238] INFO [KafkaServer id=0] started (kafka.server.KafkaServer)" }, { "code": null, "e": 7310, "s": 7254, "text": "Note: Should start the zookeeper prior to Kafka server." }, { "code": null, "e": 7394, "s": 7310, "text": "You can see the logs, we have successfully started the Zookeeper and Kafka servers." }, { "code": null, "e": 7521, "s": 7394, "text": "Then why can’t we create a simple topic and try to exchange some messages between producer and consumer let’s start to do that" }, { "code": null, "e": 7703, "s": 7521, "text": "D:\\Softwares\\kafka_2.11-2.0.0\\bin\\windows>kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic items-topic\nCreated topic \"items-topic\"." }, { "code": null, "e": 7841, "s": 7703, "text": "D:\\Softwares\\kafka_2.11-2.0.0\\bin\\windows>kafka-console-producer.bat --broker-list localhost:9092 --topic items-topic\n>hai chandra\n>hello" }, { "code": null, "e": 7999, "s": 7841, "text": "D:\\Softwares\\kafka_2.11-2.0.0\\bin\\windows>kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic items-topic --from-beginning\nhai chandra\nhello" }, { "code": null, "e": 8145, "s": 7999, "text": "If you see these messages on consumer console, you all done. Then you can play with producer and consumer terminal bypassing some Kafka messages." }, { "code": null, "e": 8170, "s": 8145, "text": "Apache Kafka quick start" }, { "code": null, "e": 8187, "s": 8170, "text": "Happy Learning 🙂" }, { "code": null, "e": 8787, "s": 8187, "text": "\nSpring Boot Kafka Producer Example\nSpring Boot Kafka Consume JSON Messages Example\nSetup/Install Redis Server on Windows 10\nHow to install Apache Kafka on Ubuntu 18.04\nInstall Mysql on Windows 10 Step by Step\nInstall Apache Solr on Windows 10\nSending Spring Boot Kafka JSON Message to Kafka Topic\nHow to Install Ant on Windows 10\nHow install Python on Windows 10\nHow to install Elasticsearch on Windows 10\nHow to install PuTTY on windows 10\nHow to install RabbitMQ on Windows 10\nHow to install Gradle on Windows 10\nHow to install SOAPUI on Windows 10\nHow to Install Git windows 10 Operating System\n" }, { "code": null, "e": 8822, "s": 8787, "text": "Spring Boot Kafka Producer Example" }, { "code": null, "e": 8870, "s": 8822, "text": "Spring Boot Kafka Consume JSON Messages Example" }, { "code": null, "e": 8911, "s": 8870, "text": "Setup/Install Redis Server on Windows 10" }, { "code": null, "e": 8955, "s": 8911, "text": "How to install Apache Kafka on Ubuntu 18.04" }, { "code": null, "e": 8996, "s": 8955, "text": "Install Mysql on Windows 10 Step by Step" }, { "code": null, "e": 9030, "s": 8996, "text": "Install Apache Solr on Windows 10" }, { "code": null, "e": 9084, "s": 9030, "text": "Sending Spring Boot Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 9117, "s": 9084, "text": "How to Install Ant on Windows 10" }, { "code": null, "e": 9150, "s": 9117, "text": "How install Python on Windows 10" }, { "code": null, "e": 9193, "s": 9150, "text": "How to install Elasticsearch on Windows 10" }, { "code": null, "e": 9228, "s": 9193, "text": "How to install PuTTY on windows 10" }, { "code": null, "e": 9266, "s": 9228, "text": "How to install RabbitMQ on Windows 10" }, { "code": null, "e": 9302, "s": 9266, "text": "How to install Gradle on Windows 10" }, { "code": null, "e": 9338, "s": 9302, "text": "How to install SOAPUI on Windows 10" }, { "code": null, "e": 9385, "s": 9338, "text": "How to Install Git windows 10 Operating System" }, { "code": null, "e": 10515, "s": 9385, "text": "\n\n\n\n\n\ncharan\nMarch 25, 2019 at 10:29 am - Reply \n\nThank you very much chandrashekar, Followed your post as it is and it works like a magic . 🙂 saved lot of time.\n\n\n\n\n\n\n\n\n\nNRaj\nJune 11, 2019 at 4:16 pm - Reply \n\nThanks for your post , it was very helpful for me as a beginner my gray area is for topic creation zookeeper is used and producer brokerlist and consumer bootstrap is used if these difference /important of using this is explained it would be helpful even more\n\n\n\n\n\n\n\n\n\nRoshan\nJune 28, 2019 at 8:29 pm - Reply \n\nThanks Chandrashekhar for this detailed post on installing Kafka components on windows 10 machine. If Message Producer (code) and Consumer (code) are running from localhost, then the messages are circulating correctly. But when I run Producer sample code from another machine (other than kafka server hosted machine) then you need add below line in the server.properties file and restart the kafka server, otherwise message doesn’t reach to kafka instance. \nadvertised.listeners=PLAINTEXT://<>:9092\nI used .net code with Confluent.Kafka [Confluent’s .NET Client for Apache Kafka] for creating sample.\n\n\n\n\n" }, { "code": null, "e": 10680, "s": 10515, "text": "\n\n\n\n\ncharan\nMarch 25, 2019 at 10:29 am - Reply \n\nThank you very much chandrashekar, Followed your post as it is and it works like a magic . 🙂 saved lot of time.\n\n\n\n" }, { "code": null, "e": 10792, "s": 10680, "text": "Thank you very much chandrashekar, Followed your post as it is and it works like a magic . 🙂 saved lot of time." }, { "code": null, "e": 11102, "s": 10792, "text": "\n\n\n\n\nNRaj\nJune 11, 2019 at 4:16 pm - Reply \n\nThanks for your post , it was very helpful for me as a beginner my gray area is for topic creation zookeeper is used and producer brokerlist and consumer bootstrap is used if these difference /important of using this is explained it would be helpful even more\n\n\n\n" }, { "code": null, "e": 11363, "s": 11102, "text": "Thanks for your post , it was very helpful for me as a beginner my gray area is for topic creation zookeeper is used and producer brokerlist and consumer bootstrap is used if these difference /important of using this is explained it would be helpful even more" }, { "code": null, "e": 12016, "s": 11363, "text": "\n\n\n\n\nRoshan\nJune 28, 2019 at 8:29 pm - Reply \n\nThanks Chandrashekhar for this detailed post on installing Kafka components on windows 10 machine. If Message Producer (code) and Consumer (code) are running from localhost, then the messages are circulating correctly. But when I run Producer sample code from another machine (other than kafka server hosted machine) then you need add below line in the server.properties file and restart the kafka server, otherwise message doesn’t reach to kafka instance. \nadvertised.listeners=PLAINTEXT://<>:9092\nI used .net code with Confluent.Kafka [Confluent’s .NET Client for Apache Kafka] for creating sample.\n\n\n\n" }, { "code": null, "e": 12475, "s": 12016, "text": "Thanks Chandrashekhar for this detailed post on installing Kafka components on windows 10 machine. If Message Producer (code) and Consumer (code) are running from localhost, then the messages are circulating correctly. But when I run Producer sample code from another machine (other than kafka server hosted machine) then you need add below line in the server.properties file and restart the kafka server, otherwise message doesn’t reach to kafka instance. " }, { "code": null, "e": 12516, "s": 12475, "text": "advertised.listeners=PLAINTEXT://<>:9092" } ]
How to declare a variable within lambda expression in Java?
A lambda expression is a function that expects and accepts input parameters and produces output results. It is an instance of a functional interface and also known as a single abstract method interface (SAM interface) like Runnable, Comparator, Callable and etc. We can declare a variable as a final string[] array and able to access that array index within a lambda expression. import java.util.*; public class LambdaTest { public static void main(String args[]) { final String[] country = {null}; List cities = new ArrayList(); cities.add("Hyderabad"); cities.add("Ireland"); cities.add("Texas"); cities.add("Cape Town"); cities.forEach(item -> { // lambda expression if(item.equals("Ireland")) country[0] = "UK"; // variable array }); System.out.println(country[0]); } } UK
[ { "code": null, "e": 1441, "s": 1062, "text": "A lambda expression is a function that expects and accepts input parameters and produces output results. It is an instance of a functional interface and also known as a single abstract method interface (SAM interface) like Runnable, Comparator, Callable and etc. We can declare a variable as a final string[] array and able to access that array index within a lambda expression." }, { "code": null, "e": 1930, "s": 1441, "text": "import java.util.*;\n\npublic class LambdaTest {\n public static void main(String args[]) {\n final String[] country = {null};\n\n List cities = new ArrayList();\n cities.add(\"Hyderabad\");\n cities.add(\"Ireland\");\n cities.add(\"Texas\");\n cities.add(\"Cape Town\");\n\n cities.forEach(item -> { // lambda expression\n if(item.equals(\"Ireland\"))\n country[0] = \"UK\"; // variable array\n });\n System.out.println(country[0]);\n }\n}" }, { "code": null, "e": 1933, "s": 1930, "text": "UK" } ]
How to print "Hello World!" using Python?
The basic way to do output to screen is to use the print statement. >>> print 'Hello, world' Hello, world To print multiple things on the same line separated by spaces, use commas between them. For example: >>> print 'Hello,', 'World' Hello, World In Python 3, all print is a function and not a statement. Hence its arguments need to be surrounded by parenthesis. For example, >>> print("Hello", "world") Hello world
[ { "code": null, "e": 1130, "s": 1062, "text": "The basic way to do output to screen is to use the print statement." }, { "code": null, "e": 1168, "s": 1130, "text": ">>> print 'Hello, world'\nHello, world" }, { "code": null, "e": 1269, "s": 1168, "text": "To print multiple things on the same line separated by spaces, use commas between them. For example:" }, { "code": null, "e": 1310, "s": 1269, "text": ">>> print 'Hello,', 'World'\nHello, World" }, { "code": null, "e": 1439, "s": 1310, "text": "In Python 3, all print is a function and not a statement. Hence its arguments need to be surrounded by parenthesis. For example," }, { "code": null, "e": 1479, "s": 1439, "text": ">>> print(\"Hello\", \"world\")\nHello world" } ]
How to build Spark from source and deploy it to a Kubernetes cluster in 60 minutes | by Nikolay Dimolarov | Towards Data Science
Motivation/Prelude In my last article I explained the broad strokes of the Hadoop ecosystem and you can read about it here. What is important about that article is the end, which I will blatantly plagiarise from my other article as it serves as the beginning of this one too: Now, if you have been sort of listening in on Hadoop’s ecosystem over the last few years you would have seen that the two biggest players on the market — Cloudera and Hortonworks — merged around a year ago amid a slow down of the Hadoop big data market. Add the fact that people seem way more interested in Kubernetes than in older Hadoop specific technologies like YARN for resource management and orchestration, the fast adoption of DL frameworks like PyTorch and you sort of have a perfect storm forming for the ageing Hadoop stack. Nonetheless projects like Apache Spark are chugging along by e.g. introducing Kubernetes as an alternative to YARN. Exciting times for the ecosystem! Introduction The goal of this article is to show you what some of the cool kids are doing in 2020 in the Big Data ecosystem; which is trying to cram stuff into Kubernetes (which is a good thing!). More specifically using Spark’s experimental implementation of a native Spark Driver and Executor where Kubernetes is the resource manager (instead of e.g. YARN) ... and let us do this in 60 minutes: Clone Spark project from GitHubBuild Spark distribution with MavenBuild Docker Image locallyRun Spark Pi job with multiple executor replicasUse port forwarding to show the Spark UI in your browser and inspect your Spark job Clone Spark project from GitHub Build Spark distribution with Maven Build Docker Image locally Run Spark Pi job with multiple executor replicas Use port forwarding to show the Spark UI in your browser and inspect your Spark job If it is that simple why do we need this article?! Read along to find out how this took me days to figure out the first time around. Disclaimer: your mileage on the 60 minutes might vary but it is really doable under the assumption that you generally know how do the things on a computer including setting up a local k8s cluster and running bash scripts and the likes. Furthermore, building Spark might take a while if you have a slowish computer ;) Now that everyone is on board, let’s deploy Spark on Kubernetes. For this you can use your laptop’s run of the mill minikube setup instead of renting a server in a public cloud just for this exercise. Unless you want to go all in on this, in which case you have just been saluted. Steps 1–3 (clone repo, build Spark, build Docker image): This is actually where the fun starts — on the “easiest” steps. Well, put on your seatbelt and check this out (pun intended): If you clone the official Spark repository here and innocently follow the official Spark guide on running Spark in k8s here, you will run into this issue that I opened in Spark’s Jira backlog a few days ago. Namely, that there are multiple wrong references in the Dockerfile and because of that simply running a docker build command as described in the Dockerfile comments will not work. Update: Well, it turns out that you can in fact run things as described in the documentation but only if you pay really close attention. Instead of running ./build/mvn -Pkubernetes -DskipTests clean package you need to run dev/make-distribution.sh -Pkubernetes which creates a Spark distribution instead of just the normal assembly bits and pieces but I guess I skipped on the fine-print in their tutorial, so I updated this article accordingly. tl;dr to complete steps 1–3 simply do this: git clone [email protected]:apache/spark.gitcd sparkdev/make-distribution.sh -Pkubernetescd distdocker build -t spark:latest -f kubernetes/dockerfiles/spark/Dockerfile . At this point you should have an image of Spark in your local Docker registry! Step 4: Run Spark Pi job with multiple executor replicas in Kubernetes: What the Spark article I linked above mentions but does not quite explain as a showstopper is the fact that due to Kubernetes’ RBAC (role-based access control), you cannot simply deploy Spark into your cluster as Spark needs some additional rights to your Kubernetes cluster to manage pods. This is due to Spark’s architecture — you deploy a Spark Driver, which can then create the Spark Executors in pods and then clean them up once the job is done: tl;dr we need to create a service account with kubectl for Spark: kubectl create serviceaccount sparkkubectl create clusterrolebinding spark-role --clusterrole=edit --serviceaccount=default:spark --namespace=default Next up is to run Spark Pi with our locally built Docker image: bin/spark-submit \--master k8s://https://kubernetes.docker.internal:6443 \--deploy-mode cluster \--name spark-pi \--class org.apache.spark.examples.SparkPi \--conf spark.executor.instances=2 \--conf spark.kubernetes.container.image=spark:latest \--conf spark.kubernetes.container.image.pullPolicy=Never \--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \local:///opt/spark/examples/jars/spark-examples_2.12-3.1.0-SNAPSHOT.jar 10000000 Ok, but what is actually happening here. Well, this is how you deploy your Spark Driver into your Kubernetes cluster! Let us go through the parameters, so you can actually start working with this on your own afterwards: define Kubernetes cluster (find with kubectl cluster-info). Yes, the somewhat weird k8s:// prefix is needed. define deployment mode (cluster, duh) define name for Spark Driver (that’s also what your pod’s name will start with) define Spark Pi example run the Spark Executor with 2 replicas on Kubernetes that will be spawned by your Spark Driver use our local spark:latest image define the Kubernetes image pull policy to Never, so the local image with that name can be used. If one is not very familiar with the inner workings of k8s, this could definitely take a minute to figure out... define service account (remember RBAC?) point to local jar path (which is copied with all other examples in the Dockerfile to the specified path) with the argument 10000000 (if you do not know what that number is for, examine the Spark Pi source code and documentation) . Yes, the local:/// is correct and it’s not a typo. kubectl get pods Should now return a list of the running pods! And do not worry when they get terminated in the end — that is the default setting for this implementation. Step 5: Use port forwarding to show Spark UI kubectl port-forward <insert spark driver pod name> 4040:4040 Then you should be able to access the Spark UI with the localhost:4040 from the first command from above in your browser like so: You can also check out your logs like this: kubectl -n=default logs -f <insert spark driver pod name> Conclusion Doing this exact setup with the config and the Dockerfile can be either super straightforward if you know Spark and Kubernetes really well or a little bit of a nightmare if you do not. I hope that this will help you to do this in minutes instead! Where do you go from here? Anywhere you want. The goal of this article was to quickly get you up and running with a new fancy resource manager for Spark. I suggest you play around with this setup with other Spark apps as the next steps — I might just write an article on some more complicated examples in the future (let me know if I should). Have fun with Kubernetes! Alternatives This is an update from 20th April 2020 — one can also use Google’s native Kubernetes operator, which seems very promising and can remove the manual deployment steps into your cluster: github.com It is currently being used by e.g. Salesforce and Microsoft in production and is being evaluated for production by Uber and Lyft. Something to look out for in the future!
[ { "code": null, "e": 191, "s": 172, "text": "Motivation/Prelude" }, { "code": null, "e": 448, "s": 191, "text": "In my last article I explained the broad strokes of the Hadoop ecosystem and you can read about it here. What is important about that article is the end, which I will blatantly plagiarise from my other article as it serves as the beginning of this one too:" }, { "code": null, "e": 1134, "s": 448, "text": "Now, if you have been sort of listening in on Hadoop’s ecosystem over the last few years you would have seen that the two biggest players on the market — Cloudera and Hortonworks — merged around a year ago amid a slow down of the Hadoop big data market. Add the fact that people seem way more interested in Kubernetes than in older Hadoop specific technologies like YARN for resource management and orchestration, the fast adoption of DL frameworks like PyTorch and you sort of have a perfect storm forming for the ageing Hadoop stack. Nonetheless projects like Apache Spark are chugging along by e.g. introducing Kubernetes as an alternative to YARN. Exciting times for the ecosystem!" }, { "code": null, "e": 1147, "s": 1134, "text": "Introduction" }, { "code": null, "e": 1493, "s": 1147, "text": "The goal of this article is to show you what some of the cool kids are doing in 2020 in the Big Data ecosystem; which is trying to cram stuff into Kubernetes (which is a good thing!). More specifically using Spark’s experimental implementation of a native Spark Driver and Executor where Kubernetes is the resource manager (instead of e.g. YARN)" }, { "code": null, "e": 1531, "s": 1493, "text": "... and let us do this in 60 minutes:" }, { "code": null, "e": 1755, "s": 1531, "text": "Clone Spark project from GitHubBuild Spark distribution with MavenBuild Docker Image locallyRun Spark Pi job with multiple executor replicasUse port forwarding to show the Spark UI in your browser and inspect your Spark job" }, { "code": null, "e": 1787, "s": 1755, "text": "Clone Spark project from GitHub" }, { "code": null, "e": 1823, "s": 1787, "text": "Build Spark distribution with Maven" }, { "code": null, "e": 1850, "s": 1823, "text": "Build Docker Image locally" }, { "code": null, "e": 1899, "s": 1850, "text": "Run Spark Pi job with multiple executor replicas" }, { "code": null, "e": 1983, "s": 1899, "text": "Use port forwarding to show the Spark UI in your browser and inspect your Spark job" }, { "code": null, "e": 2116, "s": 1983, "text": "If it is that simple why do we need this article?! Read along to find out how this took me days to figure out the first time around." }, { "code": null, "e": 2433, "s": 2116, "text": "Disclaimer: your mileage on the 60 minutes might vary but it is really doable under the assumption that you generally know how do the things on a computer including setting up a local k8s cluster and running bash scripts and the likes. Furthermore, building Spark might take a while if you have a slowish computer ;)" }, { "code": null, "e": 2714, "s": 2433, "text": "Now that everyone is on board, let’s deploy Spark on Kubernetes. For this you can use your laptop’s run of the mill minikube setup instead of renting a server in a public cloud just for this exercise. Unless you want to go all in on this, in which case you have just been saluted." }, { "code": null, "e": 2771, "s": 2714, "text": "Steps 1–3 (clone repo, build Spark, build Docker image):" }, { "code": null, "e": 2897, "s": 2771, "text": "This is actually where the fun starts — on the “easiest” steps. Well, put on your seatbelt and check this out (pun intended):" }, { "code": null, "e": 3105, "s": 2897, "text": "If you clone the official Spark repository here and innocently follow the official Spark guide on running Spark in k8s here, you will run into this issue that I opened in Spark’s Jira backlog a few days ago." }, { "code": null, "e": 3285, "s": 3105, "text": "Namely, that there are multiple wrong references in the Dockerfile and because of that simply running a docker build command as described in the Dockerfile comments will not work." }, { "code": null, "e": 3422, "s": 3285, "text": "Update: Well, it turns out that you can in fact run things as described in the documentation but only if you pay really close attention." }, { "code": null, "e": 3441, "s": 3422, "text": "Instead of running" }, { "code": null, "e": 3492, "s": 3441, "text": "./build/mvn -Pkubernetes -DskipTests clean package" }, { "code": null, "e": 3508, "s": 3492, "text": "you need to run" }, { "code": null, "e": 3546, "s": 3508, "text": "dev/make-distribution.sh -Pkubernetes" }, { "code": null, "e": 3731, "s": 3546, "text": "which creates a Spark distribution instead of just the normal assembly bits and pieces but I guess I skipped on the fine-print in their tutorial, so I updated this article accordingly." }, { "code": null, "e": 3775, "s": 3731, "text": "tl;dr to complete steps 1–3 simply do this:" }, { "code": null, "e": 3942, "s": 3775, "text": "git clone [email protected]:apache/spark.gitcd sparkdev/make-distribution.sh -Pkubernetescd distdocker build -t spark:latest -f kubernetes/dockerfiles/spark/Dockerfile ." }, { "code": null, "e": 4021, "s": 3942, "text": "At this point you should have an image of Spark in your local Docker registry!" }, { "code": null, "e": 4093, "s": 4021, "text": "Step 4: Run Spark Pi job with multiple executor replicas in Kubernetes:" }, { "code": null, "e": 4544, "s": 4093, "text": "What the Spark article I linked above mentions but does not quite explain as a showstopper is the fact that due to Kubernetes’ RBAC (role-based access control), you cannot simply deploy Spark into your cluster as Spark needs some additional rights to your Kubernetes cluster to manage pods. This is due to Spark’s architecture — you deploy a Spark Driver, which can then create the Spark Executors in pods and then clean them up once the job is done:" }, { "code": null, "e": 4610, "s": 4544, "text": "tl;dr we need to create a service account with kubectl for Spark:" }, { "code": null, "e": 4761, "s": 4610, "text": "kubectl create serviceaccount sparkkubectl create clusterrolebinding spark-role --clusterrole=edit --serviceaccount=default:spark --namespace=default" }, { "code": null, "e": 4825, "s": 4761, "text": "Next up is to run Spark Pi with our locally built Docker image:" }, { "code": null, "e": 5280, "s": 4825, "text": "bin/spark-submit \\--master k8s://https://kubernetes.docker.internal:6443 \\--deploy-mode cluster \\--name spark-pi \\--class org.apache.spark.examples.SparkPi \\--conf spark.executor.instances=2 \\--conf spark.kubernetes.container.image=spark:latest \\--conf spark.kubernetes.container.image.pullPolicy=Never \\--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \\local:///opt/spark/examples/jars/spark-examples_2.12-3.1.0-SNAPSHOT.jar 10000000" }, { "code": null, "e": 5500, "s": 5280, "text": "Ok, but what is actually happening here. Well, this is how you deploy your Spark Driver into your Kubernetes cluster! Let us go through the parameters, so you can actually start working with this on your own afterwards:" }, { "code": null, "e": 5609, "s": 5500, "text": "define Kubernetes cluster (find with kubectl cluster-info). Yes, the somewhat weird k8s:// prefix is needed." }, { "code": null, "e": 5647, "s": 5609, "text": "define deployment mode (cluster, duh)" }, { "code": null, "e": 5727, "s": 5647, "text": "define name for Spark Driver (that’s also what your pod’s name will start with)" }, { "code": null, "e": 5751, "s": 5727, "text": "define Spark Pi example" }, { "code": null, "e": 5846, "s": 5751, "text": "run the Spark Executor with 2 replicas on Kubernetes that will be spawned by your Spark Driver" }, { "code": null, "e": 5879, "s": 5846, "text": "use our local spark:latest image" }, { "code": null, "e": 6089, "s": 5879, "text": "define the Kubernetes image pull policy to Never, so the local image with that name can be used. If one is not very familiar with the inner workings of k8s, this could definitely take a minute to figure out..." }, { "code": null, "e": 6129, "s": 6089, "text": "define service account (remember RBAC?)" }, { "code": null, "e": 6412, "s": 6129, "text": "point to local jar path (which is copied with all other examples in the Dockerfile to the specified path) with the argument 10000000 (if you do not know what that number is for, examine the Spark Pi source code and documentation) . Yes, the local:/// is correct and it’s not a typo." }, { "code": null, "e": 6429, "s": 6412, "text": "kubectl get pods" }, { "code": null, "e": 6583, "s": 6429, "text": "Should now return a list of the running pods! And do not worry when they get terminated in the end — that is the default setting for this implementation." }, { "code": null, "e": 6628, "s": 6583, "text": "Step 5: Use port forwarding to show Spark UI" }, { "code": null, "e": 6690, "s": 6628, "text": "kubectl port-forward <insert spark driver pod name> 4040:4040" }, { "code": null, "e": 6820, "s": 6690, "text": "Then you should be able to access the Spark UI with the localhost:4040 from the first command from above in your browser like so:" }, { "code": null, "e": 6864, "s": 6820, "text": "You can also check out your logs like this:" }, { "code": null, "e": 6922, "s": 6864, "text": "kubectl -n=default logs -f <insert spark driver pod name>" }, { "code": null, "e": 6933, "s": 6922, "text": "Conclusion" }, { "code": null, "e": 7180, "s": 6933, "text": "Doing this exact setup with the config and the Dockerfile can be either super straightforward if you know Spark and Kubernetes really well or a little bit of a nightmare if you do not. I hope that this will help you to do this in minutes instead!" }, { "code": null, "e": 7523, "s": 7180, "text": "Where do you go from here? Anywhere you want. The goal of this article was to quickly get you up and running with a new fancy resource manager for Spark. I suggest you play around with this setup with other Spark apps as the next steps — I might just write an article on some more complicated examples in the future (let me know if I should)." }, { "code": null, "e": 7549, "s": 7523, "text": "Have fun with Kubernetes!" }, { "code": null, "e": 7562, "s": 7549, "text": "Alternatives" }, { "code": null, "e": 7746, "s": 7562, "text": "This is an update from 20th April 2020 — one can also use Google’s native Kubernetes operator, which seems very promising and can remove the manual deployment steps into your cluster:" }, { "code": null, "e": 7757, "s": 7746, "text": "github.com" } ]
How to change the file owner and group in Linux?
To change the file owner and group, we use the chown command in the Linux operating system. We know that Linux is a multiuser operating system so every file or directory belongs to an owner and group. To change ownership of files or directories we use chown command in the Linux system. This command is also available in the IBM i operating system. The chgrp command is also used to change only the group ownership of the file in the Linux system. The general syntax of the chown command is as follows chown [OPTION]... [OWNER] [: [GROUP]] FILE... chown [OPTION]... --reference=RFILE FILE... A brief description of options available in the chown command - To check the ownership of a file in the Linux system, we use the ls -l command as shown below. $ ls -l <file name> To change ownership of a file in the Linux system we need to administrative permission or sudo privilege. The general syntax for changing ownership of a file is as follows: $ sudo chown <owner name> <file name> Here, we will change the ownership of a file ‘file.txt’ Vikash to Gautam using the chown command. First, we will check the ownership of ‘file.txt’ using the below command. vikash@tutorialspoint:~/shadow$ ls -l file.txt -rw-rw-r-- 1 vikash vikash 34 Jan 11 20:59 file.txt vikash@tutorialspoint:~/shadow$ We can see that the owner of ‘file.txt’ is vikash and the group ownership of the ‘file.txt’ is vikash. To change the ownership, we will execute command as shown below. vikash@tutorialspoint:~/shadow$ sudo chown gautam file.txt [sudo] password for vikash: vikash@tutorialspoint:~/shadow$ After changing the ownership of the file, we will again check again the ownership of files to ensure that ownership is changed or not. vikash@tutorialspoint:~/shadow$ ls -l file.txt -rw-rw-r-- 1 gautam vikash 34 Jan 11 20:59 file.txt vikash@tutorialspoint:~/shadow$ To check more information and available options in the chown command, we use the --help option with the chown command as follows: $ chown --help Conclusion: In this article, we learned to change the ownership of files using the chown command in the Linux operating system with available options and suitable examples. To change only the group ownership of the file, we use the chgrp command in the Linux system.
[ { "code": null, "e": 1154, "s": 1062, "text": "To change the file owner and group, we use the chown command in the Linux operating system." }, { "code": null, "e": 1263, "s": 1154, "text": "We know that Linux is a multiuser operating system so every file or directory belongs to an owner and group." }, { "code": null, "e": 1510, "s": 1263, "text": "To change ownership of files or directories we use chown command in the Linux system. This command is also available in the IBM i operating system. The chgrp command is also used to change only the group ownership of the file in the Linux system." }, { "code": null, "e": 1564, "s": 1510, "text": "The general syntax of the chown command is as follows" }, { "code": null, "e": 1654, "s": 1564, "text": "chown [OPTION]... [OWNER] [: [GROUP]] FILE...\nchown [OPTION]... --reference=RFILE FILE..." }, { "code": null, "e": 1718, "s": 1654, "text": "A brief description of options available in the chown command -" }, { "code": null, "e": 1813, "s": 1718, "text": "To check the ownership of a file in the Linux system, we use the ls -l command as shown below." }, { "code": null, "e": 1833, "s": 1813, "text": "$ ls -l <file name>" }, { "code": null, "e": 1939, "s": 1833, "text": "To change ownership of a file in the Linux system we need to administrative permission or sudo privilege." }, { "code": null, "e": 2006, "s": 1939, "text": "The general syntax for changing ownership of a file is as follows:" }, { "code": null, "e": 2044, "s": 2006, "text": "$ sudo chown <owner name> <file name>" }, { "code": null, "e": 2142, "s": 2044, "text": "Here, we will change the ownership of a file ‘file.txt’ Vikash to Gautam using the chown command." }, { "code": null, "e": 2216, "s": 2142, "text": "First, we will check the ownership of ‘file.txt’ using the below command." }, { "code": null, "e": 2347, "s": 2216, "text": "vikash@tutorialspoint:~/shadow$ ls -l file.txt\n-rw-rw-r-- 1 vikash vikash 34 Jan 11 20:59 file.txt\nvikash@tutorialspoint:~/shadow$" }, { "code": null, "e": 2515, "s": 2347, "text": "We can see that the owner of ‘file.txt’ is vikash and the group ownership of the ‘file.txt’ is vikash. To change the ownership, we will execute command as shown below." }, { "code": null, "e": 2634, "s": 2515, "text": "vikash@tutorialspoint:~/shadow$ sudo chown gautam file.txt\n[sudo] password for vikash:\nvikash@tutorialspoint:~/shadow$" }, { "code": null, "e": 2769, "s": 2634, "text": "After changing the ownership of the file, we will again check again the ownership of files to ensure that ownership is changed or not." }, { "code": null, "e": 2900, "s": 2769, "text": "vikash@tutorialspoint:~/shadow$ ls -l file.txt\n-rw-rw-r-- 1 gautam vikash 34 Jan 11 20:59 file.txt\nvikash@tutorialspoint:~/shadow$" }, { "code": null, "e": 3030, "s": 2900, "text": "To check more information and available options in the chown command, we use the --help option with the chown command as follows:" }, { "code": null, "e": 3045, "s": 3030, "text": "$ chown --help" }, { "code": null, "e": 3312, "s": 3045, "text": "Conclusion: In this article, we learned to change the ownership of files using the chown command in the Linux operating system with available options and suitable examples. To change only the group ownership of the file, we use the chgrp command in the Linux system." } ]
Running Selenium WebDriver python bindings in chrome.
We can run Selenium webdriver with Python bindings in Chrome. This can be done by downloading the chromedriver.exe file. Visit the link: https://chromedriver.chromium.org/downloads. There shall be links available for download for various chromedriver versions. Select the version which is compatible with the Chrome browser in the local system. Click on it. As the following page is navigated, select the zip file available for download for the operating system which is compatible with our local operating system. Once the zip file is downloaded, extract it and save the chromodriver.exe file at a location. To launch the Chrome, we have to add the statement from selenium import webdriver. Also, we must have a webdriver object created. With the help of this webdriver object we should be able to access the webdriver.Chrome(). The location of the chromedriver.exe is passed as a parameter to the Chrome class with the help of the property called the executable_path. from selenium import webdriver #path of chromedriver.exe driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") #launch browser driver.get ("https://www.tutorialspoint.com/index.htm") #close browser driver.close()
[ { "code": null, "e": 1323, "s": 1062, "text": "We can run Selenium webdriver with Python bindings in Chrome. This\ncan be done by downloading the chromedriver.exe file. Visit the link: https://chromedriver.chromium.org/downloads. There shall be links available\nfor download for various chromedriver versions." }, { "code": null, "e": 1577, "s": 1323, "text": "Select the version which is compatible with the Chrome browser in the local\nsystem. Click on it. As the following page is navigated, select the zip file available\nfor download for the operating system which is compatible with our local\noperating system." }, { "code": null, "e": 1801, "s": 1577, "text": "Once the zip file is downloaded, extract it and save the chromodriver.exe file at a location. To launch the Chrome, we have to add the statement from selenium\nimport webdriver. Also, we must have a webdriver object created." }, { "code": null, "e": 2032, "s": 1801, "text": "With the help of this webdriver object we should be able to access the webdriver.Chrome(). The location of the chromedriver.exe is passed as a parameter to the Chrome class with the help of the property called the executable_path." }, { "code": null, "e": 2258, "s": 2032, "text": "from selenium import webdriver\n#path of chromedriver.exe\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\n#launch browser\ndriver.get (\"https://www.tutorialspoint.com/index.htm\")\n#close browser\ndriver.close()" } ]
Escape a Large Maze Python
Suppose we have a grid, there are 1 million rows and 1 million columns, we also have one list of blocked cells. Now we will start at the source square and want to reach the target square. In each move, we can walk to a up, down, left, right adjacent square in the grid that isn't in the given list of blocked cells. We have to check whether it is possible to reach the target square through a sequence of moves or not. So, if the input is like blocked = [[0,1],[1,0]], source = [0,0], target = [0,3], then the output will be False To solve this, we will follow these steps − blocked := make a set of all blocked cells blocked := make a set of all blocked cells Define one method dfs(), this will take x, y, target and seen Define one method dfs(), this will take x, y, target and seen if (x,y) are not in range of grids or (x,y) is in blocked or (x,y) is in seen thenreturn false if (x,y) are not in range of grids or (x,y) is in blocked or (x,y) is in seen then return false return false add (x,y) into seen add (x,y) into seen if size of seen > 20000 or (x,y) is target, thenreturn true if size of seen > 20000 or (x,y) is target, then return true return true return dfs(x+1,y,target,seen) or dfs(x-1,y,target,seen) or dfs(x,y+1,target,seen) or dfs(x,y-1,target,seen) return dfs(x+1,y,target,seen) or dfs(x-1,y,target,seen) or dfs(x,y+1,target,seen) or dfs(x,y-1,target,seen) return dfs(source[0], source[1], target, empty set) and dfs(target[0], target[1], source, empty set) return dfs(source[0], source[1], target, empty set) and dfs(target[0], target[1], source, empty set) Let us see the following implementation to get better understanding − class Solution(object): def isEscapePossible(self, blocked, source, target): blocked = set(map(tuple, blocked)) def dfs(x, y, target, seen): if not (0 <= x < 10**6 and 0 <= y < 10**6) or (x, y) in blocked or (x, y) in seen: return False seen.add((x, y)) if len(seen) > 20000 or [x, y] == target: return True return dfs(x + 1, y, target, seen) or \ dfs(x - 1, y, target, seen) or \ dfs(x, y + 1, target, seen) or \ dfs(x, y - 1, target, seen) return dfs(source[0], source[1], target, set()) and dfs(target[0], target[1], source, set()) ob = Solution() print(ob.isEscapePossible([[0,1],[1,0]], [0,0], [0,3])) [[0,1],[1,0]], [0,0], [0,3] False
[ { "code": null, "e": 1378, "s": 1062, "text": "Suppose we have a grid, there are 1 million rows and 1 million columns, we also have one list of blocked cells. Now we will start at the source square and want to reach the target square. In each move, we can walk to a up, down, left, right adjacent square in the grid that isn't in the given list of blocked cells." }, { "code": null, "e": 1481, "s": 1378, "text": "We have to check whether it is possible to reach the target square through a sequence of moves or not." }, { "code": null, "e": 1593, "s": 1481, "text": "So, if the input is like blocked = [[0,1],[1,0]], source = [0,0], target = [0,3], then the output will be False" }, { "code": null, "e": 1637, "s": 1593, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1680, "s": 1637, "text": "blocked := make a set of all blocked cells" }, { "code": null, "e": 1723, "s": 1680, "text": "blocked := make a set of all blocked cells" }, { "code": null, "e": 1785, "s": 1723, "text": "Define one method dfs(), this will take x, y, target and seen" }, { "code": null, "e": 1847, "s": 1785, "text": "Define one method dfs(), this will take x, y, target and seen" }, { "code": null, "e": 1942, "s": 1847, "text": "if (x,y) are not in range of grids or (x,y) is in blocked or (x,y) is in seen thenreturn false" }, { "code": null, "e": 2025, "s": 1942, "text": "if (x,y) are not in range of grids or (x,y) is in blocked or (x,y) is in seen then" }, { "code": null, "e": 2038, "s": 2025, "text": "return false" }, { "code": null, "e": 2051, "s": 2038, "text": "return false" }, { "code": null, "e": 2071, "s": 2051, "text": "add (x,y) into seen" }, { "code": null, "e": 2091, "s": 2071, "text": "add (x,y) into seen" }, { "code": null, "e": 2151, "s": 2091, "text": "if size of seen > 20000 or (x,y) is target, thenreturn true" }, { "code": null, "e": 2200, "s": 2151, "text": "if size of seen > 20000 or (x,y) is target, then" }, { "code": null, "e": 2212, "s": 2200, "text": "return true" }, { "code": null, "e": 2224, "s": 2212, "text": "return true" }, { "code": null, "e": 2332, "s": 2224, "text": "return dfs(x+1,y,target,seen) or dfs(x-1,y,target,seen) or dfs(x,y+1,target,seen) or dfs(x,y-1,target,seen)" }, { "code": null, "e": 2440, "s": 2332, "text": "return dfs(x+1,y,target,seen) or dfs(x-1,y,target,seen) or dfs(x,y+1,target,seen) or dfs(x,y-1,target,seen)" }, { "code": null, "e": 2541, "s": 2440, "text": "return dfs(source[0], source[1], target, empty set) and dfs(target[0], target[1], source, empty set)" }, { "code": null, "e": 2642, "s": 2541, "text": "return dfs(source[0], source[1], target, empty set) and dfs(target[0], target[1], source, empty set)" }, { "code": null, "e": 2712, "s": 2642, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3427, "s": 2712, "text": "class Solution(object):\n def isEscapePossible(self, blocked, source, target):\n blocked = set(map(tuple, blocked))\n def dfs(x, y, target, seen):\n if not (0 <= x < 10**6 and 0 <= y < 10**6) or (x, y) in blocked or (x, y) in seen: return False\n seen.add((x, y))\n if len(seen) > 20000 or [x, y] == target: return True\n return dfs(x + 1, y, target, seen) or \\\n dfs(x - 1, y, target, seen) or \\\n dfs(x, y + 1, target, seen) or \\\n dfs(x, y - 1, target, seen)\n return dfs(source[0], source[1], target, set()) and\ndfs(target[0], target[1], source, set())\nob = Solution()\nprint(ob.isEscapePossible([[0,1],[1,0]], [0,0], [0,3]))" }, { "code": null, "e": 3455, "s": 3427, "text": "[[0,1],[1,0]], [0,0], [0,3]" }, { "code": null, "e": 3461, "s": 3455, "text": "False" } ]
Arrays asList() method in Java with Examples - GeeksforGeeks
24 Nov, 2021 The asList() method of java.util.Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess. Tip: This runs in O(1) time. Syntax: public static List asList(T... a) Parameters: This method takes the array a which is required to be converted into a List. Here ... is known as varargs which is an array of parameters and works similar to an object array parameter. Special Note: The type of array must be a Wrapper Class(Integer,Float, etc) in case of primitive data types(int, float,etc) , i.e you can’t pass int a[] but you can pass Integer a[]. If you pass int a[], this function will return a List <int a[]> and not List <Integer> , as “autoboxing” doesn’t happen in this case and int a[] is itself identified as an object and a List of int array is returned, instead of list of integers , which will give error in various Collection functions . Return Value: This method returns a list view of the specified array. Example 1: Java // Java program to Demonstrate asList() method// of Arrays class for a string value // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating Arrays of String type String a[] = new String[] { "A", "B", "C", "D" }; // Getting the list view of Array List<String> list = Arrays.asList(a); // Printing all the elements in list object System.out.println("The list is: " + list); } // Catch block to handle exceptions catch (NullPointerException e) { // Print statement System.out.println("Exception thrown : " + e); } }} The list is: [A, B, C, D] Example 2: Java // Java program to Demonstrate asList() method// of Arrays class For an integer value // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating Arrays of Integer type Integer a[] = new Integer[] { 10, 20, 30, 40 }; // Getting the list view of Array List<Integer> list = Arrays.asList(a); // Printing all the elements inside list object System.out.println("The list is: " + list); } // Catch block to handle exceptions catch (NullPointerException e) { // Print statements System.out.println("Exception thrown : " + e); } }} The list is: [10, 20, 30, 40] Example 3: Java // Java Program to demonstrate asList() method// Which returns fixed size list and// throws UnsupportedOperationException// if any element is added using add() method // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating Arrays of Integer type Integer a[] = new Integer[] { 10, 20, 30, 40 }; // Getting the list view of Array List<Integer> list = Arrays.asList(a); // Adding another int to the list // As Arrays.asList() returns fixed size // list, we'll get // java.lang.UnsupportedOperationException list.add(50); // Printing all the elements of list System.out.println("The list is: " + list); } // Catch block to handle exceptions catch (UnsupportedOperationException e) { // Display message when exception occurs System.out.println("Exception thrown : " + e); } }} Output: olympusx curiousno1 shivnagarsoge simmytarika5 Java - util package Java-Arrays Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Multidimensional Arrays in Java Stream In Java Stack Class in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 24962, "s": 24934, "text": "\n24 Nov, 2021" }, { "code": null, "e": 25256, "s": 24962, "text": "The asList() method of java.util.Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess." }, { "code": null, "e": 25286, "s": 25256, "text": "Tip: This runs in O(1) time. " }, { "code": null, "e": 25295, "s": 25286, "text": "Syntax: " }, { "code": null, "e": 25329, "s": 25295, "text": "public static List asList(T... a)" }, { "code": null, "e": 25528, "s": 25329, "text": "Parameters: This method takes the array a which is required to be converted into a List. Here ... is known as varargs which is an array of parameters and works similar to an object array parameter." }, { "code": null, "e": 26014, "s": 25528, "text": "Special Note: The type of array must be a Wrapper Class(Integer,Float, etc) in case of primitive data types(int, float,etc) , i.e you can’t pass int a[] but you can pass Integer a[]. If you pass int a[], this function will return a List <int a[]> and not List <Integer> , as “autoboxing” doesn’t happen in this case and int a[] is itself identified as an object and a List of int array is returned, instead of list of integers , which will give error in various Collection functions ." }, { "code": null, "e": 26084, "s": 26014, "text": "Return Value: This method returns a list view of the specified array." }, { "code": null, "e": 26095, "s": 26084, "text": "Example 1:" }, { "code": null, "e": 26100, "s": 26095, "text": "Java" }, { "code": "// Java program to Demonstrate asList() method// of Arrays class for a string value // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating Arrays of String type String a[] = new String[] { \"A\", \"B\", \"C\", \"D\" }; // Getting the list view of Array List<String> list = Arrays.asList(a); // Printing all the elements in list object System.out.println(\"The list is: \" + list); } // Catch block to handle exceptions catch (NullPointerException e) { // Print statement System.out.println(\"Exception thrown : \" + e); } }}", "e": 26937, "s": 26100, "text": null }, { "code": null, "e": 26963, "s": 26937, "text": "The list is: [A, B, C, D]" }, { "code": null, "e": 26975, "s": 26963, "text": " Example 2:" }, { "code": null, "e": 26980, "s": 26975, "text": "Java" }, { "code": "// Java program to Demonstrate asList() method// of Arrays class For an integer value // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating Arrays of Integer type Integer a[] = new Integer[] { 10, 20, 30, 40 }; // Getting the list view of Array List<Integer> list = Arrays.asList(a); // Printing all the elements inside list object System.out.println(\"The list is: \" + list); } // Catch block to handle exceptions catch (NullPointerException e) { // Print statements System.out.println(\"Exception thrown : \" + e); } }}", "e": 27808, "s": 26980, "text": null }, { "code": null, "e": 27838, "s": 27808, "text": "The list is: [10, 20, 30, 40]" }, { "code": null, "e": 27849, "s": 27838, "text": "Example 3:" }, { "code": null, "e": 27854, "s": 27849, "text": "Java" }, { "code": "// Java Program to demonstrate asList() method// Which returns fixed size list and// throws UnsupportedOperationException// if any element is added using add() method // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating Arrays of Integer type Integer a[] = new Integer[] { 10, 20, 30, 40 }; // Getting the list view of Array List<Integer> list = Arrays.asList(a); // Adding another int to the list // As Arrays.asList() returns fixed size // list, we'll get // java.lang.UnsupportedOperationException list.add(50); // Printing all the elements of list System.out.println(\"The list is: \" + list); } // Catch block to handle exceptions catch (UnsupportedOperationException e) { // Display message when exception occurs System.out.println(\"Exception thrown : \" + e); } }}", "e": 28990, "s": 27854, "text": null }, { "code": null, "e": 28998, "s": 28990, "text": "Output:" }, { "code": null, "e": 29007, "s": 28998, "text": "olympusx" }, { "code": null, "e": 29018, "s": 29007, "text": "curiousno1" }, { "code": null, "e": 29032, "s": 29018, "text": "shivnagarsoge" }, { "code": null, "e": 29045, "s": 29032, "text": "simmytarika5" }, { "code": null, "e": 29065, "s": 29045, "text": "Java - util package" }, { "code": null, "e": 29077, "s": 29065, "text": "Java-Arrays" }, { "code": null, "e": 29082, "s": 29077, "text": "Java" }, { "code": null, "e": 29087, "s": 29082, "text": "Java" }, { "code": null, "e": 29185, "s": 29087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29236, "s": 29185, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29266, "s": 29236, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29285, "s": 29266, "text": "Interfaces in Java" }, { "code": null, "e": 29316, "s": 29285, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29334, "s": 29316, "text": "ArrayList in Java" }, { "code": null, "e": 29366, "s": 29334, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29381, "s": 29366, "text": "Stream In Java" }, { "code": null, "e": 29401, "s": 29381, "text": "Stack Class in Java" }, { "code": null, "e": 29425, "s": 29401, "text": "Singleton Class in Java" } ]
How does parameters 'c' and 'cmap' behave in a Matplotlib scatter plot?
To get a sense of how the parameters c and cmap behave in a Matplotlib scatterplot, 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 x and y data points using scatter() method, color and colormap. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True N = 50 x = np.random.randn(N) y = np.random.randn(N) plt.scatter(x, y, c=x, cmap="plasma") plt.show()
[ { "code": null, "e": 1180, "s": 1062, "text": "To get a sense of how the parameters c and cmap behave in a Matplotlib scatterplot, we can take the following steps −" }, { "code": null, "e": 1256, "s": 1180, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1316, "s": 1256, "text": "Initialize a variable N to store the number of sample data." }, { "code": null, "e": 1356, "s": 1316, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1425, "s": 1356, "text": "Plot x and y data points using scatter() method, color and colormap." }, { "code": null, "e": 1467, "s": 1425, "text": "To display the figure, use show() method." }, { "code": null, "e": 1716, "s": 1467, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nN = 50\nx = np.random.randn(N)\ny = np.random.randn(N)\n\nplt.scatter(x, y, c=x, cmap=\"plasma\")\n\nplt.show()" } ]
Class getDeclaredField() method in Java with Examples - GeeksforGeeks
16 Dec, 2019 The getDeclaredField() method of java.lang.Class class is used to get the specified field of this class. The method returns the specified field of this class in the form of Field object. Syntax: public Field getDeclaredField(String fieldName) throws NoSuchMethodException, SecurityException Parameter: This method accepts a parameter fieldName which is the Field to get. Return Value: This method returns the specified field of this class in the form of Field objects. Exception This method throws: NoSuchFieldException if a field with the specified name is not found. NullPointerException if name is null SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredField() method.Example 1:// Java program to demonstrate// getDeclaredField() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); String fieldName = "obj"; // Get the field of myClass // using getDeclaredField() method System.out.println( fieldName + " Field of myClass: " + myClass.getDeclaredField(fieldName)); }}Output:Class represented by myClass: class Test obj Field of myClass: public java.lang.Object Test.obj Example 2:// Java program to demonstrate// getDeclaredField() method import java.util.*; class Main { private Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); String fieldName = "obj"; try { // Get the field of myClass // using getDeclaredField() method System.out.println( fieldName + " Field of myClass: " + myClass.getDeclaredField(fieldName)); } catch (Exception e) { System.out.println(e); } }}Output:Class represented by myClass: class Main obj Field of myClass: private java.lang.Object Main.obj Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredField-java.lang.String-My Personal Notes arrow_drop_upSave Below programs demonstrate the getDeclaredField() method. Example 1: // Java program to demonstrate// getDeclaredField() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); String fieldName = "obj"; // Get the field of myClass // using getDeclaredField() method System.out.println( fieldName + " Field of myClass: " + myClass.getDeclaredField(fieldName)); }} Class represented by myClass: class Test obj Field of myClass: public java.lang.Object Test.obj Example 2: // Java program to demonstrate// getDeclaredField() method import java.util.*; class Main { private Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); String fieldName = "obj"; try { // Get the field of myClass // using getDeclaredField() method System.out.println( fieldName + " Field of myClass: " + myClass.getDeclaredField(fieldName)); } catch (Exception e) { System.out.println(e); } }} Class represented by myClass: class Main obj Field of myClass: private java.lang.Object Main.obj Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredField-java.lang.String- Java-Functions Java-lang package Java.lang.Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n16 Dec, 2019" }, { "code": null, "e": 24135, "s": 23948, "text": "The getDeclaredField() method of java.lang.Class class is used to get the specified field of this class. The method returns the specified field of this class in the form of Field object." }, { "code": null, "e": 24143, "s": 24135, "text": "Syntax:" }, { "code": null, "e": 24261, "s": 24143, "text": "public Field getDeclaredField(String fieldName)\n throws NoSuchMethodException,\n SecurityException\n" }, { "code": null, "e": 24341, "s": 24261, "text": "Parameter: This method accepts a parameter fieldName which is the Field to get." }, { "code": null, "e": 24439, "s": 24341, "text": "Return Value: This method returns the specified field of this class in the form of Field objects." }, { "code": null, "e": 24469, "s": 24439, "text": "Exception This method throws:" }, { "code": null, "e": 24539, "s": 24469, "text": "NoSuchFieldException if a field with the specified name is not found." }, { "code": null, "e": 24576, "s": 24539, "text": "NullPointerException if name is null" }, { "code": null, "e": 26569, "s": 24576, "text": "SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredField() method.Example 1:// Java program to demonstrate// getDeclaredField() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String fieldName = \"obj\"; // Get the field of myClass // using getDeclaredField() method System.out.println( fieldName + \" Field of myClass: \" + myClass.getDeclaredField(fieldName)); }}Output:Class represented by myClass: class Test\nobj Field of myClass: public java.lang.Object Test.obj\nExample 2:// Java program to demonstrate// getDeclaredField() method import java.util.*; class Main { private Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String fieldName = \"obj\"; try { // Get the field of myClass // using getDeclaredField() method System.out.println( fieldName + \" Field of myClass: \" + myClass.getDeclaredField(fieldName)); } catch (Exception e) { System.out.println(e); } }}Output:Class represented by myClass: class Main\nobj Field of myClass: private java.lang.Object Main.obj\nReference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredField-java.lang.String-My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 26627, "s": 26569, "text": "Below programs demonstrate the getDeclaredField() method." }, { "code": null, "e": 26638, "s": 26627, "text": "Example 1:" }, { "code": "// Java program to demonstrate// getDeclaredField() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String fieldName = \"obj\"; // Get the field of myClass // using getDeclaredField() method System.out.println( fieldName + \" Field of myClass: \" + myClass.getDeclaredField(fieldName)); }}", "e": 27322, "s": 26638, "text": null }, { "code": null, "e": 27419, "s": 27322, "text": "Class represented by myClass: class Test\nobj Field of myClass: public java.lang.Object Test.obj\n" }, { "code": null, "e": 27430, "s": 27419, "text": "Example 2:" }, { "code": "// Java program to demonstrate// getDeclaredField() method import java.util.*; class Main { private Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String fieldName = \"obj\"; try { // Get the field of myClass // using getDeclaredField() method System.out.println( fieldName + \" Field of myClass: \" + myClass.getDeclaredField(fieldName)); } catch (Exception e) { System.out.println(e); } }}", "e": 28222, "s": 27430, "text": null }, { "code": null, "e": 28320, "s": 28222, "text": "Class represented by myClass: class Main\nobj Field of myClass: private java.lang.Object Main.obj\n" }, { "code": null, "e": 28429, "s": 28320, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredField-java.lang.String-" }, { "code": null, "e": 28444, "s": 28429, "text": "Java-Functions" }, { "code": null, "e": 28462, "s": 28444, "text": "Java-lang package" }, { "code": null, "e": 28478, "s": 28462, "text": "Java.lang.Class" }, { "code": null, "e": 28483, "s": 28478, "text": "Java" }, { "code": null, "e": 28488, "s": 28483, "text": "Java" }, { "code": null, "e": 28586, "s": 28488, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28601, "s": 28586, "text": "Stream In Java" }, { "code": null, "e": 28647, "s": 28601, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28668, "s": 28647, "text": "Constructors in Java" }, { "code": null, "e": 28687, "s": 28668, "text": "Exceptions in Java" }, { "code": null, "e": 28717, "s": 28687, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28734, "s": 28717, "text": "Generics in Java" }, { "code": null, "e": 28777, "s": 28734, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28806, "s": 28777, "text": "HashMap get() Method in Java" }, { "code": null, "e": 28827, "s": 28806, "text": "Introduction to Java" } ]
Bootstrap - Helper Classes
This chapter discusses some of the helper classes in Bootstrap that might come in handy. Use the generic close icon for dismissing content like modals and alerts. Use the class close to get the close icon. <p>Close Icon Example <button type = "button" class = "close" aria-hidden = "true"> &times; </button> </p> Close Icon Example × Use carets to indicate dropdown functionality and direction. To get this functionality use the class caret with a <span> element. <p>Caret Example<span class = "caret"></span></p> Caret Example You can float an element to the left or right with class pull-left or pull-right respectively the following example demonstrates this. <div class = "pull-left">Quick Float to left</div> <div class = "pull-right">Quick Float to right</div> Use class center-block to set an element to center. <div class = "row"> <div class = "center-block" style = "width:200px; background-color:#ccc;"> This is an example for center-block </div> </div> To clear the float of any element, use the .clearfix class. <div class = "clearfix" style = "background: #D8D8D8;border: 1px solid #000; padding: 10px;"> <div class = "pull-left" style = "background:#58D3F7;"> Quick Float to left </div> <div class = "pull-right" style = "background: #DA81F5;"> Quick Float to right </div> </div> You can force an element to be shown or hidden (including for screen readers) with the use of classes .show and .hidden. <div class = "row" style = "padding: 91px 100px 19px 50px;"> <div class = "show" style = "left-margin:10px; width:300px; background-color:#ccc;"> This is an example for show class </div> <div class = "hidden" style = "width:200px; background-color:#ccc;"> This is an example for hide class </div> </div> You can hide an element to all devices except screen readers with the class .sr-only. <div class = "row" style = "padding: 91px 100px 19px 50px;"> <form class = "form-inline" role = "form"> <div class = "form-group"> <label class = "sr-only" for = "email">Email address</label> <input type = "email" class = "form-control" placeholder = "Enter email"> </div> <div class = "form-group"> <label class = "sr-only" for = "pass">Password</label> <input type = "password" class = "form-control" placeholder = "Password"> </div> </form> </div> Here we can see that the label of both the input types is assigned the class sr-only, hence labels will be visible to only screen readers. 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3420, "s": 3331, "text": "This chapter discusses some of the helper classes in Bootstrap that might come in handy." }, { "code": null, "e": 3537, "s": 3420, "text": "Use the generic close icon for dismissing content like modals and alerts. Use the class close to get the close icon." }, { "code": null, "e": 3656, "s": 3537, "text": "<p>Close Icon Example\n <button type = \"button\" class = \"close\" aria-hidden = \"true\">\n &times;\n </button>\n</p>" }, { "code": null, "e": 3710, "s": 3656, "text": "Close Icon Example\n \n ×\n \n" }, { "code": null, "e": 3840, "s": 3710, "text": "Use carets to indicate dropdown functionality and direction. To get this functionality use the class caret with a <span> element." }, { "code": null, "e": 3890, "s": 3840, "text": "<p>Caret Example<span class = \"caret\"></span></p>" }, { "code": null, "e": 3904, "s": 3890, "text": "Caret Example" }, { "code": null, "e": 4039, "s": 3904, "text": "You can float an element to the left or right with class pull-left or pull-right respectively the following example demonstrates this." }, { "code": null, "e": 4143, "s": 4039, "text": "<div class = \"pull-left\">Quick Float to left</div>\n<div class = \"pull-right\">Quick Float to right</div>" }, { "code": null, "e": 4195, "s": 4143, "text": "Use class center-block to set an element to center." }, { "code": null, "e": 4352, "s": 4195, "text": "<div class = \"row\">\n <div class = \"center-block\" style = \"width:200px; background-color:#ccc;\">\n This is an example for center-block\n </div>\n</div>" }, { "code": null, "e": 4412, "s": 4352, "text": "To clear the float of any element, use the .clearfix class." }, { "code": null, "e": 4719, "s": 4412, "text": "\n<div class = \"clearfix\" style = \"background: #D8D8D8;border: 1px solid #000; padding: 10px;\">\n \n <div class = \"pull-left\" style = \"background:#58D3F7;\">\n Quick Float to left\n </div>\n \n <div class = \"pull-right\" style = \"background: #DA81F5;\">\n Quick Float to right\n </div>\n \n</div>" }, { "code": null, "e": 4840, "s": 4719, "text": "You can force an element to be shown or hidden (including for screen readers) with the use of classes .show and .hidden." }, { "code": null, "e": 5180, "s": 4840, "text": "<div class = \"row\" style = \"padding: 91px 100px 19px 50px;\">\n \n <div class = \"show\" style = \"left-margin:10px; width:300px; background-color:#ccc;\">\n This is an example for show class\n </div>\n \n <div class = \"hidden\" style = \"width:200px; background-color:#ccc;\">\n This is an example for hide class\n </div>\n \n</div>" }, { "code": null, "e": 5266, "s": 5180, "text": "You can hide an element to all devices except screen readers with the class .sr-only." }, { "code": null, "e": 5804, "s": 5266, "text": "<div class = \"row\" style = \"padding: 91px 100px 19px 50px;\">\n <form class = \"form-inline\" role = \"form\">\n \n <div class = \"form-group\">\n <label class = \"sr-only\" for = \"email\">Email address</label>\n <input type = \"email\" class = \"form-control\" placeholder = \"Enter email\">\n </div>\n \n <div class = \"form-group\">\n <label class = \"sr-only\" for = \"pass\">Password</label>\n <input type = \"password\" class = \"form-control\" placeholder = \"Password\">\n </div>\n \n </form>\n</div>" }, { "code": null, "e": 5943, "s": 5804, "text": "Here we can see that the label of both the input types is assigned the class sr-only, hence labels will be visible to only screen readers." }, { "code": null, "e": 5976, "s": 5943, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 5990, "s": 5976, "text": " Anadi Sharma" }, { "code": null, "e": 6025, "s": 5990, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6042, "s": 6025, "text": " Frahaan Hussain" }, { "code": null, "e": 6079, "s": 6042, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 6107, "s": 6079, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6140, "s": 6107, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 6152, "s": 6140, "text": " Azaz Patel" }, { "code": null, "e": 6187, "s": 6152, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6204, "s": 6187, "text": " Muhammad Ismail" }, { "code": null, "e": 6237, "s": 6204, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 6257, "s": 6237, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 6264, "s": 6257, "text": " Print" }, { "code": null, "e": 6275, "s": 6264, "text": " Add Notes" } ]
Using Lambda Function with Amazon S3
Amazon S3 service is used for file storage, where you can upload or remove files. We can trigger AWS Lambda on S3 when there are any file uploads in S3 buckets. AWS Lambda has a handler function which acts as a start point for AWS Lambda function. The handler has the details of the events. In this chapter, let us see how to use AWS S3 to trigger AWS Lambda function when we upload files in S3 bucket. To start using AWS Lambda with Amazon S3, we need the following − Create S3 Bucket Create role which has permission to work with s3 and lambda Create lambda function and add s3 as the trigger. Let us see these steps with the help of an example which shows the basic interaction between Amazon S3 and AWS Lambda. User will upload a file in Amazon S3 bucket User will upload a file in Amazon S3 bucket Once the file is uploaded, it will trigger AWS Lambda function in the background which will display an output in the form of a console message that the file is uploaded. Once the file is uploaded, it will trigger AWS Lambda function in the background which will display an output in the form of a console message that the file is uploaded. The user will be able to see the message in Cloudwatch logs once the file is uploaded. The user will be able to see the message in Cloudwatch logs once the file is uploaded. The block diagram that explains the flow of the example is shown here − Let us start first by creating a s3 bucket in AWS console using the steps given below − Go to Amazon services and click S3 in storage section as highlighted in the image given below − Click S3 storage and Create bucket which will store the files uploaded. Once you click Create bucket button, you can see a screen as follows − Enter the details Bucket name, Select the Region and click Create button at the bottom left side. Thus, we have created bucket with name : workingwithlambdaands3. Now, click the bucket name and it will ask you to upload files as shown below − Thus, we are done with bucket creation in S3. To create role that works with S3 and Lambda, please follow the Steps given below − Go to AWS services and select IAM as shown below − Now, click IAM -> Roles as shown below − Now, click Create role and choose the services that will use this role. Select Lambda and click Permission button. Add the permission from below and click Review. Observe that we have chosen the following permissions − Observe that the Policies that we have selected are AmazonS3FullAccess, AWSLambdaFullAccess and CloudWatchFullAccess. Now, enter the Role name, Role description and click Create Role button at the bottom. Thus, our role named lambdawiths3service is created. In this section, let us see how to create a Lambda function and add a S3 trigger to it. For this purpose, you will have to follow th Steps given below − Go to AWS Services and select Lambda as shown below − Click Lambda and follow the process for adding Name. Choose the Runtime, Role etc. and create the function. The Lambda function that we have created is shown in the screenshot below − Now let us add the S3 trigger. Choose the trigger from above and add the details as shown below − Select the bucket created from bucket dropdown. The event type has following details − Select Object Created (All), as we need AWS Lambda trigger when file is uploaded, removed etc. You can add Prefix and File pattern which are used to filter the files added. For Example, to trigger lambda only for .jpg images. Let us keep it blank for now as we need to trigger Lambda for all files uploaded. Click Add button to add the trigger. You can find the the trigger display for the Lambda function as shown below − Let’s add the details for the aws lambda function. Here, we will use the online editor to add our code and use nodejs as the runtime environment. To trigger S3 with AWS Lambda, we will have to use S3 event in the code as shown below − exports.handler = function(event, context, callback) { console.log("Incoming Event: ", event); const bucket = event.Records[0].s3.bucket.name; const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const message = `File is uploaded in - ${bucket} -> ${filename}`; console.log(message); callback(null, message); }; Note that the event param has the details of the S3event. We have consoled the bucket name and the file name which will get logged when you upload image in S3bucket. Now, let us save the changes and test the lambda function with S3upload. The following are the code details added in AWS Lambda − Now, let us add the role, memory and timeout. Now, save the Lambda function. Open S3 from Amazon services and open the bucket we created earlier namely workingwithlambdaands3. Upload the image in it as shown below − Click Upload button to add files as shown − Click Add files to add files. You can also drag and drop the files. Now, click Upload button. Thus, we have uploaded one image in our S3 bucket. To see the trigger details, go to AWS service and select CloudWatch. Open the logs for the Lambda function and use the following code − exports.handler = function(event, context, callback) { console.log("Incoming Event: ", event); const bucket = event.Records[0].s3.bucket.name; const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const message = `File is uploaded in - ${bucket} -> ${filename}`; console.log(message); callback(null, message); }; The output you can observe in Cloudwatch is as shown − AWS Lambda function gets triggered when file is uploaded in S3 bucket and the details are logged in Cloudwatch as shown below − 35 Lectures 7.5 hours Mr. Pradeep Kshetrapal 30 Lectures 3.5 hours Priyanka Choudhary 44 Lectures 7.5 hours Eduonix Learning Solutions 51 Lectures 6 hours Manuj Aggarwal 41 Lectures 5 hours AR Shankar 14 Lectures 1 hours Zach Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2809, "s": 2406, "text": "Amazon S3 service is used for file storage, where you can upload or remove files. We can trigger AWS Lambda on S3 when there are any file uploads in S3 buckets. AWS Lambda has a handler function which acts as a start point for AWS Lambda function. The handler has the details of the events. In this chapter, let us see how to use AWS S3 to trigger AWS Lambda function when we upload files in S3 bucket." }, { "code": null, "e": 2875, "s": 2809, "text": "To start using AWS Lambda with Amazon S3, we need the following −" }, { "code": null, "e": 2892, "s": 2875, "text": "Create S3 Bucket" }, { "code": null, "e": 2952, "s": 2892, "text": "Create role which has permission to work with s3 and lambda" }, { "code": null, "e": 3002, "s": 2952, "text": "Create lambda function and add s3 as the trigger." }, { "code": null, "e": 3121, "s": 3002, "text": "Let us see these steps with the help of an example which shows the basic interaction between Amazon S3 and AWS Lambda." }, { "code": null, "e": 3165, "s": 3121, "text": "User will upload a file in Amazon S3 bucket" }, { "code": null, "e": 3209, "s": 3165, "text": "User will upload a file in Amazon S3 bucket" }, { "code": null, "e": 3379, "s": 3209, "text": "Once the file is uploaded, it will trigger AWS Lambda function in the background which will display an output in the form of a console message that the file is uploaded." }, { "code": null, "e": 3549, "s": 3379, "text": "Once the file is uploaded, it will trigger AWS Lambda function in the background which will display an output in the form of a console message that the file is uploaded." }, { "code": null, "e": 3636, "s": 3549, "text": "The user will be able to see the message in Cloudwatch logs once the file is uploaded." }, { "code": null, "e": 3723, "s": 3636, "text": "The user will be able to see the message in Cloudwatch logs once the file is uploaded." }, { "code": null, "e": 3795, "s": 3723, "text": "The block diagram that explains the flow of the example is shown here −" }, { "code": null, "e": 3883, "s": 3795, "text": "Let us start first by creating a s3 bucket in AWS console using the steps given below −" }, { "code": null, "e": 3979, "s": 3883, "text": "Go to Amazon services and click S3 in storage section as highlighted in the image given below −" }, { "code": null, "e": 4051, "s": 3979, "text": "Click S3 storage and Create bucket which will store the files uploaded." }, { "code": null, "e": 4122, "s": 4051, "text": "Once you click Create bucket button, you can see a screen as follows −" }, { "code": null, "e": 4285, "s": 4122, "text": "Enter the details Bucket name, Select the Region and click Create button at the bottom left side. Thus, we have created bucket with name : workingwithlambdaands3." }, { "code": null, "e": 4365, "s": 4285, "text": "Now, click the bucket name and it will ask you to upload files as shown below −" }, { "code": null, "e": 4411, "s": 4365, "text": "Thus, we are done with bucket creation in S3." }, { "code": null, "e": 4495, "s": 4411, "text": "To create role that works with S3 and Lambda, please follow the Steps given below −" }, { "code": null, "e": 4546, "s": 4495, "text": "Go to AWS services and select IAM as shown below −" }, { "code": null, "e": 4587, "s": 4546, "text": "Now, click IAM -> Roles as shown below −" }, { "code": null, "e": 4702, "s": 4587, "text": "Now, click Create role and choose the services that will use this role. Select Lambda and click Permission button." }, { "code": null, "e": 4750, "s": 4702, "text": "Add the permission from below and click Review." }, { "code": null, "e": 4806, "s": 4750, "text": "Observe that we have chosen the following permissions −" }, { "code": null, "e": 4924, "s": 4806, "text": "Observe that the Policies that we have selected are AmazonS3FullAccess, AWSLambdaFullAccess and CloudWatchFullAccess." }, { "code": null, "e": 5011, "s": 4924, "text": "Now, enter the Role name, Role description and click Create Role button at the bottom." }, { "code": null, "e": 5064, "s": 5011, "text": "Thus, our role named lambdawiths3service is created." }, { "code": null, "e": 5217, "s": 5064, "text": "In this section, let us see how to create a Lambda function and add a S3 trigger to it. For this purpose, you will have to follow th Steps given below −" }, { "code": null, "e": 5271, "s": 5217, "text": "Go to AWS Services and select Lambda as shown below −" }, { "code": null, "e": 5455, "s": 5271, "text": "Click Lambda and follow the process for adding Name. Choose the Runtime, Role etc. and create the function. The Lambda function that we have created is shown in the screenshot below −" }, { "code": null, "e": 5486, "s": 5455, "text": "Now let us add the S3 trigger." }, { "code": null, "e": 5553, "s": 5486, "text": "Choose the trigger from above and add the details as shown below −" }, { "code": null, "e": 5640, "s": 5553, "text": "Select the bucket created from bucket dropdown. The event type has following details −" }, { "code": null, "e": 5735, "s": 5640, "text": "Select Object Created (All), as we need AWS Lambda trigger when file is uploaded, removed etc." }, { "code": null, "e": 5985, "s": 5735, "text": "You can add Prefix and File pattern which are used to filter the files added. For Example, to trigger lambda only for .jpg images. Let us keep it blank for now as we need to trigger Lambda for all files uploaded. Click Add button to add the trigger." }, { "code": null, "e": 6063, "s": 5985, "text": "You can find the the trigger display for the Lambda function as shown below −" }, { "code": null, "e": 6209, "s": 6063, "text": "Let’s add the details for the aws lambda function. Here, we will use the online editor to add our code and use nodejs as the runtime environment." }, { "code": null, "e": 6298, "s": 6209, "text": "To trigger S3 with AWS Lambda, we will have to use S3 event in the code as shown below −" }, { "code": null, "e": 6664, "s": 6298, "text": "exports.handler = function(event, context, callback) {\n console.log(\"Incoming Event: \", event);\n const bucket = event.Records[0].s3.bucket.name;\n const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/\\+/g, ' '));\n const message = `File is uploaded in - ${bucket} -> ${filename}`;\n console.log(message);\n callback(null, message);\n};" }, { "code": null, "e": 6830, "s": 6664, "text": "Note that the event param has the details of the S3event. We have consoled the bucket name and the file name which will get logged when you upload image in S3bucket." }, { "code": null, "e": 6960, "s": 6830, "text": "Now, let us save the changes and test the lambda function with S3upload. The following are the code details added in AWS Lambda −" }, { "code": null, "e": 7006, "s": 6960, "text": "Now, let us add the role, memory and timeout." }, { "code": null, "e": 7136, "s": 7006, "text": "Now, save the Lambda function. Open S3 from Amazon services and open the bucket we created earlier namely workingwithlambdaands3." }, { "code": null, "e": 7176, "s": 7136, "text": "Upload the image in it as shown below −" }, { "code": null, "e": 7220, "s": 7176, "text": "Click Upload button to add files as shown −" }, { "code": null, "e": 7314, "s": 7220, "text": "Click Add files to add files. You can also drag and drop the files. Now, click Upload button." }, { "code": null, "e": 7365, "s": 7314, "text": "Thus, we have uploaded one image in our S3 bucket." }, { "code": null, "e": 7501, "s": 7365, "text": "To see the trigger details, go to AWS service and select CloudWatch. Open the logs for the Lambda function and use the following code −" }, { "code": null, "e": 7867, "s": 7501, "text": "exports.handler = function(event, context, callback) {\n console.log(\"Incoming Event: \", event);\n const bucket = event.Records[0].s3.bucket.name;\n const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/\\+/g, ' '));\n const message = `File is uploaded in - ${bucket} -> ${filename}`;\n console.log(message);\n callback(null, message);\n};" }, { "code": null, "e": 7922, "s": 7867, "text": "The output you can observe in Cloudwatch is as shown −" }, { "code": null, "e": 8050, "s": 7922, "text": "AWS Lambda function gets triggered when file is uploaded in S3 bucket and the details are logged in Cloudwatch as shown below −" }, { "code": null, "e": 8085, "s": 8050, "text": "\n 35 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8109, "s": 8085, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 8144, "s": 8109, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8164, "s": 8144, "text": " Priyanka Choudhary" }, { "code": null, "e": 8199, "s": 8164, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8227, "s": 8199, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8260, "s": 8227, "text": "\n 51 Lectures \n 6 hours \n" }, { "code": null, "e": 8276, "s": 8260, "text": " Manuj Aggarwal" }, { "code": null, "e": 8309, "s": 8276, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 8321, "s": 8309, "text": " AR Shankar" }, { "code": null, "e": 8354, "s": 8321, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8367, "s": 8354, "text": " Zach Miller" }, { "code": null, "e": 8374, "s": 8367, "text": " Print" }, { "code": null, "e": 8385, "s": 8374, "text": " Add Notes" } ]
memset() in C with examples - GeeksforGeeks
28 Jun, 2021 memset() is used to fill a block of memory with a particular value.The syntax of memset() function is as follows : // ptr ==> Starting address of memory to be filled // x ==> Value to be filled // n ==> Number of bytes to be filled starting // from ptr to be filled void *memset(void *ptr, int x, size_t n); Note that ptr is a void pointer, so that we can pass any type of pointer to this function. Let us see a simple example in C to demonstrate how memset() function is used: // C program to demonstrate working of memset()#include <stdio.h>#include <string.h> int main(){ char str[50] = "GeeksForGeeks is for programming geeks."; printf("\nBefore memset(): %s\n", str); // Fill 8 characters starting from str[13] with '.' memset(str + 13, '.', 8*sizeof(char)); printf("After memset(): %s", str); return 0;} Output: Before memset(): GeeksForGeeks is for programming geeks. After memset(): GeeksForGeeks........programming geeks. Explanation: (str + 13) points to first space (0 based index) of the string “GeeksForGeeks is for programming geeks.”, and memset() sets the character ‘.’ starting from first ‘ ‘ of the string up to 8 character positions of the given string and hence we get the output as shown above. // C program to demonstrate working of memset()#include <stdio.h>#include <string.h> void printArray(int arr[], int n){ for (int i=0; i<n; i++) printf("%d ", arr[i]);} int main(){ int n = 10; int arr[n]; // Fill whole array with 0. memset(arr, 0, n*sizeof(arr[0])); printf("Array after memset()\n"); printArray(arr, n); return 0;} Output: 0 0 0 0 0 0 0 0 0 0 Exercise :Predict the output of below program. // C program to demonstrate working of memset()#include <stdio.h>#include <string.h> void printArray(int arr[], int n){ for (int i=0; i<n; i++) printf("%d ", arr[i]);} int main(){ int n = 10; int arr[n]; // Fill whole array with 100. memset(arr, 10, n*sizeof(arr[0])); printf("Array after memset()\n"); printArray(arr, n); return 0;} Note that the above code doesn’t set array values to 10 as memset works character by character and an integer contains more than one bytes (or characters). However, if we replace 10 with -1, we get -1 values. Because representation of -1 contains all 1s in case of both char and int. Reference: memset man page (linux) This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. abhnv CPP-Library C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Object Oriented Programming in C++
[ { "code": null, "e": 25571, "s": 25543, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25686, "s": 25571, "text": "memset() is used to fill a block of memory with a particular value.The syntax of memset() function is as follows :" }, { "code": null, "e": 25893, "s": 25686, "text": "// ptr ==> Starting address of memory to be filled\n// x ==> Value to be filled\n// n ==> Number of bytes to be filled starting \n// from ptr to be filled\nvoid *memset(void *ptr, int x, size_t n);\n" }, { "code": null, "e": 25984, "s": 25893, "text": "Note that ptr is a void pointer, so that we can pass any type of pointer to this function." }, { "code": null, "e": 26063, "s": 25984, "text": "Let us see a simple example in C to demonstrate how memset() function is used:" }, { "code": "// C program to demonstrate working of memset()#include <stdio.h>#include <string.h> int main(){ char str[50] = \"GeeksForGeeks is for programming geeks.\"; printf(\"\\nBefore memset(): %s\\n\", str); // Fill 8 characters starting from str[13] with '.' memset(str + 13, '.', 8*sizeof(char)); printf(\"After memset(): %s\", str); return 0;}", "e": 26419, "s": 26063, "text": null }, { "code": null, "e": 26427, "s": 26419, "text": "Output:" }, { "code": null, "e": 26541, "s": 26427, "text": "Before memset(): GeeksForGeeks is for programming geeks.\nAfter memset(): GeeksForGeeks........programming geeks.\n" }, { "code": null, "e": 26826, "s": 26541, "text": "Explanation: (str + 13) points to first space (0 based index) of the string “GeeksForGeeks is for programming geeks.”, and memset() sets the character ‘.’ starting from first ‘ ‘ of the string up to 8 character positions of the given string and hence we get the output as shown above." }, { "code": "// C program to demonstrate working of memset()#include <stdio.h>#include <string.h> void printArray(int arr[], int n){ for (int i=0; i<n; i++) printf(\"%d \", arr[i]);} int main(){ int n = 10; int arr[n]; // Fill whole array with 0. memset(arr, 0, n*sizeof(arr[0])); printf(\"Array after memset()\\n\"); printArray(arr, n); return 0;}", "e": 27191, "s": 26826, "text": null }, { "code": null, "e": 27199, "s": 27191, "text": "Output:" }, { "code": null, "e": 27219, "s": 27199, "text": "0 0 0 0 0 0 0 0 0 0" }, { "code": null, "e": 27266, "s": 27219, "text": "Exercise :Predict the output of below program." }, { "code": "// C program to demonstrate working of memset()#include <stdio.h>#include <string.h> void printArray(int arr[], int n){ for (int i=0; i<n; i++) printf(\"%d \", arr[i]);} int main(){ int n = 10; int arr[n]; // Fill whole array with 100. memset(arr, 10, n*sizeof(arr[0])); printf(\"Array after memset()\\n\"); printArray(arr, n); return 0;}", "e": 27634, "s": 27266, "text": null }, { "code": null, "e": 27790, "s": 27634, "text": "Note that the above code doesn’t set array values to 10 as memset works character by character and an integer contains more than one bytes (or characters)." }, { "code": null, "e": 27918, "s": 27790, "text": "However, if we replace 10 with -1, we get -1 values. Because representation of -1 contains all 1s in case of both char and int." }, { "code": null, "e": 27953, "s": 27918, "text": "Reference: memset man page (linux)" }, { "code": null, "e": 28253, "s": 27953, "text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28378, "s": 28253, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28384, "s": 28378, "text": "abhnv" }, { "code": null, "e": 28396, "s": 28384, "text": "CPP-Library" }, { "code": null, "e": 28400, "s": 28396, "text": "C++" }, { "code": null, "e": 28404, "s": 28400, "text": "CPP" }, { "code": null, "e": 28502, "s": 28404, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28521, "s": 28502, "text": "Inheritance in C++" }, { "code": null, "e": 28564, "s": 28521, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 28588, "s": 28564, "text": "C++ Classes and Objects" }, { "code": null, "e": 28615, "s": 28588, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 28639, "s": 28615, "text": "Virtual Function in C++" }, { "code": null, "e": 28670, "s": 28639, "text": "Templates in C++ with Examples" }, { "code": null, "e": 28690, "s": 28670, "text": "Constructors in C++" }, { "code": null, "e": 28718, "s": 28690, "text": "Operator Overloading in C++" }, { "code": null, "e": 28746, "s": 28718, "text": "Socket Programming in C/C++" } ]
How to install Librosa Library in Python? - GeeksforGeeks
06 Oct, 2021 Librosa is a Python package for music and audio analysis. Librosa is basically used when we work with audio data like in music generation(using LSTM’s), Automatic Speech Recognition. It provides the building blocks necessary to create the music information retrieval systems. Librosa helps to visualize the audio signals and also do the feature extractions in it using different signal processing techniques. Using PyPI(Python Package Index)Open the command prompt on your system and write any one of them.pip install librosa sudo pip install librosa pip install -u librosa Open the command prompt on your system and write any one of them. pip install librosa sudo pip install librosa pip install -u librosa Conda InstallIf you use conda/Anaconda environments, librosa can be installed from the conda-forge channel. Open the Anaconda prompt and write:conda install -c conda-forge librosaNote: If you’re using a Python 3.5 environment in conda, you may run into trouble with the numba dependency. This can be avoided by installing from the numba conda channel before installing librosa:conda install -c numba numba If you use conda/Anaconda environments, librosa can be installed from the conda-forge channel. Open the Anaconda prompt and write: conda install -c conda-forge librosa Note: If you’re using a Python 3.5 environment in conda, you may run into trouble with the numba dependency. This can be avoided by installing from the numba conda channel before installing librosa: conda install -c numba numba how-to-install python-modules How To Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Align Text in HTML? How to Install OpenCV for Python on Windows? How to filter object array based on attributes? Java Tutorial How to Install FFmpeg on Windows? Installation of Node.js on Linux How to Install OpenCV for Python on Windows? How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Install and Run Apache Kafka on Windows?
[ { "code": null, "e": 26143, "s": 26115, "text": "\n06 Oct, 2021" }, { "code": null, "e": 26326, "s": 26143, "text": "Librosa is a Python package for music and audio analysis. Librosa is basically used when we work with audio data like in music generation(using LSTM’s), Automatic Speech Recognition." }, { "code": null, "e": 26552, "s": 26326, "text": "It provides the building blocks necessary to create the music information retrieval systems. Librosa helps to visualize the audio signals and also do the feature extractions in it using different signal processing techniques." }, { "code": null, "e": 26718, "s": 26552, "text": "Using PyPI(Python Package Index)Open the command prompt on your system and write any one of them.pip install librosa \nsudo pip install librosa\npip install -u librosa" }, { "code": null, "e": 26784, "s": 26718, "text": "Open the command prompt on your system and write any one of them." }, { "code": null, "e": 26853, "s": 26784, "text": "pip install librosa \nsudo pip install librosa\npip install -u librosa" }, { "code": null, "e": 27259, "s": 26853, "text": "Conda InstallIf you use conda/Anaconda environments, librosa can be installed from the conda-forge channel. Open the Anaconda prompt and write:conda install -c conda-forge librosaNote: If you’re using a Python 3.5 environment in conda, you may run into trouble with the numba dependency. This can be avoided by installing from the numba conda channel before installing librosa:conda install -c numba numba" }, { "code": null, "e": 27390, "s": 27259, "text": "If you use conda/Anaconda environments, librosa can be installed from the conda-forge channel. Open the Anaconda prompt and write:" }, { "code": null, "e": 27427, "s": 27390, "text": "conda install -c conda-forge librosa" }, { "code": null, "e": 27626, "s": 27427, "text": "Note: If you’re using a Python 3.5 environment in conda, you may run into trouble with the numba dependency. This can be avoided by installing from the numba conda channel before installing librosa:" }, { "code": null, "e": 27655, "s": 27626, "text": "conda install -c numba numba" }, { "code": null, "e": 27670, "s": 27655, "text": "how-to-install" }, { "code": null, "e": 27685, "s": 27670, "text": "python-modules" }, { "code": null, "e": 27692, "s": 27685, "text": "How To" }, { "code": null, "e": 27711, "s": 27692, "text": "Installation Guide" }, { "code": null, "e": 27718, "s": 27711, "text": "Python" }, { "code": null, "e": 27816, "s": 27718, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27843, "s": 27816, "text": "How to Align Text in HTML?" }, { "code": null, "e": 27888, "s": 27843, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 27936, "s": 27888, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27950, "s": 27936, "text": "Java Tutorial" }, { "code": null, "e": 27984, "s": 27950, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28017, "s": 27984, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28062, "s": 28017, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 28096, "s": 28062, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28131, "s": 28096, "text": "How to Install Pygame on Windows ?" } ]
withContext in Kotlin Coroutines - GeeksforGeeks
14 Sep, 2020 Prerequisite: Kotlin Coroutines on Android Launch vs Async in Kotlin Coroutines It is known that async and launch are the two ways to start the coroutine. Since It is known that async is used to get the result back, & should be used only when we need the parallel execution, whereas the launch is used when we do not want to get the result back and is used for the operation such as updating of data, etc. As we know that async is the only way till now to start the coroutine and get the result back, but the problem with async arises when we do not want to make parallel network calls. It is known when async is used, one needs to use the await() function, which leads to blocking of the main thread, but here comes the concept of withContext which removes the problem of blocking the main thread. withContext is nothing but another way of writing the async where one does not have to write await(). When withContext, is used, it runs the tasks in series instead of parallel. So one should remember that when we have a single task in the background and want to get back the result of that task, we should use withContext. Let us take an example which demonstrates the working of the withContext: Kotlin // two kotlin suspend functions// Suppose we have two tasks like below private suspend fun doTaskOne(): String{ delay(2000) return "One"} private suspend fun doTaskTwo(): String{ delay(2000) return "Two"} Let’s run the two tasks in parallel using async-await and then using withcontext and see the difference between the two. Kotlin // kotlin function using asyncfun startLongRunningTaskInParallel() { viewModelScope.launch { val resultOneDeferred = async { TaskOne() } val resultTwoDeferred = async { TaskTwo() } val combinedResult = resultOneDeferred.await() + resultTwoDeferred.await() }} Here using async, both the task run in parallel. Now let’s use the withContext and do the same task in series with withContext. Kotlin // kotlin function using withContextfun startLongRunningTaskInParallel() { viewModelScope.launch { val resultOne = withContext(Dispatchers.IO) { TaskOne() } val resultTwo = withContext(Dispatchers.IO) { TaskTwo() } val combinedResult = resultOne + resultTwo }} Here one can see that in withContext everything is the same, the only difference is that here we do not have to use the await() function, and tasks are executed in a serial manner. Since here multiple tasks have been taken, one should remember that async should be used with multiple tasks and withContext should be used with a single task. Now let’s take an example and try to understand withContext in detail and how it is executed. Kotlin // sample kotlin program for complete // demonstration of withContextfun testWithContext { var resultOne = "GFG" var resultTwo = "Is Best" Log.i("withContext", "Before") resultOne = withContext(Dispatchers.IO) { function1() } resultTwo = withContext(Dispatchers.IO) { function2() } Log.i("withContext", "After") val resultText = resultOne + resultTwo Log.i("withContext", resultText)} suspend fun function1(): String{ delay(1000L) val message = "function1" Log.i("withContext", message) return message} suspend fun function2(): String { delay(100L) val message = "function2" Log.i("withContext", message) return message} function 2 executes faster than function 1 since function 2 has less delay then function 1. Since withContext is a suspend call, that is it won’t go to the next line until it finished. Since withContext is a suspend call and does not block the main thread, we can do other tasks while the IO thread is busy in executing function1 and function 2. android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Resource Raw Folder in Android Studio Broadcast Receiver in Android With Example Services in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android UI Layouts Services in Android with Example Android RecyclerView in Kotlin Content Providers in Android with Example
[ { "code": null, "e": 25383, "s": 25355, "text": "\n14 Sep, 2020" }, { "code": null, "e": 25397, "s": 25383, "text": "Prerequisite:" }, { "code": null, "e": 25426, "s": 25397, "text": "Kotlin Coroutines on Android" }, { "code": null, "e": 25463, "s": 25426, "text": "Launch vs Async in Kotlin Coroutines" }, { "code": null, "e": 26182, "s": 25463, "text": "It is known that async and launch are the two ways to start the coroutine. Since It is known that async is used to get the result back, & should be used only when we need the parallel execution, whereas the launch is used when we do not want to get the result back and is used for the operation such as updating of data, etc. As we know that async is the only way till now to start the coroutine and get the result back, but the problem with async arises when we do not want to make parallel network calls. It is known when async is used, one needs to use the await() function, which leads to blocking of the main thread, but here comes the concept of withContext which removes the problem of blocking the main thread." }, { "code": null, "e": 26580, "s": 26182, "text": "withContext is nothing but another way of writing the async where one does not have to write await(). When withContext, is used, it runs the tasks in series instead of parallel. So one should remember that when we have a single task in the background and want to get back the result of that task, we should use withContext. Let us take an example which demonstrates the working of the withContext:" }, { "code": null, "e": 26587, "s": 26580, "text": "Kotlin" }, { "code": "// two kotlin suspend functions// Suppose we have two tasks like below private suspend fun doTaskOne(): String{ delay(2000) return \"One\"} private suspend fun doTaskTwo(): String{ delay(2000) return \"Two\"}", "e": 26798, "s": 26587, "text": null }, { "code": null, "e": 26919, "s": 26798, "text": "Let’s run the two tasks in parallel using async-await and then using withcontext and see the difference between the two." }, { "code": null, "e": 26926, "s": 26919, "text": "Kotlin" }, { "code": "// kotlin function using asyncfun startLongRunningTaskInParallel() { viewModelScope.launch { val resultOneDeferred = async { TaskOne() } val resultTwoDeferred = async { TaskTwo() } val combinedResult = resultOneDeferred.await() + resultTwoDeferred.await() }}", "e": 27198, "s": 26926, "text": null }, { "code": null, "e": 27326, "s": 27198, "text": "Here using async, both the task run in parallel. Now let’s use the withContext and do the same task in series with withContext." }, { "code": null, "e": 27333, "s": 27326, "text": "Kotlin" }, { "code": "// kotlin function using withContextfun startLongRunningTaskInParallel() { viewModelScope.launch { val resultOne = withContext(Dispatchers.IO) { TaskOne() } val resultTwo = withContext(Dispatchers.IO) { TaskTwo() } val combinedResult = resultOne + resultTwo }}", "e": 27606, "s": 27333, "text": null }, { "code": null, "e": 28041, "s": 27606, "text": "Here one can see that in withContext everything is the same, the only difference is that here we do not have to use the await() function, and tasks are executed in a serial manner. Since here multiple tasks have been taken, one should remember that async should be used with multiple tasks and withContext should be used with a single task. Now let’s take an example and try to understand withContext in detail and how it is executed." }, { "code": null, "e": 28048, "s": 28041, "text": "Kotlin" }, { "code": "// sample kotlin program for complete // demonstration of withContextfun testWithContext { var resultOne = \"GFG\" var resultTwo = \"Is Best\" Log.i(\"withContext\", \"Before\") resultOne = withContext(Dispatchers.IO) { function1() } resultTwo = withContext(Dispatchers.IO) { function2() } Log.i(\"withContext\", \"After\") val resultText = resultOne + resultTwo Log.i(\"withContext\", resultText)} suspend fun function1(): String{ delay(1000L) val message = \"function1\" Log.i(\"withContext\", message) return message} suspend fun function2(): String { delay(100L) val message = \"function2\" Log.i(\"withContext\", message) return message}", "e": 28687, "s": 28048, "text": null }, { "code": null, "e": 29034, "s": 28687, "text": "function 2 executes faster than function 1 since function 2 has less delay then function 1. Since withContext is a suspend call, that is it won’t go to the next line until it finished. Since withContext is a suspend call and does not block the main thread, we can do other tasks while the IO thread is busy in executing function1 and function 2. " }, { "code": null, "e": 29042, "s": 29034, "text": "android" }, { "code": null, "e": 29050, "s": 29042, "text": "Android" }, { "code": null, "e": 29057, "s": 29050, "text": "Kotlin" }, { "code": null, "e": 29065, "s": 29057, "text": "Android" }, { "code": null, "e": 29163, "s": 29065, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29221, "s": 29163, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 29259, "s": 29221, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 29302, "s": 29259, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29335, "s": 29302, "text": "Services in Android with Example" }, { "code": null, "e": 29366, "s": 29335, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29409, "s": 29366, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29428, "s": 29409, "text": "Android UI Layouts" }, { "code": null, "e": 29461, "s": 29428, "text": "Services in Android with Example" }, { "code": null, "e": 29492, "s": 29461, "text": "Android RecyclerView in Kotlin" } ]
Maximum number of set bits count in a K-size substring of a Binary String - GeeksforGeeks
18 May, 2021 Given a binary string S of size N and an integer K. The task is to find the maximum number of set bit appears in a substring of size K. Examples: Input: S = “100111010”, K = 3 Output: 3 Explanation: The substring “111” contains 3 set bits. Input:S = “0000000”, K = 4 Output: 0 Explanation: S doesn’t have any set bits in it, so ans is 0. Naive Approach: Generate all substring of size K.Find maximum of count of set bits in all substrings. Generate all substring of size K. Find maximum of count of set bits in all substrings. Time Complexity: O( N2). Auxiliary Space: O(1). Efficient Approach: The problem can be solved using Sliding window technique. Take maxcount variable to store maximum count of set bit and Count variable to store count set bit of current window.Traverse string from 1 to K and calculate the count of set bits and store as maxcount.Traverse string from K + 1 to length of the string.At every iteration, decrease count if (K – i)th bit is set. Increase count if ith bit is set. Compare and update maxcount.After complete array traversal, finally return maxcount. Take maxcount variable to store maximum count of set bit and Count variable to store count set bit of current window. Traverse string from 1 to K and calculate the count of set bits and store as maxcount. Traverse string from K + 1 to length of the string. At every iteration, decrease count if (K – i)th bit is set. Increase count if ith bit is set. Compare and update maxcount. After complete array traversal, finally return maxcount. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the maximum// set bits in a substring of size K#include<bits/stdc++.h>using namespace std; // Function that find Maximum number// of set bit appears in a substring// of size K.int maxSetBitCount(string s, int k){ int maxCount = 0, n = s.length(); int count = 0; // Traverse string 1 to k for(int i = 0; i < k; i++) { // Increment count if // character is set bit if (s[i] == '1') count++; } maxCount = count; // Traverse string k+1 // to length of string for(int i = k; i < n; i++) { // Remove the contribution of the // (i - k)th character which is no // longer in the window if (s[i - k] == '1') count--; // Add the contribution of // the current character if (s[i] == '1') count++; // Update maxCount at for // each window of size k maxCount = max(maxCount, count); } // Return maxCount return maxCount;} // Driver codeint main(){ string s = "100111010"; int k = 3; cout << (maxSetBitCount(s, k)); return 0;} // This code is contributed by Rajput-Ji // Java program to find the maximum// set bits in a substring of size Kimport java.util.*; class GFG { // Function that find Maximum number // of set bit appears in a substring // of size K. static int maxSetBitCount(String s, int k) { int maxCount = 0, n = s.length(); int count = 0; // Traverse string 1 to k for (int i = 0; i < k; i++) { // Increment count if // character is set bit if (s.charAt(i) == '1') count++; } maxCount = count; // Traverse string k+1 // to length of string for (int i = k; i < n; i++) { // remove the contribution of the // (i - k)th character which is no // longer in the window if (s.charAt(i - k) == '1') count--; // add the contribution of // the current character if (s.charAt(i) == '1') count++; // update maxCount at for // each window of size k maxCount = Math.max(maxCount, count); } // return maxCount return maxCount; } // Driver Program public static void main(String[] args) { String s = "100111010"; int k = 3; System.out.println(maxSetBitCount(s, k)); }} # Python3 program to find the maximum# set bits in a substring of size K # Function that find Maximum number# of set bit appears in a substring# of size K.def maxSetBitCount(s, k): maxCount = 0 n = len(s) count = 0 # Traverse string 1 to k for i in range(k): # Increment count if # character is set bit if (s[i] == '1'): count += 1 maxCount = count # Traverse string k+1 # to length of string for i in range(k, n): # Remove the contribution of the # (i - k)th character which is no # longer in the window if (s[i - k] == '1'): count -= 1 # Add the contribution of # the current character if (s[i] == '1'): count += 1 # Update maxCount at for # each window of size k maxCount = max(maxCount, count) # Return maxCount return maxCount # Driver codeif __name__ == '__main__': s = "100111010" k = 3 print(maxSetBitCount(s, k)) # This code is contributed by mohit kumar 29 // C# program to find the maximum// set bits in a substring of size Kusing System;class GFG { // Function that find Maximum number// of set bit appears in a substring// of size K.static int maxSetBitCount(string s, int k){ int maxCount = 0, n = s.Length; int count = 0; // Traverse string 1 to k for (int i = 0; i < k; i++) { // Increment count if // character is set bit if (s[i] == '1') count++; } maxCount = count; // Traverse string k+1 // to length of string for (int i = k; i < n; i++) { // remove the contribution of the // (i - k)th character which is no // longer in the window if (s[i - k] == '1') count--; // add the contribution of // the current character if (s[i] == '1') count++; // update maxCount at for // each window of size k maxCount = Math.Max(maxCount, count); } // return maxCount return maxCount;}// Driver Programpublic static void Main(){ string s = "100111010"; int k = 3; Console.Write(maxSetBitCount(s, k));}} // This code is contributed by Code_Mech <script> // Javascript program to find the maximum// set bits in a substring of size K // Function that find Maximum number// of set bit appears in a substring// of size K.function maxSetBitCount(s, k){ var maxCount = 0, n = s.length; var count = 0; // Traverse string 1 to k for(var i = 0; i < k; i++) { // Increment count if // character is set bit if (s[i] == '1') count++; } maxCount = count; // Traverse string k+1 // to length of string for(var i = k; i < n; i++) { // Remove the contribution of the // (i - k)th character which is no // longer in the window if (s[i - k] == '1') count--; // Add the contribution of // the current character if (s[i] == '1') count++; // Update maxCount at for // each window of size k maxCount = Math.max(maxCount, count); } // Return maxCount return maxCount;} // Driver codevar s = "100111010";var k = 3;document.write(maxSetBitCount(s, k)); // This code is contributed by famously.</script> 3 Time Complexity: O(N). Auxiliary Space: O(1). mohit kumar 29 Rajput-Ji Code_Mech nidhi_biet simmytarika5 famously binary-string setBitCount sliding-window substring Bit Magic Strings sliding-window Strings Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Check whether bitwise AND of a number with any subset of an array is zero or not Find the size of Largest Subset with positive Bitwise AND Write an Efficient Method to Check if a Number is Multiple of 3 Highest power of 2 less than or equal to given number Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26277, "s": 26249, "text": "\n18 May, 2021" }, { "code": null, "e": 26413, "s": 26277, "text": "Given a binary string S of size N and an integer K. The task is to find the maximum number of set bit appears in a substring of size K." }, { "code": null, "e": 26424, "s": 26413, "text": "Examples: " }, { "code": null, "e": 26518, "s": 26424, "text": "Input: S = “100111010”, K = 3 Output: 3 Explanation: The substring “111” contains 3 set bits." }, { "code": null, "e": 26618, "s": 26518, "text": "Input:S = “0000000”, K = 4 Output: 0 Explanation: S doesn’t have any set bits in it, so ans is 0. " }, { "code": null, "e": 26636, "s": 26618, "text": "Naive Approach: " }, { "code": null, "e": 26722, "s": 26636, "text": "Generate all substring of size K.Find maximum of count of set bits in all substrings." }, { "code": null, "e": 26756, "s": 26722, "text": "Generate all substring of size K." }, { "code": null, "e": 26809, "s": 26756, "text": "Find maximum of count of set bits in all substrings." }, { "code": null, "e": 26857, "s": 26809, "text": "Time Complexity: O( N2). Auxiliary Space: O(1)." }, { "code": null, "e": 26937, "s": 26857, "text": "Efficient Approach: The problem can be solved using Sliding window technique. " }, { "code": null, "e": 27370, "s": 26937, "text": "Take maxcount variable to store maximum count of set bit and Count variable to store count set bit of current window.Traverse string from 1 to K and calculate the count of set bits and store as maxcount.Traverse string from K + 1 to length of the string.At every iteration, decrease count if (K – i)th bit is set. Increase count if ith bit is set. Compare and update maxcount.After complete array traversal, finally return maxcount." }, { "code": null, "e": 27488, "s": 27370, "text": "Take maxcount variable to store maximum count of set bit and Count variable to store count set bit of current window." }, { "code": null, "e": 27575, "s": 27488, "text": "Traverse string from 1 to K and calculate the count of set bits and store as maxcount." }, { "code": null, "e": 27627, "s": 27575, "text": "Traverse string from K + 1 to length of the string." }, { "code": null, "e": 27750, "s": 27627, "text": "At every iteration, decrease count if (K – i)th bit is set. Increase count if ith bit is set. Compare and update maxcount." }, { "code": null, "e": 27807, "s": 27750, "text": "After complete array traversal, finally return maxcount." }, { "code": null, "e": 27860, "s": 27807, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27864, "s": 27860, "text": "C++" }, { "code": null, "e": 27869, "s": 27864, "text": "Java" }, { "code": null, "e": 27877, "s": 27869, "text": "Python3" }, { "code": null, "e": 27880, "s": 27877, "text": "C#" }, { "code": null, "e": 27891, "s": 27880, "text": "Javascript" }, { "code": "// C++ program to find the maximum// set bits in a substring of size K#include<bits/stdc++.h>using namespace std; // Function that find Maximum number// of set bit appears in a substring// of size K.int maxSetBitCount(string s, int k){ int maxCount = 0, n = s.length(); int count = 0; // Traverse string 1 to k for(int i = 0; i < k; i++) { // Increment count if // character is set bit if (s[i] == '1') count++; } maxCount = count; // Traverse string k+1 // to length of string for(int i = k; i < n; i++) { // Remove the contribution of the // (i - k)th character which is no // longer in the window if (s[i - k] == '1') count--; // Add the contribution of // the current character if (s[i] == '1') count++; // Update maxCount at for // each window of size k maxCount = max(maxCount, count); } // Return maxCount return maxCount;} // Driver codeint main(){ string s = \"100111010\"; int k = 3; cout << (maxSetBitCount(s, k)); return 0;} // This code is contributed by Rajput-Ji", "e": 29074, "s": 27891, "text": null }, { "code": "// Java program to find the maximum// set bits in a substring of size Kimport java.util.*; class GFG { // Function that find Maximum number // of set bit appears in a substring // of size K. static int maxSetBitCount(String s, int k) { int maxCount = 0, n = s.length(); int count = 0; // Traverse string 1 to k for (int i = 0; i < k; i++) { // Increment count if // character is set bit if (s.charAt(i) == '1') count++; } maxCount = count; // Traverse string k+1 // to length of string for (int i = k; i < n; i++) { // remove the contribution of the // (i - k)th character which is no // longer in the window if (s.charAt(i - k) == '1') count--; // add the contribution of // the current character if (s.charAt(i) == '1') count++; // update maxCount at for // each window of size k maxCount = Math.max(maxCount, count); } // return maxCount return maxCount; } // Driver Program public static void main(String[] args) { String s = \"100111010\"; int k = 3; System.out.println(maxSetBitCount(s, k)); }}", "e": 30406, "s": 29074, "text": null }, { "code": "# Python3 program to find the maximum# set bits in a substring of size K # Function that find Maximum number# of set bit appears in a substring# of size K.def maxSetBitCount(s, k): maxCount = 0 n = len(s) count = 0 # Traverse string 1 to k for i in range(k): # Increment count if # character is set bit if (s[i] == '1'): count += 1 maxCount = count # Traverse string k+1 # to length of string for i in range(k, n): # Remove the contribution of the # (i - k)th character which is no # longer in the window if (s[i - k] == '1'): count -= 1 # Add the contribution of # the current character if (s[i] == '1'): count += 1 # Update maxCount at for # each window of size k maxCount = max(maxCount, count) # Return maxCount return maxCount # Driver codeif __name__ == '__main__': s = \"100111010\" k = 3 print(maxSetBitCount(s, k)) # This code is contributed by mohit kumar 29", "e": 31467, "s": 30406, "text": null }, { "code": "// C# program to find the maximum// set bits in a substring of size Kusing System;class GFG { // Function that find Maximum number// of set bit appears in a substring// of size K.static int maxSetBitCount(string s, int k){ int maxCount = 0, n = s.Length; int count = 0; // Traverse string 1 to k for (int i = 0; i < k; i++) { // Increment count if // character is set bit if (s[i] == '1') count++; } maxCount = count; // Traverse string k+1 // to length of string for (int i = k; i < n; i++) { // remove the contribution of the // (i - k)th character which is no // longer in the window if (s[i - k] == '1') count--; // add the contribution of // the current character if (s[i] == '1') count++; // update maxCount at for // each window of size k maxCount = Math.Max(maxCount, count); } // return maxCount return maxCount;}// Driver Programpublic static void Main(){ string s = \"100111010\"; int k = 3; Console.Write(maxSetBitCount(s, k));}} // This code is contributed by Code_Mech", "e": 32632, "s": 31467, "text": null }, { "code": "<script> // Javascript program to find the maximum// set bits in a substring of size K // Function that find Maximum number// of set bit appears in a substring// of size K.function maxSetBitCount(s, k){ var maxCount = 0, n = s.length; var count = 0; // Traverse string 1 to k for(var i = 0; i < k; i++) { // Increment count if // character is set bit if (s[i] == '1') count++; } maxCount = count; // Traverse string k+1 // to length of string for(var i = k; i < n; i++) { // Remove the contribution of the // (i - k)th character which is no // longer in the window if (s[i - k] == '1') count--; // Add the contribution of // the current character if (s[i] == '1') count++; // Update maxCount at for // each window of size k maxCount = Math.max(maxCount, count); } // Return maxCount return maxCount;} // Driver codevar s = \"100111010\";var k = 3;document.write(maxSetBitCount(s, k)); // This code is contributed by famously.</script>", "e": 33759, "s": 32632, "text": null }, { "code": null, "e": 33761, "s": 33759, "text": "3" }, { "code": null, "e": 33810, "s": 33763, "text": "Time Complexity: O(N). Auxiliary Space: O(1). " }, { "code": null, "e": 33825, "s": 33810, "text": "mohit kumar 29" }, { "code": null, "e": 33835, "s": 33825, "text": "Rajput-Ji" }, { "code": null, "e": 33845, "s": 33835, "text": "Code_Mech" }, { "code": null, "e": 33856, "s": 33845, "text": "nidhi_biet" }, { "code": null, "e": 33869, "s": 33856, "text": "simmytarika5" }, { "code": null, "e": 33878, "s": 33869, "text": "famously" }, { "code": null, "e": 33892, "s": 33878, "text": "binary-string" }, { "code": null, "e": 33904, "s": 33892, "text": "setBitCount" }, { "code": null, "e": 33919, "s": 33904, "text": "sliding-window" }, { "code": null, "e": 33929, "s": 33919, "text": "substring" }, { "code": null, "e": 33939, "s": 33929, "text": "Bit Magic" }, { "code": null, "e": 33947, "s": 33939, "text": "Strings" }, { "code": null, "e": 33962, "s": 33947, "text": "sliding-window" }, { "code": null, "e": 33970, "s": 33962, "text": "Strings" }, { "code": null, "e": 33980, "s": 33970, "text": "Bit Magic" }, { "code": null, "e": 34078, "s": 33980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34129, "s": 34078, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 34210, "s": 34129, "text": "Check whether bitwise AND of a number with any subset of an array is zero or not" }, { "code": null, "e": 34268, "s": 34210, "text": "Find the size of Largest Subset with positive Bitwise AND" }, { "code": null, "e": 34332, "s": 34268, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 34386, "s": 34332, "text": "Highest power of 2 less than or equal to given number" }, { "code": null, "e": 34432, "s": 34386, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 34457, "s": 34432, "text": "Reverse a string in Java" }, { "code": null, "e": 34517, "s": 34457, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34532, "s": 34517, "text": "C++ Data Types" } ]
SortedSet in C# with Examples - GeeksforGeeks
09 Dec, 2021 In C#, SortedSet is a collection of objects in sorted order. It is of the generic type collection and defined under System.Collections.Generic namespace. It also provides many mathematical set operations, such as intersection, union, and difference. It is a dynamic collection means the size of the SortedSet is automatically increased when the new elements are added. Important Points: The SortedSet class implements the ICollection, IEnumerable, IReadOnlyCollection, ISet, ICollection, IEnumerable, IDeserializationCallback, and ISerializable interfaces. The capacity of a SortedSet is the number of elements it can hold. In SortedSet, the elements must be unique. In SortedSet, the order of the element is ascending. It is generally used when we want to use SortedSet class if you have to store unique elements and maintain ascending order. In SortedSet, the user can only store the same type of elements. The SortedSet class provides 5 different types of constructors which are used to create a SortedSet, here we only use SortedSet(), constructor. To read more about SortedSet’s constructors you can refer to C# | SortedSet Class.SortedSet(): It is used to create an instance of the SortedSet class.Step 1: Include System.Collections.Generic namespace in your program with the help of using keyword: using System.Collections.Generic; Step 2: Create a SortedSet using the SortedSet class as shown below: SortedSet<type_of_sortedset> sortedset_name = new SortedSet<type_of_sortedset>(); Step 3: If you want to add elements in your SortedSet, then use Add() method to add elements in the SortedSet. And you can also store elements in your SortedSet using collection initializer.Step 4: The elements of SortedSet is accessed by using a foreach loop. As shown in the below example.Example: CSharp // C# program to illustrate how to// create SortedSetusing System;using System.Collections.Generic; class GFG { // Driver Class static public void Main() { // Creating SortedSet // Using SortedSet class SortedSet<int> my_Set1 = new SortedSet<int>(); // Add the elements in SortedSet // Using Add method my_Set1.Add(101); my_Set1.Add(1001); my_Set1.Add(10001); my_Set1.Add(100001); Console.WriteLine("Elements of my_Set1:"); // Accessing elements of SortedSet // Using foreach loop foreach(var val in my_Set1) { Console.WriteLine(val); } // Creating another SortedSet // using collection initializer // to initialize SortedSet SortedSet<int> my_Set2 = new SortedSet<int>() { 202,2002,20002,200002}; // Display elements of my_Set2 Console.WriteLine("Elements of my_Set2:"); foreach(var value in my_Set2) { Console.WriteLine(value); } }} Elements of my_Set1: 101 1001 10001 100001 Elements of my_Set2: 202 2002 20002 200002 In SortedSet, you are allowed to remove elements from the SortedSet. SortedSet<T> class provides three different methods to remove elements and the methods are: Remove(T): This method is used to remove a specified item from the SortedSet. RemoveWhere(Predicate): This method is used to remove all elements that match the conditions defined by the specified predicate from a SortedSet. Clear(): This method is used to remove all elements from the set. Example: CSharp // C# program to illustrate how to// remove elements from SortedSetusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating SortedSet // Using SortedSet class SortedSet<int> my_Set = new SortedSet<int>(); // Add the elements in SortedSet // Using Add method my_Set.Add(101); my_Set.Add(1001); my_Set.Add(10001); my_Set.Add(100001); // After using Remove method Console.WriteLine("Total number of elements "+ "present in my_Set:{0}", my_Set.Count); // Remove element from SortedSet // Using Remove method my_Set.Remove(1001); // Before using Remove method Console.WriteLine("Total number of elements "+ "present in my_Set:{0}", my_Set.Count); // Remove all elements from SortedSet // Using Clear method my_Set.Clear(); Console.WriteLine("Total number of elements "+ "present in my_Set:{0}", my_Set.Count); }} Total number of elements present in my_Set:4 Total number of elements present in my_Set:3 Total number of elements present in my_Set:0 In SortedSet, you can check whether the given element is present or not using the Contains method. This method is used to determine whether the set contains a specific element.Example: CSharp // C# program to illustrate how to check// availability of elements in SortedSetusing System;using System.Collections.Generic; public class GFG { static public void Main() { // Creating SortedSet // Using SortedSet class SortedSet<int> my_Set = new SortedSet<int>(); // Add the elements in SortedSet // Using Add method my_Set.Add(101); my_Set.Add(1001); my_Set.Add(10001); my_Set.Add(100001); // Check the given element present // in the SortedSet or not // Using Contains method if (my_Set.Contains(101) == true) { Console.WriteLine("Element is available..!"); } else { Console.WriteLine("Element is not available..!"); } }} Element is available..! sagartomar9927 CSharp-Generic-Namespace CSharp-Generic-SortedSet C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method C# | Delegates C# | Arrays of Strings C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 26525, "s": 26497, "text": "\n09 Dec, 2021" }, { "code": null, "e": 26913, "s": 26525, "text": "In C#, SortedSet is a collection of objects in sorted order. It is of the generic type collection and defined under System.Collections.Generic namespace. It also provides many mathematical set operations, such as intersection, union, and difference. It is a dynamic collection means the size of the SortedSet is automatically increased when the new elements are added. Important Points: " }, { "code": null, "e": 27083, "s": 26913, "text": "The SortedSet class implements the ICollection, IEnumerable, IReadOnlyCollection, ISet, ICollection, IEnumerable, IDeserializationCallback, and ISerializable interfaces." }, { "code": null, "e": 27150, "s": 27083, "text": "The capacity of a SortedSet is the number of elements it can hold." }, { "code": null, "e": 27193, "s": 27150, "text": "In SortedSet, the elements must be unique." }, { "code": null, "e": 27246, "s": 27193, "text": "In SortedSet, the order of the element is ascending." }, { "code": null, "e": 27370, "s": 27246, "text": "It is generally used when we want to use SortedSet class if you have to store unique elements and maintain ascending order." }, { "code": null, "e": 27435, "s": 27370, "text": "In SortedSet, the user can only store the same type of elements." }, { "code": null, "e": 27834, "s": 27437, "text": "The SortedSet class provides 5 different types of constructors which are used to create a SortedSet, here we only use SortedSet(), constructor. To read more about SortedSet’s constructors you can refer to C# | SortedSet Class.SortedSet(): It is used to create an instance of the SortedSet class.Step 1: Include System.Collections.Generic namespace in your program with the help of using keyword: " }, { "code": null, "e": 27868, "s": 27834, "text": "using System.Collections.Generic;" }, { "code": null, "e": 27938, "s": 27868, "text": "Step 2: Create a SortedSet using the SortedSet class as shown below: " }, { "code": null, "e": 28020, "s": 27938, "text": "SortedSet<type_of_sortedset> sortedset_name = new SortedSet<type_of_sortedset>();" }, { "code": null, "e": 28321, "s": 28020, "text": "Step 3: If you want to add elements in your SortedSet, then use Add() method to add elements in the SortedSet. And you can also store elements in your SortedSet using collection initializer.Step 4: The elements of SortedSet is accessed by using a foreach loop. As shown in the below example.Example: " }, { "code": null, "e": 28328, "s": 28321, "text": "CSharp" }, { "code": "// C# program to illustrate how to// create SortedSetusing System;using System.Collections.Generic; class GFG { // Driver Class static public void Main() { // Creating SortedSet // Using SortedSet class SortedSet<int> my_Set1 = new SortedSet<int>(); // Add the elements in SortedSet // Using Add method my_Set1.Add(101); my_Set1.Add(1001); my_Set1.Add(10001); my_Set1.Add(100001); Console.WriteLine(\"Elements of my_Set1:\"); // Accessing elements of SortedSet // Using foreach loop foreach(var val in my_Set1) { Console.WriteLine(val); } // Creating another SortedSet // using collection initializer // to initialize SortedSet SortedSet<int> my_Set2 = new SortedSet<int>() { 202,2002,20002,200002}; // Display elements of my_Set2 Console.WriteLine(\"Elements of my_Set2:\"); foreach(var value in my_Set2) { Console.WriteLine(value); } }}", "e": 29418, "s": 28328, "text": null }, { "code": null, "e": 29504, "s": 29418, "text": "Elements of my_Set1:\n101\n1001\n10001\n100001\nElements of my_Set2:\n202\n2002\n20002\n200002" }, { "code": null, "e": 29668, "s": 29506, "text": "In SortedSet, you are allowed to remove elements from the SortedSet. SortedSet<T> class provides three different methods to remove elements and the methods are: " }, { "code": null, "e": 29746, "s": 29668, "text": "Remove(T): This method is used to remove a specified item from the SortedSet." }, { "code": null, "e": 29892, "s": 29746, "text": "RemoveWhere(Predicate): This method is used to remove all elements that match the conditions defined by the specified predicate from a SortedSet." }, { "code": null, "e": 29958, "s": 29892, "text": "Clear(): This method is used to remove all elements from the set." }, { "code": null, "e": 29968, "s": 29958, "text": "Example: " }, { "code": null, "e": 29975, "s": 29968, "text": "CSharp" }, { "code": "// C# program to illustrate how to// remove elements from SortedSetusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating SortedSet // Using SortedSet class SortedSet<int> my_Set = new SortedSet<int>(); // Add the elements in SortedSet // Using Add method my_Set.Add(101); my_Set.Add(1001); my_Set.Add(10001); my_Set.Add(100001); // After using Remove method Console.WriteLine(\"Total number of elements \"+ \"present in my_Set:{0}\", my_Set.Count); // Remove element from SortedSet // Using Remove method my_Set.Remove(1001); // Before using Remove method Console.WriteLine(\"Total number of elements \"+ \"present in my_Set:{0}\", my_Set.Count); // Remove all elements from SortedSet // Using Clear method my_Set.Clear(); Console.WriteLine(\"Total number of elements \"+ \"present in my_Set:{0}\", my_Set.Count); }}", "e": 31041, "s": 29975, "text": null }, { "code": null, "e": 31176, "s": 31041, "text": "Total number of elements present in my_Set:4\nTotal number of elements present in my_Set:3\nTotal number of elements present in my_Set:0" }, { "code": null, "e": 31364, "s": 31178, "text": "In SortedSet, you can check whether the given element is present or not using the Contains method. This method is used to determine whether the set contains a specific element.Example: " }, { "code": null, "e": 31371, "s": 31364, "text": "CSharp" }, { "code": "// C# program to illustrate how to check// availability of elements in SortedSetusing System;using System.Collections.Generic; public class GFG { static public void Main() { // Creating SortedSet // Using SortedSet class SortedSet<int> my_Set = new SortedSet<int>(); // Add the elements in SortedSet // Using Add method my_Set.Add(101); my_Set.Add(1001); my_Set.Add(10001); my_Set.Add(100001); // Check the given element present // in the SortedSet or not // Using Contains method if (my_Set.Contains(101) == true) { Console.WriteLine(\"Element is available..!\"); } else { Console.WriteLine(\"Element is not available..!\"); } }}", "e": 32159, "s": 31371, "text": null }, { "code": null, "e": 32183, "s": 32159, "text": "Element is available..!" }, { "code": null, "e": 32200, "s": 32185, "text": "sagartomar9927" }, { "code": null, "e": 32225, "s": 32200, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 32250, "s": 32225, "text": "CSharp-Generic-SortedSet" }, { "code": null, "e": 32253, "s": 32250, "text": "C#" }, { "code": null, "e": 32351, "s": 32253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32405, "s": 32351, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 32447, "s": 32405, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 32509, "s": 32447, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 32537, "s": 32509, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 32552, "s": 32537, "text": "C# | Delegates" }, { "code": null, "e": 32575, "s": 32552, "text": "C# | Arrays of Strings" }, { "code": null, "e": 32597, "s": 32575, "text": "C# | Abstract Classes" }, { "code": null, "e": 32643, "s": 32597, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 32666, "s": 32643, "text": "Extension Method in C#" } ]
ML | Transfer Learning with Convolutional Neural Networks - GeeksforGeeks
25 Nov, 2019 Transfer learning as a general term refers to reusing the knowledge learned from one task for another. Specifically for convolutional neural networks (CNNs), many image features are common to a variety of datasets (e.g. lines, edges are seen in almost every image). It is for this reason that, especially for large structures, CNNs are very rarely trained completely from scratch as large datasets and heavy computational resources are hard to come by.A common pretraining dataset used is the ImageNet dataset, consisting of 1.2 million images. The actual model used varies from task to task (many times, people just choose what performs best on the ImageNet challenge), but ResNet50 model in used this article. The pre-trained model can often be found through whatever library is being used which, in this case, is Keras. ResNet IntroductionResNet was initially designed as a method to solve the vanishing gradient problem. This is a problem where backpropagated gradients become extremely small as they’re multiplied over and over again, limiting the size of a neural network. The ResNet architecture attempts to solve that by employing skip connections, that is adding shortcuts that allow data to skip past layers. The model consists of a series of convolutional layers + skip connections, then average pooling, then an output fully connected (dense) layer. For transfer learning, we only want the convolutional layers as those to contain the features we’re interested in, so we would want to omit them when importing the model. Finally, because we’re removing the output layers, we then need to replace them with our own series of layers. Problem StatementTo show the process of transfer learning, I’ll be using the Caltech-101 dataset, an image dataset with 101 categories and about 40-800 images per category. Data Processing First download and extract the dataset here. Make sure to remove the “BACKGROUND_Google” folder after extraction. Code : To properly evaluate, we need to split the data into training and testing sets as well. Here, we need to split within each category to ensure proper representation in the test set. TEST_SPLIT = 0.2VALIDATION_SPLIT = 0.2 import osimport math # stores test dataos.mkdir("caltech_test") for cat in os.listdir("101_ObjectCategories/"): # moves x portion of images per category into test images # new category folder os.mkdir("caltech_test/"+cat) imgs = os.listdir("101_ObjectCategories/"+cat) # all image filenames split = math.floor(len(imgs)*TEST_SPLIT) test_imgs = imgs[:split] # move test portion for t_img in test_imgs: os.rename("101_ObjectCategories/"+cat+"/"+t_img, "caltech_test/"+cat+"/"+t_img) Output: This above code creates the file structure: 101_ObjectCategories/ -- accordion -- airplanes -- anchor -- ... caltech_test/ -- accordion -- airplanes -- anchor -- ... The first folder contains the train images, the second contains test images. Each subfolder includes images belonging to that category. To input the data, we’re going to use Keras’s ImageDataGenerator class. ImageDataGenerator allows for the easy processing of image data, having options for augmentation as well. # make sure to match original model's preprocessing functionfrom keras.applications.resnet50 import preprocess_input from keras.preprocessing.image import ImageDataGenerator train_gen = ImageDataGenerator( validation_split = 0.2, preprocessing_function = preprocess_input)train_flow = train_gen.flow_from_directory("101_ObjectCategories/", target_size =(256, 256), batch_size = 32, subset ="training") valid_flow = train_gen.flow_from_directory("101_ObjectCategories/", target_size =(256, 256), batch_size = 32, subset ="validation") test_gen = ImageDataGenerator( preprocessing_function = preprocess_input)test_flow = test_gen.flow_from_directory("caltech_test", target_size =(256, 256), batch_size = 32) The above code takes the file path of the image directory and creates an object for data generation. Model BuildingCode : To add the base pretrained model. from keras.applications.resnet50 import ResNet50from keras.layers import GlobalAveragePooling2D, Densefrom keras.layers import BatchNormalization, Dropoutfrom keras.models import Model # by default, the loaded model will include the original CNN #classifier designed for the ImageNet dataset# since we want to reuse this model for a different problem,# we need to omit the original fully connected layers, and # replace them with our own setting include_top = False will# load the model without the fully connected layer # load resnet model, with pretrained imagenet weights.res = ResNet50(weights ='imagenet', include_top = False, input_shape =(256, 256, 3)) This dataset is relatively small at around 5628 images after splitting, with most categories having only 50 images, so fine-tuning the convolutional layers may result in overfitting. Our new dataset is pretty similar to the ImageNet dataset, so we can be confident that a lot of the pre-trained weights have the correct features as well. So, we can freeze those trained convolutional layers so they aren’t changed when we train the rest of the classifier. If you have a smaller dataset that is significantly different from the original, fine-tuning may still cause overfitting, but the later layers wouldn’t contain the correct features. So, you could again freeze the convolutional layers but only use the output from earlier layers as those contain more general features. With a large dataset, you don’t need to worry about overfitting, so you can often fine-tune the entire network. from keras.applications.resnet50 import ResNet50from keras.layers import GlobalAveragePooling2D, Densefrom keras.layers import BatchNormalization, Dropoutfrom keras.models import Model # by default, the loaded model will include the original CNN #classifier designed for the ImageNet dataset# since we want to reuse this model for a different problem,# we need to omit the original fully connected layers, and # replace them with our own setting include_top = False will# load the model without the fully connected layer # load resnet model, with pretrained imagenet weights.res = ResNet50(weights ='imagenet', include_top = False, input_shape =(256, 256, 3)) Now, we can add the rest of the classifier. This takes the output from the pre-trained convolutional layers and inputs it into a separate classifier that gets trained on the new dataset. # get the output from the loaded modelx = res.output # avg. pools across the spatial dimensions (rows, columns) # until it becomes zero. Reshapes data into a 1D, allowing # for proper input shape into Dense layers # (e.g. (8, 8, 2048) -> (2048)).x = GlobalAveragePooling2D()(x) # subtracts batch mean and divides by batch standard deviation# to reduce shift in input distributions between layers. x = BatchNormalization()(x) # dropout allows layers to be less dependent on# certain features, reducing overfittingx = Dropout(0.5)(x) x = Dense(512, activation ='relu')(x)x = BatchNormalization()(x)x = Dropout(0.5)(x) # output classification layer, we have 101 classes, # so we need 101 output neuronsx = Dense(101, activation ='softmax')(x) # create the model, setting input / outputmodel = Model(res.input, x) # compile the model - we're training using the Adam Optimizer# and Categorical Cross Entropy as the loss functionmodel.compile(optimizer ='Adam', loss ='categorical_crossentropy', metrics =['accuracy']) # structure of our modelmodel.summary() Code : Train the model model.fit_generator(train_flow, epochs = 5, validation_data = valid_flow) Output: Epoch 1/5 176/176 [==============================] - 27s 156ms/step - loss: 1.6601 - acc: 0.6338 - val_loss: 0.3799 - val_acc: 0.8922 Epoch 2/5 176/176 [==============================] - 19s 107ms/step - loss: 0.4637 - acc: 0.8696 - val_loss: 0.2841 - val_acc: 0.9225 Epoch 3/5 176/176 [==============================] - 19s 107ms/step - loss: 0.2777 - acc: 0.9211 - val_loss: 0.2714 - val_acc: 0.9225 Epoch 4/5 176/176 [==============================] - 19s 107ms/step - loss: 0.2223 - acc: 0.9327 - val_loss: 0.2419 - val_acc: 0.9284 Epoch 5/5 176/176 [==============================] - 19s 106ms/step - loss: 0.1784 - acc: 0.9461 - val_loss: 0.2499 - val_acc: 0.9239 Code: To evaluate the test set result = model.evaluate(test_flow) print('The model achieved a loss of %.2f and,' 'accuracy of %.2f%%.' % (result[0], result[1]*100)) Output: 53/53 [==============================] - 5s 95ms/step The model achieved a loss of 0.23 and accuracy of 92.80%. For a 101 class dataset, we have achieved a 92.8% accuracy after only 5 epochs. For perspective, the original ResNet was trained on an ~1 million image dataset, for 120 epochs.There are a couple of things that could be improved upon. For one, looking at the discrepancy between validation loss and training loss in the last epoch, you can see that the model is starting to overfit. One way to solve this is to add image augmentation. Simple image augmentation can be easily implemented with the ImageDataGenerator class. You could also play around with adding/removing layers or changing hyperparameters such as the dropout or the size of the Dense layer.Run this code here with Google Colab’s free GPU compute resources. Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25589, "s": 25561, "text": "\n25 Nov, 2019" }, { "code": null, "e": 26412, "s": 25589, "text": "Transfer learning as a general term refers to reusing the knowledge learned from one task for another. Specifically for convolutional neural networks (CNNs), many image features are common to a variety of datasets (e.g. lines, edges are seen in almost every image). It is for this reason that, especially for large structures, CNNs are very rarely trained completely from scratch as large datasets and heavy computational resources are hard to come by.A common pretraining dataset used is the ImageNet dataset, consisting of 1.2 million images. The actual model used varies from task to task (many times, people just choose what performs best on the ImageNet challenge), but ResNet50 model in used this article. The pre-trained model can often be found through whatever library is being used which, in this case, is Keras." }, { "code": null, "e": 26808, "s": 26412, "text": "ResNet IntroductionResNet was initially designed as a method to solve the vanishing gradient problem. This is a problem where backpropagated gradients become extremely small as they’re multiplied over and over again, limiting the size of a neural network. The ResNet architecture attempts to solve that by employing skip connections, that is adding shortcuts that allow data to skip past layers." }, { "code": null, "e": 27233, "s": 26808, "text": "The model consists of a series of convolutional layers + skip connections, then average pooling, then an output fully connected (dense) layer. For transfer learning, we only want the convolutional layers as those to contain the features we’re interested in, so we would want to omit them when importing the model. Finally, because we’re removing the output layers, we then need to replace them with our own series of layers." }, { "code": null, "e": 27406, "s": 27233, "text": "Problem StatementTo show the process of transfer learning, I’ll be using the Caltech-101 dataset, an image dataset with 101 categories and about 40-800 images per category." }, { "code": null, "e": 27422, "s": 27406, "text": "Data Processing" }, { "code": null, "e": 27536, "s": 27422, "text": "First download and extract the dataset here. Make sure to remove the “BACKGROUND_Google” folder after extraction." }, { "code": null, "e": 27724, "s": 27536, "text": "Code : To properly evaluate, we need to split the data into training and testing sets as well. Here, we need to split within each category to ensure proper representation in the test set." }, { "code": "TEST_SPLIT = 0.2VALIDATION_SPLIT = 0.2 import osimport math # stores test dataos.mkdir(\"caltech_test\") for cat in os.listdir(\"101_ObjectCategories/\"): # moves x portion of images per category into test images # new category folder os.mkdir(\"caltech_test/\"+cat) imgs = os.listdir(\"101_ObjectCategories/\"+cat) # all image filenames split = math.floor(len(imgs)*TEST_SPLIT) test_imgs = imgs[:split] # move test portion for t_img in test_imgs: os.rename(\"101_ObjectCategories/\"+cat+\"/\"+t_img, \"caltech_test/\"+cat+\"/\"+t_img)", "e": 28278, "s": 27724, "text": null }, { "code": null, "e": 28286, "s": 28278, "text": "Output:" }, { "code": null, "e": 28454, "s": 28286, "text": "This above code creates the file structure:\n\n101_ObjectCategories/\n-- accordion\n-- airplanes\n-- anchor\n-- ...\ncaltech_test/\n-- accordion\n-- airplanes\n-- anchor\n-- ...\n" }, { "code": null, "e": 28768, "s": 28454, "text": "The first folder contains the train images, the second contains test images. Each subfolder includes images belonging to that category. To input the data, we’re going to use Keras’s ImageDataGenerator class. ImageDataGenerator allows for the easy processing of image data, having options for augmentation as well." }, { "code": "# make sure to match original model's preprocessing functionfrom keras.applications.resnet50 import preprocess_input from keras.preprocessing.image import ImageDataGenerator train_gen = ImageDataGenerator( validation_split = 0.2, preprocessing_function = preprocess_input)train_flow = train_gen.flow_from_directory(\"101_ObjectCategories/\", target_size =(256, 256), batch_size = 32, subset =\"training\") valid_flow = train_gen.flow_from_directory(\"101_ObjectCategories/\", target_size =(256, 256), batch_size = 32, subset =\"validation\") test_gen = ImageDataGenerator( preprocessing_function = preprocess_input)test_flow = test_gen.flow_from_directory(\"caltech_test\", target_size =(256, 256), batch_size = 32)", "e": 29839, "s": 28768, "text": null }, { "code": null, "e": 29940, "s": 29839, "text": "The above code takes the file path of the image directory and creates an object for data generation." }, { "code": null, "e": 29995, "s": 29940, "text": "Model BuildingCode : To add the base pretrained model." }, { "code": "from keras.applications.resnet50 import ResNet50from keras.layers import GlobalAveragePooling2D, Densefrom keras.layers import BatchNormalization, Dropoutfrom keras.models import Model # by default, the loaded model will include the original CNN #classifier designed for the ImageNet dataset# since we want to reuse this model for a different problem,# we need to omit the original fully connected layers, and # replace them with our own setting include_top = False will# load the model without the fully connected layer # load resnet model, with pretrained imagenet weights.res = ResNet50(weights ='imagenet', include_top = False, input_shape =(256, 256, 3)) ", "e": 30673, "s": 29995, "text": null }, { "code": null, "e": 31559, "s": 30673, "text": "This dataset is relatively small at around 5628 images after splitting, with most categories having only 50 images, so fine-tuning the convolutional layers may result in overfitting. Our new dataset is pretty similar to the ImageNet dataset, so we can be confident that a lot of the pre-trained weights have the correct features as well. So, we can freeze those trained convolutional layers so they aren’t changed when we train the rest of the classifier. If you have a smaller dataset that is significantly different from the original, fine-tuning may still cause overfitting, but the later layers wouldn’t contain the correct features. So, you could again freeze the convolutional layers but only use the output from earlier layers as those contain more general features. With a large dataset, you don’t need to worry about overfitting, so you can often fine-tune the entire network." }, { "code": "from keras.applications.resnet50 import ResNet50from keras.layers import GlobalAveragePooling2D, Densefrom keras.layers import BatchNormalization, Dropoutfrom keras.models import Model # by default, the loaded model will include the original CNN #classifier designed for the ImageNet dataset# since we want to reuse this model for a different problem,# we need to omit the original fully connected layers, and # replace them with our own setting include_top = False will# load the model without the fully connected layer # load resnet model, with pretrained imagenet weights.res = ResNet50(weights ='imagenet', include_top = False, input_shape =(256, 256, 3)) ", "e": 32237, "s": 31559, "text": null }, { "code": null, "e": 32424, "s": 32237, "text": "Now, we can add the rest of the classifier. This takes the output from the pre-trained convolutional layers and inputs it into a separate classifier that gets trained on the new dataset." }, { "code": "# get the output from the loaded modelx = res.output # avg. pools across the spatial dimensions (rows, columns) # until it becomes zero. Reshapes data into a 1D, allowing # for proper input shape into Dense layers # (e.g. (8, 8, 2048) -> (2048)).x = GlobalAveragePooling2D()(x) # subtracts batch mean and divides by batch standard deviation# to reduce shift in input distributions between layers. x = BatchNormalization()(x) # dropout allows layers to be less dependent on# certain features, reducing overfittingx = Dropout(0.5)(x) x = Dense(512, activation ='relu')(x)x = BatchNormalization()(x)x = Dropout(0.5)(x) # output classification layer, we have 101 classes, # so we need 101 output neuronsx = Dense(101, activation ='softmax')(x) # create the model, setting input / outputmodel = Model(res.input, x) # compile the model - we're training using the Adam Optimizer# and Categorical Cross Entropy as the loss functionmodel.compile(optimizer ='Adam', loss ='categorical_crossentropy', metrics =['accuracy']) # structure of our modelmodel.summary() ", "e": 33519, "s": 32424, "text": null }, { "code": null, "e": 33542, "s": 33519, "text": "Code : Train the model" }, { "code": "model.fit_generator(train_flow, epochs = 5, validation_data = valid_flow)", "e": 33616, "s": 33542, "text": null }, { "code": null, "e": 33624, "s": 33616, "text": "Output:" }, { "code": null, "e": 34295, "s": 33624, "text": "Epoch 1/5\n176/176 [==============================] - 27s 156ms/step - loss: 1.6601 - acc: 0.6338 - val_loss: 0.3799 - val_acc: 0.8922\nEpoch 2/5\n176/176 [==============================] - 19s 107ms/step - loss: 0.4637 - acc: 0.8696 - val_loss: 0.2841 - val_acc: 0.9225\nEpoch 3/5\n176/176 [==============================] - 19s 107ms/step - loss: 0.2777 - acc: 0.9211 - val_loss: 0.2714 - val_acc: 0.9225\nEpoch 4/5\n176/176 [==============================] - 19s 107ms/step - loss: 0.2223 - acc: 0.9327 - val_loss: 0.2419 - val_acc: 0.9284\nEpoch 5/5\n176/176 [==============================] - 19s 106ms/step - loss: 0.1784 - acc: 0.9461 - val_loss: 0.2499 - val_acc: 0.9239\n" }, { "code": null, "e": 34326, "s": 34295, "text": "Code: To evaluate the test set" }, { "code": "result = model.evaluate(test_flow) print('The model achieved a loss of %.2f and,' 'accuracy of %.2f%%.' % (result[0], result[1]*100))", "e": 34466, "s": 34326, "text": null }, { "code": null, "e": 34474, "s": 34466, "text": "Output:" }, { "code": null, "e": 34587, "s": 34474, "text": "53/53 [==============================] - 5s 95ms/step\nThe model achieved a loss of 0.23 and accuracy of 92.80%.\n" }, { "code": null, "e": 35309, "s": 34587, "text": "For a 101 class dataset, we have achieved a 92.8% accuracy after only 5 epochs. For perspective, the original ResNet was trained on an ~1 million image dataset, for 120 epochs.There are a couple of things that could be improved upon. For one, looking at the discrepancy between validation loss and training loss in the last epoch, you can see that the model is starting to overfit. One way to solve this is to add image augmentation. Simple image augmentation can be easily implemented with the ImageDataGenerator class. You could also play around with adding/removing layers or changing hyperparameters such as the dropout or the size of the Dense layer.Run this code here with Google Colab’s free GPU compute resources." }, { "code": null, "e": 35326, "s": 35309, "text": "Machine Learning" }, { "code": null, "e": 35333, "s": 35326, "text": "Python" }, { "code": null, "e": 35350, "s": 35333, "text": "Machine Learning" }, { "code": null, "e": 35448, "s": 35350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35489, "s": 35448, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 35522, "s": 35489, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 35550, "s": 35522, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 35586, "s": 35550, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 35641, "s": 35586, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 35669, "s": 35641, "text": "Read JSON file using Python" }, { "code": null, "e": 35719, "s": 35669, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 35741, "s": 35719, "text": "Python map() function" } ]
How to hide sensitive credentials using Python - GeeksforGeeks
14 Sep, 2021 Have you ever been in a situation where you are working on a python project need to share your code with someone or you are hosting your code in a public repository but don’t want to share the sensitive credentials so it isn’t exploited by a random user? For example, you are making a web app in Django, where there is a concept of ‘SECRET_KEY’ which is a randomly generated unique key and is used for cryptographic signing of data. As the name suggests it should not be publicly shared as it defeats many of Django’s security protections. Or maybe you are using cloud storage say AWS S3, you will need to store the access token in the code and also prevent unauthorized users to misuse the credentials, how can we do both? For such cases, we need to prevent hardcoding of the ‘key’ (essentially the variables holding our credentials) into our code and subsequently not exposing it in our public repository. One of the easiest and basic methods is to save the credentials in another python file say secrets.py and import it into the required file. We need to .gitignore the secrets.py file. Now we can store the credentials in essentially two ways, the first being to use python variables to store the values and the second more preferred way is to use a dictionary. Dictionary is preferred because if we try to access a non-existent variable, it will raise an error but in the case of the dictionary, we can return a default value. We have saved the following credentials in a dictionary in secrets.py: Python3 # secrets.pysecrets = { 'SECRET_KEY': "superSecretkey1234", 'DATABASE_USER': "testusr", 'DATABASE_PASSWORD': 'pass1234', 'DATABASE_PORT': 5432 } Now import the credentials in the required file, main.py. Python3 # main.pyfrom secrets import secrets secret_key = secrets.get('SECRET_KEY') # gives default value if the credential is absentgoogle_maps_key = secrets.get('gmaps_key', 'mapsapikey543') db_user = secrets.get('DATABASE_USER', 'root')db_pass = secrets.get('DATABASE_PASSWORD', 'pass')db_port = secrets.get('DATABASE_PORT', 3306) print('secret_key :', secret_key)print('google_maps_key :', google_maps_key)print('db_user :', db_user)print('db_pass :', db_pass) # no need to type cast numbers and booleansprint('db_port :', db_port, type(db_port)) Output : This works and we don’t need to worry about data type conversion of boolean and integer values(you will understand why this is important in the later methods) but isn’t the recommended approach because the file name and dictionary name can vary for different projects so it doesn’t form a standard solution. More importantly, this approach is restricted to python as in a more realistic scenario we could be working with multiple languages which also require access to the same credentials, and storing them in a way that is only accessible to one language isn’t ideal. A better approach is to use environment variables. We can store the credentials as environment variables. Environment variables are essentially key-value pairs that are set using the functionality of the operating system and can be used by any programming language since they are linked to the environment or operating system. Since we are setting credentials as environment variables we aren’t exposing them in our code, so if someone else has the access to our code the credentials wouldn’t be set in their environment. Also, we can set different values for production and local environments like using a different mailing service while in development and we don’t need to worry about changing the code. Many hosting providers like Heroku, netlify, etc. provide an easy way to set the environment variables. In python we can access the environment variables using os.environ and it works very similar to a normal python dictionary. os.environ returns string values and we need to manually typecast every value. Assuming we have set the same credentials mentioned above as environment variables. Python3 # main.pyimport os def convert(val): if type(val) != str: return val if val.isnumeric(): return int(val) elif val == 'True': return True elif val == 'False': return False else: return val secret_key = convert(os.environ.get('SECRET_KEY')) # gives default value if the credential is absentgoogle_maps_key = convert(os.environ.get('gmaps_key', 'mapsapikey543'))db_user = convert(os.environ.get('DATABASE_USER', 'root'))db_pass = convert(os.environ.get('DATABASE_PASSWORD', 'pass'))db_port = convert(os.environ.get('DATABASE_PORT', '3306')) print('secret_key :', secret_key)print('google_maps_key :', google_maps_key)print('db_user :', db_user)print('db_pass :', db_pass)print('db_port :', db_port, type(db_port)) Output : Also, environment variables set locally during development are persistent only for a session so we need to manually set them every time before we run our project. To make the process simpler we have an awesome package called python-decouple. The package helps in loading the credentials both from the environment or from an external .env or .ini file. We store the credentials in a .env or settings.ini file and gitignore them. python-decouple searches for options in this order : Environment variables.ini or .env file.default value passed during the call. Environment variables. ini or .env file. default value passed during the call. If the environment variable is already set it returns the same otherwise tries to read from the file and if not found it can return a default value. So it can read from the environment while in production and from the file while in development. Follow the simple 3 step process below: Step 1: Install python-decouple using pip. pip install python-decouple Step 2: Store your credentials separately. First, we need to ‘decouple’ our credentials from our code repository into a separate file. If you are using a version control system say git make sure to add this file to .gitignore. The file should be in one of the following forms and should be saved at the repository’s root directory: settings.ini .env -notice there is no name to the file These are popular file formats to save the configuration for the project. The files follow the syntax: KEY=YOUR_KEY -> without any quotes. As a convention, we store the key name in all caps. Here we are using .env format with the following credentials saved: Now, we will .gitignore this file. To know more about .gitignore read this: Step 3: Load your credentials securely. We can cast values by specifying the “cast” parameter to the corresponding type. Also if we do not specify a default value and the config object cannot find the given key it will raise an “UndefinedValueError”. Python3 # main.py # 1. Import the config object from decouple.from decouple import config # 2. Retrieve the credentials in your code. # default data-type of returned value is str.SECRET_KEY = config('SECRET_KEY') # you can cast the values on the fly.DEBUG = config('DEBUG', cast=bool) # provide defaulft value if key is not found.EMAIL_HOST = config('EMAIL_HOST', default='localhost') EMAIL_USER = config('EMAIL_USER', default='gfg') # if key not found and no default is given,# it will raise UndefinedValueError.EMAIL_PASSWORD = config('EMAIL_PASSWORD') EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int) print('secret_key :', SECRET_KEY)print('email_host :', EMAIL_HOST)print('email_user :', EMAIL_USER)print('email_pass :', EMAIL_PASSWORD)print('email_port :', EMAIL_PORT, type(EMAIL_PORT)) Output: python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25811, "s": 25783, "text": "\n14 Sep, 2021" }, { "code": null, "e": 26066, "s": 25811, "text": "Have you ever been in a situation where you are working on a python project need to share your code with someone or you are hosting your code in a public repository but don’t want to share the sensitive credentials so it isn’t exploited by a random user?" }, { "code": null, "e": 26719, "s": 26066, "text": "For example, you are making a web app in Django, where there is a concept of ‘SECRET_KEY’ which is a randomly generated unique key and is used for cryptographic signing of data. As the name suggests it should not be publicly shared as it defeats many of Django’s security protections. Or maybe you are using cloud storage say AWS S3, you will need to store the access token in the code and also prevent unauthorized users to misuse the credentials, how can we do both? For such cases, we need to prevent hardcoding of the ‘key’ (essentially the variables holding our credentials) into our code and subsequently not exposing it in our public repository." }, { "code": null, "e": 27244, "s": 26719, "text": "One of the easiest and basic methods is to save the credentials in another python file say secrets.py and import it into the required file. We need to .gitignore the secrets.py file. Now we can store the credentials in essentially two ways, the first being to use python variables to store the values and the second more preferred way is to use a dictionary. Dictionary is preferred because if we try to access a non-existent variable, it will raise an error but in the case of the dictionary, we can return a default value." }, { "code": null, "e": 27315, "s": 27244, "text": "We have saved the following credentials in a dictionary in secrets.py:" }, { "code": null, "e": 27323, "s": 27315, "text": "Python3" }, { "code": "# secrets.pysecrets = { 'SECRET_KEY': \"superSecretkey1234\", 'DATABASE_USER': \"testusr\", 'DATABASE_PASSWORD': 'pass1234', 'DATABASE_PORT': 5432 }", "e": 27481, "s": 27323, "text": null }, { "code": null, "e": 27540, "s": 27481, "text": "Now import the credentials in the required file, main.py. " }, { "code": null, "e": 27548, "s": 27540, "text": "Python3" }, { "code": "# main.pyfrom secrets import secrets secret_key = secrets.get('SECRET_KEY') # gives default value if the credential is absentgoogle_maps_key = secrets.get('gmaps_key', 'mapsapikey543') db_user = secrets.get('DATABASE_USER', 'root')db_pass = secrets.get('DATABASE_PASSWORD', 'pass')db_port = secrets.get('DATABASE_PORT', 3306) print('secret_key :', secret_key)print('google_maps_key :', google_maps_key)print('db_user :', db_user)print('db_pass :', db_pass) # no need to type cast numbers and booleansprint('db_port :', db_port, type(db_port))", "e": 28126, "s": 27548, "text": null }, { "code": null, "e": 28135, "s": 28126, "text": "Output :" }, { "code": null, "e": 28756, "s": 28135, "text": "This works and we don’t need to worry about data type conversion of boolean and integer values(you will understand why this is important in the later methods) but isn’t the recommended approach because the file name and dictionary name can vary for different projects so it doesn’t form a standard solution. More importantly, this approach is restricted to python as in a more realistic scenario we could be working with multiple languages which also require access to the same credentials, and storing them in a way that is only accessible to one language isn’t ideal. A better approach is to use environment variables." }, { "code": null, "e": 29412, "s": 28756, "text": "We can store the credentials as environment variables. Environment variables are essentially key-value pairs that are set using the functionality of the operating system and can be used by any programming language since they are linked to the environment or operating system. Since we are setting credentials as environment variables we aren’t exposing them in our code, so if someone else has the access to our code the credentials wouldn’t be set in their environment. Also, we can set different values for production and local environments like using a different mailing service while in development and we don’t need to worry about changing the code. " }, { "code": null, "e": 29806, "s": 29412, "text": "Many hosting providers like Heroku, netlify, etc. provide an easy way to set the environment variables. In python we can access the environment variables using os.environ and it works very similar to a normal python dictionary. os.environ returns string values and we need to manually typecast every value. Assuming we have set the same credentials mentioned above as environment variables. " }, { "code": null, "e": 29814, "s": 29806, "text": "Python3" }, { "code": "# main.pyimport os def convert(val): if type(val) != str: return val if val.isnumeric(): return int(val) elif val == 'True': return True elif val == 'False': return False else: return val secret_key = convert(os.environ.get('SECRET_KEY')) # gives default value if the credential is absentgoogle_maps_key = convert(os.environ.get('gmaps_key', 'mapsapikey543'))db_user = convert(os.environ.get('DATABASE_USER', 'root'))db_pass = convert(os.environ.get('DATABASE_PASSWORD', 'pass'))db_port = convert(os.environ.get('DATABASE_PORT', '3306')) print('secret_key :', secret_key)print('google_maps_key :', google_maps_key)print('db_user :', db_user)print('db_pass :', db_pass)print('db_port :', db_port, type(db_port))", "e": 30628, "s": 29814, "text": null }, { "code": null, "e": 30637, "s": 30628, "text": "Output :" }, { "code": null, "e": 30989, "s": 30637, "text": "Also, environment variables set locally during development are persistent only for a session so we need to manually set them every time before we run our project. To make the process simpler we have an awesome package called python-decouple. The package helps in loading the credentials both from the environment or from an external .env or .ini file." }, { "code": null, "e": 31118, "s": 30989, "text": "We store the credentials in a .env or settings.ini file and gitignore them. python-decouple searches for options in this order :" }, { "code": null, "e": 31195, "s": 31118, "text": "Environment variables.ini or .env file.default value passed during the call." }, { "code": null, "e": 31218, "s": 31195, "text": "Environment variables." }, { "code": null, "e": 31236, "s": 31218, "text": "ini or .env file." }, { "code": null, "e": 31274, "s": 31236, "text": "default value passed during the call." }, { "code": null, "e": 31520, "s": 31274, "text": "If the environment variable is already set it returns the same otherwise tries to read from the file and if not found it can return a default value. So it can read from the environment while in production and from the file while in development. " }, { "code": null, "e": 31560, "s": 31520, "text": "Follow the simple 3 step process below:" }, { "code": null, "e": 31603, "s": 31560, "text": "Step 1: Install python-decouple using pip." }, { "code": null, "e": 31631, "s": 31603, "text": "pip install python-decouple" }, { "code": null, "e": 31674, "s": 31631, "text": "Step 2: Store your credentials separately." }, { "code": null, "e": 31963, "s": 31674, "text": "First, we need to ‘decouple’ our credentials from our code repository into a separate file. If you are using a version control system say git make sure to add this file to .gitignore. The file should be in one of the following forms and should be saved at the repository’s root directory:" }, { "code": null, "e": 31976, "s": 31963, "text": "settings.ini" }, { "code": null, "e": 32020, "s": 31976, "text": ".env -notice there is no name to the file" }, { "code": null, "e": 32123, "s": 32020, "text": "These are popular file formats to save the configuration for the project. The files follow the syntax:" }, { "code": null, "e": 32162, "s": 32123, "text": "KEY=YOUR_KEY -> without any quotes." }, { "code": null, "e": 32214, "s": 32162, "text": "As a convention, we store the key name in all caps." }, { "code": null, "e": 32282, "s": 32214, "text": "Here we are using .env format with the following credentials saved:" }, { "code": null, "e": 32358, "s": 32282, "text": "Now, we will .gitignore this file. To know more about .gitignore read this:" }, { "code": null, "e": 32399, "s": 32358, "text": "Step 3: Load your credentials securely. " }, { "code": null, "e": 32611, "s": 32399, "text": "We can cast values by specifying the “cast” parameter to the corresponding type. Also if we do not specify a default value and the config object cannot find the given key it will raise an “UndefinedValueError”." }, { "code": null, "e": 32619, "s": 32611, "text": "Python3" }, { "code": "# main.py # 1. Import the config object from decouple.from decouple import config # 2. Retrieve the credentials in your code. # default data-type of returned value is str.SECRET_KEY = config('SECRET_KEY') # you can cast the values on the fly.DEBUG = config('DEBUG', cast=bool) # provide defaulft value if key is not found.EMAIL_HOST = config('EMAIL_HOST', default='localhost') EMAIL_USER = config('EMAIL_USER', default='gfg') # if key not found and no default is given,# it will raise UndefinedValueError.EMAIL_PASSWORD = config('EMAIL_PASSWORD') EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int) print('secret_key :', SECRET_KEY)print('email_host :', EMAIL_HOST)print('email_user :', EMAIL_USER)print('email_pass :', EMAIL_PASSWORD)print('email_port :', EMAIL_PORT, type(EMAIL_PORT))", "e": 33477, "s": 32619, "text": null }, { "code": null, "e": 33485, "s": 33477, "text": "Output:" }, { "code": null, "e": 33500, "s": 33485, "text": "python-utility" }, { "code": null, "e": 33507, "s": 33500, "text": "Python" }, { "code": null, "e": 33605, "s": 33507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33623, "s": 33605, "text": "Python Dictionary" }, { "code": null, "e": 33658, "s": 33623, "text": "Read a file line by line in Python" }, { "code": null, "e": 33690, "s": 33658, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33712, "s": 33690, "text": "Enumerate() in Python" }, { "code": null, "e": 33754, "s": 33712, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 33784, "s": 33754, "text": "Iterate over a list in Python" }, { "code": null, "e": 33810, "s": 33784, "text": "Python String | replace()" }, { "code": null, "e": 33839, "s": 33810, "text": "*args and **kwargs in Python" }, { "code": null, "e": 33883, "s": 33839, "text": "Reading and Writing to text files in Python" } ]
How to scroll down a webpage in selenium using Java?
We can scroll down a webpage in Selenium using Java. Selenium is unable to handle scrolling directly. It takes the help of the Javascript Executor to perform the scrolling action up to an element. First of all, we have to locate the element up to which we have to scroll. Next, we shall use the Javascript Executor to run the Javascript commands. The method executeScript is used to run Javascript commands in Selenium. We shall take the help of the scrollIntoView method in Javascript and pass true as an argument to the method. Syntax − WebElement elm = driver.findElement(By.name("name")); ((JavascriptExecutor) driver) .executeScript("arguments[0].scrollIntoView(true);", elm); import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ScrollAction{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); //launch application driver.get ("https://www.tutorialspoint.com/about/about_careers.htm "); // identify element WebElement n=driver.findElement(By.xpath("//*[text()='Contact']")); // Javascript executor ((JavascriptExecutor)driver) .executeScript("arguments[0].scrollIntoView(true);", n); } }
[ { "code": null, "e": 1259, "s": 1062, "text": "We can scroll down a webpage in Selenium using Java. Selenium is unable to handle scrolling directly. It takes the help of the Javascript Executor to perform the scrolling action up to an element." }, { "code": null, "e": 1592, "s": 1259, "text": "First of all, we have to locate the element up to which we have to scroll. Next, we shall use the Javascript Executor to run the Javascript commands. The method executeScript is used to run Javascript commands in Selenium. We shall take the\nhelp of the scrollIntoView method in Javascript and pass true as an argument to the method." }, { "code": null, "e": 1601, "s": 1592, "text": "Syntax −" }, { "code": null, "e": 1744, "s": 1601, "text": "WebElement elm = driver.findElement(By.name(\"name\"));\n((JavascriptExecutor) driver)\n.executeScript(\"arguments[0].scrollIntoView(true);\", elm);" }, { "code": null, "e": 2647, "s": 1744, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ScrollAction{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n //launch application\n driver.get\n (\"https://www.tutorialspoint.com/about/about_careers.htm \");\n // identify element\n WebElement n=driver.findElement(By.xpath(\"//*[text()='Contact']\"));\n // Javascript executor\n ((JavascriptExecutor)driver)\n .executeScript(\"arguments[0].scrollIntoView(true);\", n);\n }\n}" } ]
Convert characters of a string to opposite case in C++
We are given a string of any length and the task is to convert the string having uppercase letters to lowercase letters and lowercase letters to uppercase letters. Input − string str = ”Welcome To The Site!” Output − wELCOME tO tHE sITE! Explanation − converted the letters W, T, T, S to lowercase and letters e,l,c,o,m,e,o,,i,t,e to uppercase and it doesn’t perform any operations to the special characters. Input − string str = ”HELLO” Output − hello Explanation − converted the letters H,E,L,L,E to lowercase. Using inbuilt functions provided by C++ to perform these operations and those are toLowerCase(char) and toUpperCase(char). Using inbuilt functions provided by C++ to perform these operations and those are toLowerCase(char) and toUpperCase(char). Through the logic, which we are implementing in the below program. Through the logic, which we are implementing in the below program. Input the string of any length Input the string of any length Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces. Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces. The ASCII values of uppercase letters[A-Z] start with 65 till 90 and lowercase letters[a-z] starts with 97 till 122. The ASCII values of uppercase letters[A-Z] start with 65 till 90 and lowercase letters[a-z] starts with 97 till 122. Start the loop which will compare each letter in a string. If a letter is in uppercase then add 32 to convert it to lowercase and if the letter is in lowercase then subtract 32 to convert it to uppercase. Start the loop which will compare each letter in a string. If a letter is in uppercase then add 32 to convert it to lowercase and if the letter is in lowercase then subtract 32 to convert it to uppercase. Print the string. Print the string. Live Demo #include<iostream> using namespace std; void Convert_case(string &str){ //calculate the length of a string int len = str.length(); //converting lowercase to uppercase and vice versa for (int i=0; i<len; i++){ if (str[i]>='a' && str[i]<='z'){ str[i] = str[i] - 32; } else if(str[i]>='A' && str[i]<='Z'){ str[i] = str[i] + 32; } } } int main(){ string str = "What’s Your Name?"; cout<<"String before conversion is: "<<str; Convert_case(str); cout<<"\nString after conversion is: "<<str; return 0; } If we run the above code it will generate the following output − String before conversion is − What’s Your Name? String after conversion is &mius; wHAT’S yOUR nAME?
[ { "code": null, "e": 1226, "s": 1062, "text": "We are given a string of any length and the task is to convert the string having uppercase letters to lowercase letters and lowercase letters to uppercase letters." }, { "code": null, "e": 1270, "s": 1226, "text": "Input − string str = ”Welcome To The Site!”" }, { "code": null, "e": 1300, "s": 1270, "text": "Output − wELCOME tO tHE sITE!" }, { "code": null, "e": 1471, "s": 1300, "text": "Explanation − converted the letters W, T, T, S to lowercase and letters e,l,c,o,m,e,o,,i,t,e to uppercase and it doesn’t perform any operations to the special characters." }, { "code": null, "e": 1500, "s": 1471, "text": "Input − string str = ”HELLO”" }, { "code": null, "e": 1515, "s": 1500, "text": "Output − hello" }, { "code": null, "e": 1575, "s": 1515, "text": "Explanation − converted the letters H,E,L,L,E to lowercase." }, { "code": null, "e": 1698, "s": 1575, "text": "Using inbuilt functions provided by C++ to perform these operations and those are\ntoLowerCase(char) and toUpperCase(char)." }, { "code": null, "e": 1821, "s": 1698, "text": "Using inbuilt functions provided by C++ to perform these operations and those are\ntoLowerCase(char) and toUpperCase(char)." }, { "code": null, "e": 1888, "s": 1821, "text": "Through the logic, which we are implementing in the below program." }, { "code": null, "e": 1955, "s": 1888, "text": "Through the logic, which we are implementing in the below program." }, { "code": null, "e": 1986, "s": 1955, "text": "Input the string of any length" }, { "code": null, "e": 2017, "s": 1986, "text": "Input the string of any length" }, { "code": null, "e": 2179, "s": 2017, "text": "Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces." }, { "code": null, "e": 2341, "s": 2179, "text": "Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces." }, { "code": null, "e": 2458, "s": 2341, "text": "The ASCII values of uppercase letters[A-Z] start with 65 till 90 and lowercase letters[a-z] starts with 97 till 122." }, { "code": null, "e": 2575, "s": 2458, "text": "The ASCII values of uppercase letters[A-Z] start with 65 till 90 and lowercase letters[a-z] starts with 97 till 122." }, { "code": null, "e": 2780, "s": 2575, "text": "Start the loop which will compare each letter in a string. If a letter is in uppercase then add 32 to convert it to lowercase and if the letter is in lowercase then subtract 32 to convert it to uppercase." }, { "code": null, "e": 2985, "s": 2780, "text": "Start the loop which will compare each letter in a string. If a letter is in uppercase then add 32 to convert it to lowercase and if the letter is in lowercase then subtract 32 to convert it to uppercase." }, { "code": null, "e": 3003, "s": 2985, "text": "Print the string." }, { "code": null, "e": 3021, "s": 3003, "text": "Print the string." }, { "code": null, "e": 3032, "s": 3021, "text": " Live Demo" }, { "code": null, "e": 3601, "s": 3032, "text": "#include<iostream>\nusing namespace std;\nvoid Convert_case(string &str){\n //calculate the length of a string\n int len = str.length();\n //converting lowercase to uppercase and vice versa\n for (int i=0; i<len; i++){\n if (str[i]>='a' && str[i]<='z'){\n str[i] = str[i] - 32;\n }\n else if(str[i]>='A' && str[i]<='Z'){\n str[i] = str[i] + 32;\n }\n }\n}\nint main(){\n string str = \"What’s Your Name?\";\n cout<<\"String before conversion is: \"<<str;\n Convert_case(str);\n cout<<\"\\nString after conversion is: \"<<str;\n return 0;\n}" }, { "code": null, "e": 3666, "s": 3601, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3766, "s": 3666, "text": "String before conversion is − What’s Your Name?\nString after conversion is &mius; wHAT’S yOUR nAME?" } ]
getline (string) in C++
It is used to extracts characters from the stream as unformatted input and stores them into s as a c-string, until either the extracted character is the delimiting character, or n characters have been written to s (including the terminating null character). The declaration is like: basic_istream& getline (char_type* s, streamsize n ); basic_istream& getline (char_type* s, streamsize n, char_type delim); The parameters are ‘s’ pointer to an array of characters, where the extracted characters are stored as a c_string. Next parameter is ‘n’ this is the maximum number of characters to write (including the terminating character). The third parameter is ‘delim’ Explicit delimiting character. The operation of extracting successive characters stops as soon as the next character to exact compares equal to this (using traits_type::eq) This function returns the basic_istream object (*this). Live Demo #include <iostream> using namespace std; int main () { char name[256], title[256]; cout << "Please, enter your name: "; cin.getline (name,256); cout << "Please, enter your favourite movie: "; cin.getline (title,256); cout << name << "'s favourite movie is " << title; } Please, enter your name: Jack Please, enter your favourite movie: The Boss Baby Jack's favourite movie is The Boss Baby
[ { "code": null, "e": 1345, "s": 1062, "text": "It is used to extracts characters from the stream as unformatted input and stores them into s as a c-string, until either the extracted character is the delimiting character, or n characters have been written to s (including the terminating null character). The declaration is like:" }, { "code": null, "e": 1469, "s": 1345, "text": "basic_istream& getline (char_type* s, streamsize n );\nbasic_istream& getline (char_type* s, streamsize n, char_type delim);" }, { "code": null, "e": 1899, "s": 1469, "text": "The parameters are ‘s’ pointer to an array of characters, where the extracted characters are stored as a c_string. Next parameter is ‘n’ this is the maximum number of characters to write (including the terminating character). The third parameter is ‘delim’ Explicit delimiting character. The operation of extracting successive characters stops as soon as the next character to exact compares equal to this (using traits_type::eq)" }, { "code": null, "e": 1955, "s": 1899, "text": "This function returns the basic_istream object (*this)." }, { "code": null, "e": 1966, "s": 1955, "text": " Live Demo" }, { "code": null, "e": 2254, "s": 1966, "text": "#include <iostream>\nusing namespace std;\nint main () {\n char name[256], title[256];\n cout << \"Please, enter your name: \";\n cin.getline (name,256);\n cout << \"Please, enter your favourite movie: \";\n cin.getline (title,256);\n cout << name << \"'s favourite movie is \" << title;\n}" }, { "code": null, "e": 2374, "s": 2254, "text": "Please, enter your name: Jack\nPlease, enter your favourite movie: The Boss Baby\nJack's favourite movie is The Boss Baby" } ]
How to create a pagination using JavaFX?
Pagination divides content up between pages and allows users to skip between pages or go in order through the content. You can create pagination by instantiating the javafx.scene.control.Pagination class. The following Example demonstrates the creation of a Pagination. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Pagination; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; public class PaginationExample extends Application { public void start(Stage stage) { //Creating a pagination Pagination pagination = new Pagination(); //Setting number of pages pagination.setPageCount(10); //Creating a vbox to hold the pagination VBox vbox = new VBox(); vbox.setSpacing(5); vbox.setPadding(new Insets(50, 50, 50, 60)); vbox.getChildren().addAll(pagination); //Setting the stage Group root = new Group(vbox); Scene scene = new Scene(root, 595, 200, Color.BEIGE); stage.setTitle("Pagination"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1267, "s": 1062, "text": "Pagination divides content up between pages and allows users to skip between pages or go in order through the content. You can create pagination by instantiating the javafx.scene.control.Pagination class." }, { "code": null, "e": 1332, "s": 1267, "text": "The following Example demonstrates the creation of a Pagination." }, { "code": null, "e": 2304, "s": 1332, "text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Pagination;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class PaginationExample extends Application {\n public void start(Stage stage) {\n //Creating a pagination\n Pagination pagination = new Pagination();\n //Setting number of pages\n pagination.setPageCount(10);\n //Creating a vbox to hold the pagination\n VBox vbox = new VBox();\n vbox.setSpacing(5);\n vbox.setPadding(new Insets(50, 50, 50, 60));\n vbox.getChildren().addAll(pagination);\n //Setting the stage\n Group root = new Group(vbox);\n Scene scene = new Scene(root, 595, 200, Color.BEIGE);\n stage.setTitle(\"Pagination\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Program to convert IntStream to String in Java - GeeksforGeeks
11 Dec, 2018 Given a Instream containing ASCII values, the task is to convert this Instream into a String containing the characters corresponding to the ASCII values. Examples: Input: IntStream = 71, 101, 101, 107, 115 Output: Geeks Input: IntStream = 71, 101, 101, 107, 115, 70, 111, 114, 71, 101, 101, 107, 115 Output: GeeksForGeeks Algorithm: Get the Instream to be converted.Convert the IntStream into String with the help of StringBuilderCollect the formed StringBuilderConvert the StringBuilder into String using toString() methods.Print the formed String. Get the Instream to be converted. Convert the IntStream into String with the help of StringBuilder Collect the formed StringBuilder Convert the StringBuilder into String using toString() methods. Print the formed String. Below is the implementation of the above approach: // Java program to convert// String to IntStream import java.util.stream.IntStream; class GFG { public static void main(String[] args) { // Get the String to be converted IntStream intStream = "Geeks".chars(); // Convert IntStream to String String string = intStream .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); // Print the String System.out.println("String: " + string); }} Output: String: Geeks Java - util package java-intstream Java-Stream-programs Java-String-Programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24149, "s": 24121, "text": "\n11 Dec, 2018" }, { "code": null, "e": 24303, "s": 24149, "text": "Given a Instream containing ASCII values, the task is to convert this Instream into a String containing the characters corresponding to the ASCII values." }, { "code": null, "e": 24313, "s": 24303, "text": "Examples:" }, { "code": null, "e": 24473, "s": 24313, "text": "Input: IntStream = 71, 101, 101, 107, 115\nOutput: Geeks\n\nInput: IntStream = 71, 101, 101, 107, 115, 70, 111, 114, 71, 101, 101, 107, 115\nOutput: GeeksForGeeks\n" }, { "code": null, "e": 24484, "s": 24473, "text": "Algorithm:" }, { "code": null, "e": 24701, "s": 24484, "text": "Get the Instream to be converted.Convert the IntStream into String with the help of StringBuilderCollect the formed StringBuilderConvert the StringBuilder into String using toString() methods.Print the formed String." }, { "code": null, "e": 24735, "s": 24701, "text": "Get the Instream to be converted." }, { "code": null, "e": 24800, "s": 24735, "text": "Convert the IntStream into String with the help of StringBuilder" }, { "code": null, "e": 24833, "s": 24800, "text": "Collect the formed StringBuilder" }, { "code": null, "e": 24897, "s": 24833, "text": "Convert the StringBuilder into String using toString() methods." }, { "code": null, "e": 24922, "s": 24897, "text": "Print the formed String." }, { "code": null, "e": 24973, "s": 24922, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to convert// String to IntStream import java.util.stream.IntStream; class GFG { public static void main(String[] args) { // Get the String to be converted IntStream intStream = \"Geeks\".chars(); // Convert IntStream to String String string = intStream .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); // Print the String System.out.println(\"String: \" + string); }}", "e": 25586, "s": 24973, "text": null }, { "code": null, "e": 25594, "s": 25586, "text": "Output:" }, { "code": null, "e": 25609, "s": 25594, "text": "String: Geeks\n" }, { "code": null, "e": 25629, "s": 25609, "text": "Java - util package" }, { "code": null, "e": 25644, "s": 25629, "text": "java-intstream" }, { "code": null, "e": 25665, "s": 25644, "text": "Java-Stream-programs" }, { "code": null, "e": 25686, "s": 25665, "text": "Java-String-Programs" }, { "code": null, "e": 25691, "s": 25686, "text": "Java" }, { "code": null, "e": 25705, "s": 25691, "text": "Java Programs" }, { "code": null, "e": 25710, "s": 25705, "text": "Java" }, { "code": null, "e": 25808, "s": 25710, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25817, "s": 25808, "text": "Comments" }, { "code": null, "e": 25830, "s": 25817, "text": "Old Comments" }, { "code": null, "e": 25862, "s": 25830, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 25881, "s": 25862, "text": "Interfaces in Java" }, { "code": null, "e": 25899, "s": 25881, "text": "ArrayList in Java" }, { "code": null, "e": 25931, "s": 25899, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 25951, "s": 25931, "text": "Stack Class in Java" }, { "code": null, "e": 25995, "s": 25951, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 26023, "s": 25995, "text": "Initializing a List in Java" }, { "code": null, "e": 26049, "s": 26023, "text": "Java Programming Examples" }, { "code": null, "e": 26083, "s": 26049, "text": "Convert Double to Integer in Java" } ]
PyTorch – torchvision.transforms – GaussianBlur()
The torchvision.transforms module provides many important transformations that can be used to perform different types of manipulations on the image data. GaussianBlur() transformation is used to blur an image with randomly chosen Gaussian blur. The GaussianBlur() transformation accepts both PIL and tensor images or a batch of tensor images. A tensor image is a PyTorch Tensor with shape [3, H, W], where H is the image height and W is the image width. A batch of tensor images is also a torch tensor with [B, 3, H, W] where B is the number of images in the batch. torchvision.transforms.GaussianBlur(kernel_size, sigma=(0.1,.2))(img) kernel_size – Size of Gaussian kernel. It must be a list or tuple of two integers. kernel_size – Size of Gaussian kernel. It must be a list or tuple of two integers. sigma – Standard deviation used in creating the Gaussian kernel. sigma – Standard deviation used in creating the Gaussian kernel. img – PIL image or tensor image to be blurred. img – PIL image or tensor image to be blurred. It returns a Gaussian blurred image. We could use the following steps to blur an image with a randomly chosen Gaussian blur − Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them. Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them. import torch import torchvision import torchvision.transforms as T from PIL import Image Read the input image. The input image is a PIL image or a torch tensor. Read the input image. The input image is a PIL image or a torch tensor. img = Image.open('spice.jpg') Define a transform to blur the input image with randomly chosen Gaussian blur. Define a transform to blur the input image with randomly chosen Gaussian blur. transform = T.GaussianBlur(kernel_size=(7, 13), sigma=(0.1, 0.2)) Apply the above-defined transform on the input image to blur the input image. Apply the above-defined transform on the input image to blur the input image. blurred_img = transform(img) Show the blurred image. Show the blurred image. blurred_img.show() This image is used as the input file in all the following examples. This example demonstrates how you can blur an input image with a randomly chosen Gaussian blur. # import required libraries import torch import torchvision.transforms as T from PIL import Image # read the input image img = Image.open('spice.jpg') # define the transform to blur image transform = T.GaussianBlur(kernel_size=(7, 13), sigma=(9, 11)) # blur the input image using the above defined transform img = transform(img) # display the blurred image img.show() It will produce the following output − The above output is the blurred image of original input image. Let's take another example − import torch import torchvision.transforms as T from PIL import Image import matplotlib.pyplot as plt # read the input image img = Image.open('spice.jpg') # define a transform with kernel size and sigma transform = T.GaussianBlur(kernel_size=(19, 23), sigma=(20, 25)) # apply the above transform on input image blurred_imgs = [transform(img) for _ in range(4)] fig = plt.figure(figsize=(7,4)) rows, cols = 2,2 for j in range(0, len(blurred_imgs)): fig.add_subplot(rows, cols, j+1) plt.imshow(blurred_imgs[j]) plt.xticks([]) plt.yticks([]) plt.show() It will produce the following output − Each of the output image is blurred with a random Gaussian blur chosen from a given range.
[ { "code": null, "e": 1307, "s": 1062, "text": "The torchvision.transforms module provides many important transformations that can be used to perform different types of manipulations on the image data. GaussianBlur() transformation is used to blur an image with randomly chosen Gaussian blur." }, { "code": null, "e": 1628, "s": 1307, "text": "The GaussianBlur() transformation accepts both PIL and tensor images or a batch of tensor images. A tensor image is a PyTorch Tensor with shape [3, H, W], where H is the image height and W is the image width. A batch of tensor images is also a torch tensor with [B, 3, H, W] where B is the number of images in the batch." }, { "code": null, "e": 1698, "s": 1628, "text": "torchvision.transforms.GaussianBlur(kernel_size, sigma=(0.1,.2))(img)" }, { "code": null, "e": 1781, "s": 1698, "text": "kernel_size – Size of Gaussian kernel. It must be a list or tuple of two integers." }, { "code": null, "e": 1864, "s": 1781, "text": "kernel_size – Size of Gaussian kernel. It must be a list or tuple of two integers." }, { "code": null, "e": 1929, "s": 1864, "text": "sigma – Standard deviation used in creating the Gaussian kernel." }, { "code": null, "e": 1994, "s": 1929, "text": "sigma – Standard deviation used in creating the Gaussian kernel." }, { "code": null, "e": 2041, "s": 1994, "text": "img – PIL image or tensor image to be blurred." }, { "code": null, "e": 2088, "s": 2041, "text": "img – PIL image or tensor image to be blurred." }, { "code": null, "e": 2125, "s": 2088, "text": "It returns a Gaussian blurred image." }, { "code": null, "e": 2214, "s": 2125, "text": "We could use the following steps to blur an image with a randomly chosen Gaussian blur −" }, { "code": null, "e": 2385, "s": 2214, "text": "Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them." }, { "code": null, "e": 2556, "s": 2385, "text": "Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them." }, { "code": null, "e": 2645, "s": 2556, "text": "import torch\nimport torchvision\nimport torchvision.transforms as T\nfrom PIL import Image" }, { "code": null, "e": 2717, "s": 2645, "text": "Read the input image. The input image is a PIL image or a torch tensor." }, { "code": null, "e": 2789, "s": 2717, "text": "Read the input image. The input image is a PIL image or a torch tensor." }, { "code": null, "e": 2819, "s": 2789, "text": "img = Image.open('spice.jpg')" }, { "code": null, "e": 2898, "s": 2819, "text": "Define a transform to blur the input image with randomly chosen Gaussian blur." }, { "code": null, "e": 2977, "s": 2898, "text": "Define a transform to blur the input image with randomly chosen Gaussian blur." }, { "code": null, "e": 3043, "s": 2977, "text": "transform = T.GaussianBlur(kernel_size=(7, 13), sigma=(0.1, 0.2))" }, { "code": null, "e": 3121, "s": 3043, "text": "Apply the above-defined transform on the input image to blur the input image." }, { "code": null, "e": 3199, "s": 3121, "text": "Apply the above-defined transform on the input image to blur the input image." }, { "code": null, "e": 3228, "s": 3199, "text": "blurred_img = transform(img)" }, { "code": null, "e": 3252, "s": 3228, "text": "Show the blurred image." }, { "code": null, "e": 3276, "s": 3252, "text": "Show the blurred image." }, { "code": null, "e": 3295, "s": 3276, "text": "blurred_img.show()" }, { "code": null, "e": 3363, "s": 3295, "text": "This image is used as the input file in all the following examples." }, { "code": null, "e": 3459, "s": 3363, "text": "This example demonstrates how you can blur an input image with a randomly\nchosen Gaussian blur." }, { "code": null, "e": 3831, "s": 3459, "text": "# import required libraries\nimport torch\nimport torchvision.transforms as T\nfrom PIL import Image\n\n# read the input image\nimg = Image.open('spice.jpg')\n\n# define the transform to blur image\ntransform = T.GaussianBlur(kernel_size=(7, 13), sigma=(9, 11))\n\n# blur the input image using the above defined transform\nimg = transform(img)\n\n# display the blurred image\nimg.show()" }, { "code": null, "e": 3870, "s": 3831, "text": "It will produce the following output −" }, { "code": null, "e": 3933, "s": 3870, "text": "The above output is the blurred image of original input image." }, { "code": null, "e": 3962, "s": 3933, "text": "Let's take another example −" }, { "code": null, "e": 4527, "s": 3962, "text": "import torch\nimport torchvision.transforms as T\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n# read the input image\nimg = Image.open('spice.jpg')\n\n# define a transform with kernel size and sigma\ntransform = T.GaussianBlur(kernel_size=(19, 23), sigma=(20, 25))\n\n# apply the above transform on input image\nblurred_imgs = [transform(img) for _ in range(4)]\nfig = plt.figure(figsize=(7,4))\nrows, cols = 2,2\nfor j in range(0, len(blurred_imgs)):\n fig.add_subplot(rows, cols, j+1)\n plt.imshow(blurred_imgs[j])\n plt.xticks([])\n plt.yticks([])\nplt.show()" }, { "code": null, "e": 4566, "s": 4527, "text": "It will produce the following output −" }, { "code": null, "e": 4657, "s": 4566, "text": "Each of the output image is blurred with a random Gaussian blur chosen from a\ngiven range." } ]
Flattening a JSON object in JavaScript
Suppose, we have the following JSON object that may contain nesting upto any level − const obj = { "one": 1, "two": { "three": 3 }, "four": { "five": 5, "six": { "seven": 7 }, "eight": 8 }, "nine": 9 }; We are required to write a JavaScript function that takes in one such nested JSON object and returns a new object that contains no nesting and maps the corresponding values to the keys using the dot notation. Therefore, in case of the object above, the output should look something like this − const output = { 'one': 1, 'two.three': 3, 'four.five': 5, 'four.six.seven': 7, 'four.eight': 8, 'nine': 9 }; The code for this will be − Live Demo const obj = { "one": 1, "two": { "three": 3 }, "four": { "five": 5, "six": { "seven": 7 }, "eight": 8 }, "nine": 9 }; const flattenJSON = (obj = {}, res = {}, extraKey = '') => { for(key in obj){ if(typeof obj[key] !== 'object'){ res[extraKey + key] = obj[key]; }else{ flattenJSON(obj[key], res, `${extraKey}${key}.`); }; }; return res; }; console.log(flattenJSON(obj)); And the output in the console will be − { one: 1, 'two.three': 3, 'four.five': 5, 'four.six.seven': 7, 'four.eight': 8, nine: 9 }
[ { "code": null, "e": 1147, "s": 1062, "text": "Suppose, we have the following JSON object that may contain nesting upto any level −" }, { "code": null, "e": 1322, "s": 1147, "text": "const obj = {\n \"one\": 1,\n \"two\": {\n \"three\": 3\n },\n \"four\": {\n \"five\": 5,\n \"six\": {\n \"seven\": 7\n },\n \"eight\": 8\n },\n \"nine\": 9\n};" }, { "code": null, "e": 1531, "s": 1322, "text": "We are required to write a JavaScript function that takes in one such nested JSON object and returns a new object that contains no nesting and maps the corresponding values to the keys using the dot notation." }, { "code": null, "e": 1616, "s": 1531, "text": "Therefore, in case of the object above, the output should look something like this −" }, { "code": null, "e": 1744, "s": 1616, "text": "const output = {\n 'one': 1,\n 'two.three': 3,\n 'four.five': 5,\n 'four.six.seven': 7,\n 'four.eight': 8,\n 'nine': 9\n};" }, { "code": null, "e": 1772, "s": 1744, "text": "The code for this will be −" }, { "code": null, "e": 1783, "s": 1772, "text": " Live Demo" }, { "code": null, "e": 2256, "s": 1783, "text": "const obj = {\n \"one\": 1,\n \"two\": {\n \"three\": 3\n },\n \"four\": {\n \"five\": 5,\n \"six\": {\n \"seven\": 7\n },\n \"eight\": 8\n },\n \"nine\": 9\n};\nconst flattenJSON = (obj = {}, res = {}, extraKey = '') => {\n for(key in obj){\n if(typeof obj[key] !== 'object'){\n res[extraKey + key] = obj[key];\n }else{\n flattenJSON(obj[key], res, `${extraKey}${key}.`);\n };\n };\n return res;\n};\nconsole.log(flattenJSON(obj));" }, { "code": null, "e": 2296, "s": 2256, "text": "And the output in the console will be −" }, { "code": null, "e": 2404, "s": 2296, "text": "{\n one: 1,\n 'two.three': 3,\n 'four.five': 5,\n 'four.six.seven': 7,\n 'four.eight': 8,\n nine: 9\n}" } ]
How to append a list to a Pandas DataFrame using append() in Python?
To append a list to a DataFrame using append(), let us first create a DataFrame. The data is in the form of lists of team rankings for our example − # data in the form of list of team rankings Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50]] # Creating a DataFrame and adding columns dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points']) Let’s say the following is the row to be append − myList = [["Sri Lanka", 6, 40]] Append the above row in the form of list using append() − dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True) Following is the code − import pandas as pd # data in the form of list of team rankings Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50]] # Creating a DataFrame and adding columns dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points']) print"DataFrame...\n",dataFrame # row to be appended myList = [["Sri Lanka", 6, 40]] # append the above row in the form of list dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True) # display the update dataframe print"\nUpdated DataFrame after appending a row...\n",dataFrame This will produce the following output − DataFrame... Country Rank Points 0 India 1 100 1 Australia 2 85 2 England 3 75 3 New Zealand 4 65 4 South Africa 5 50 Updated DataFrame after appending a row... Country Rank Points 0 India 1 100 1 Australia 2 85 2 England 3 75 3 New Zealand 4 65 4 South Africa 5 50 5 Sri Lanka 6 40
[ { "code": null, "e": 1211, "s": 1062, "text": "To append a list to a DataFrame using append(), let us first create a DataFrame. The data is in the form of lists of team rankings for our example −" }, { "code": null, "e": 1483, "s": 1211, "text": "# data in the form of list of team rankings\nTeam = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50]]\n\n# Creating a DataFrame and adding columns\ndataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])" }, { "code": null, "e": 1533, "s": 1483, "text": "Let’s say the following is the row to be append −" }, { "code": null, "e": 1566, "s": 1533, "text": "myList = [[\"Sri Lanka\", 6, 40]]\n" }, { "code": null, "e": 1624, "s": 1566, "text": "Append the above row in the form of list using append() −" }, { "code": null, "e": 1733, "s": 1624, "text": "dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True)" }, { "code": null, "e": 1757, "s": 1733, "text": "Following is the code −" }, { "code": null, "e": 2386, "s": 1757, "text": "import pandas as pd\n\n# data in the form of list of team rankings\nTeam = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50]]\n\n# Creating a DataFrame and adding columns\ndataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])\n\nprint\"DataFrame...\\n\",dataFrame\n\n# row to be appended\nmyList = [[\"Sri Lanka\", 6, 40]]\n\n# append the above row in the form of list\ndataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True)\n\n# display the update dataframe\nprint\"\\nUpdated DataFrame after appending a row...\\n\",dataFrame" }, { "code": null, "e": 2427, "s": 2386, "text": "This will produce the following output −" }, { "code": null, "e": 2900, "s": 2427, "text": "DataFrame...\n Country Rank Points\n0 India 1 100\n1 Australia 2 85\n2 England 3 75\n3 New Zealand 4 65\n4 South Africa 5 50\n\nUpdated DataFrame after appending a row...\n Country Rank Points\n0 India 1 100\n1 Australia 2 85\n2 England 3 75\n3 New Zealand 4 65\n4 South Africa 5 50\n5 Sri Lanka 6 40" } ]
Pass array to MySQL stored routine?
We need to create a stored procedure to display how to pass array to MySQL stored routine. Let us first create a table for our example. Creating a table mysql> create table FindDemo -> ( -> name varchar(100) -> ); Query OK, 0 rows affected (0.46 sec) Inserting some records into the table. mysql> insert into FindDemo values('John'),('Smith'); Query OK, 2 rows affected (0.13 sec) Records: 2 Duplicates: 0 Warnings: 0 To display all records. mysql> select *from FindDemo; The following is the output. +-------+ | name | +-------+ | John | | Smith | +-------+ 2 rows in set (0.00 sec) To create a stored routine that accepts an array as a parameter. mysql> delimiter // mysql>CREATE PROCEDURE SearchingStoredProcedure(IN ArrayDemo VARCHAR(100)) -> BEGIN -> SELECT * FROM FindDemo -> WHERE FIND_IN_SET(name, ArrayDemo); -> -> END// Query OK, 0 rows affected (0.14 sec) Passing array as a parameter. mysql> delimiter ; mysql> call SearchingStoredProcedure('David,Bob,John'); Here is the output. +------+ | name | +------+ | John | +------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.01 sec)
[ { "code": null, "e": 1198, "s": 1062, "text": "We need to create a stored procedure to display how to pass array to MySQL stored routine. Let us first create a table for our example." }, { "code": null, "e": 1215, "s": 1198, "text": "Creating a table" }, { "code": null, "e": 1322, "s": 1215, "text": "mysql> create table FindDemo\n -> (\n -> name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.46 sec)" }, { "code": null, "e": 1361, "s": 1322, "text": "Inserting some records into the table." }, { "code": null, "e": 1491, "s": 1361, "text": "mysql> insert into FindDemo values('John'),('Smith');\nQuery OK, 2 rows affected (0.13 sec)\nRecords: 2 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1515, "s": 1491, "text": "To display all records." }, { "code": null, "e": 1545, "s": 1515, "text": "mysql> select *from FindDemo;" }, { "code": null, "e": 1574, "s": 1545, "text": "The following is the output." }, { "code": null, "e": 1660, "s": 1574, "text": "+-------+\n| name |\n+-------+\n| John |\n| Smith |\n+-------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 1725, "s": 1660, "text": "To create a stored routine that accepts an array as a parameter." }, { "code": null, "e": 1967, "s": 1725, "text": "mysql> delimiter //\nmysql>CREATE PROCEDURE SearchingStoredProcedure(IN ArrayDemo VARCHAR(100))\n -> BEGIN\n -> SELECT * FROM FindDemo\n -> WHERE FIND_IN_SET(name, ArrayDemo);\n ->\n -> END//\nQuery OK, 0 rows affected (0.14 sec)" }, { "code": null, "e": 1997, "s": 1967, "text": "Passing array as a parameter." }, { "code": null, "e": 2072, "s": 1997, "text": "mysql> delimiter ;\nmysql> call SearchingStoredProcedure('David,Bob,John');" }, { "code": null, "e": 2092, "s": 2072, "text": "Here is the output." }, { "code": null, "e": 2200, "s": 2092, "text": "+------+\n| name |\n+------+\n| John |\n+------+\n1 row in set (0.00 sec)\n\nQuery OK, 0 rows affected (0.01 sec)\n" } ]
Alternative Sorting - GeeksforGeeks
26 Mar, 2021 Given an array of integers, print the array in such a way that the first element is first maximum and second element is first minimum and so on.Examples : Input : arr[] = {7, 1, 2, 3, 4, 5, 6} Output : 7 1 6 2 5 3 4 Input : arr[] = {1, 6, 9, 4, 3, 7, 8, 2} Output : 9 1 8 2 7 3 6 4 A simple solution is to first print maximum element, then minimum, then second maximum, and so on. Time complexity of this approach is O(n2).An efficient solution involves following steps. 1) Sort input array using a O(n Log n) algorithm. 2) We maintain two pointers, one from beginning and one from end in sorted array. We alternatively print elements pointed by two pointers and move them toward each other. C++ Java Python3 C# PHP Javascript // C++ program to print an array in alternate// sorted manner.#include <bits/stdc++.h>using namespace std; // Function to print alternate sorted valuesvoid alternateSort(int arr[], int n){ // Sorting the array sort(arr, arr+n); // Printing the last element of array // first and then first element and then // second last element and then second // element and so on. int i = 0, j = n-1; while (i < j) { cout << arr[j--] << " "; cout << arr[i++] << " "; } // If the total element in array is odd // then print the last middle element. if (n % 2 != 0) cout << arr[i];} // Driver codeint main(){ int arr[] = {1, 12, 4, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); alternateSort(arr, n); return 0;} // Java program to print an array in alternate// sorted mannerimport java.io.*;import java.util.Arrays; class AlternativeString{ // Function to print alternate sorted values static void alternateSort(int arr[], int n) { Arrays.sort(arr); // Printing the last element of array // first and then first element and then // second last element and then second // element and so on. int i = 0, j = n-1; while (i < j) { System.out.print(arr[j--] + " "); System.out.print(arr[i++] + " "); } // If the total element in array is odd // then print the last middle element. if (n % 2 != 0) System.out.print(arr[i]); } /* Driver program to test above functions */ public static void main (String[] args) { int arr[] = {1, 12, 4, 6, 7, 10}; int n = arr.length; alternateSort(arr, n); }}/*This code is contributed by Prakriti Gupta*/ # Python 3 program to print an array# in alternate sorted manner. # Function to print alternate sorted# valuesdef alternateSort(arr, n): # Sorting the array arr.sort() # Printing the last element of array # first and then first element and then # second last element and then second # element and so on. i = 0 j = n-1 while (i < j): print(arr[j], end =" ") j-= 1 print(arr[i], end =" ") i+= 1 # If the total element in array is odd # then print the last middle element. if (n % 2 != 0): print(arr[i]) # Driver codearr = [1, 12, 4, 6, 7, 10]n = len(arr) alternateSort(arr, n) # This code is contributed by# Smitha Dinesh Semwal // C# program to print an array in alternate// sorted mannerusing System; class AlternativeString { // Function to print alternate sorted values static void alternateSort(int[] arr, int n) { Array.Sort(arr); // Printing the last element of array // first and then first element and then // second last element and then second // element and so on. int i = 0, j = n - 1; while (i < j) { Console.Write(arr[j--] + " "); Console.Write(arr[i++] + " "); } // If the total element in array is odd // then print the last middle element. if (n % 2 != 0) Console.WriteLine(arr[i]); } /* Driver program to test above functions */ public static void Main() { int[] arr = { 1, 12, 4, 6, 7, 10 }; int n = arr.Length; alternateSort(arr, n); }} // This article is contributed by vt_m. <?php// PHP program to print an array in// alternate sorted manner. // Function to print alternate// sorted valuesfunction alternateSort($arr, $n){ // Sorting the array sort($arr); // Printing the last element // of array first and then // first element and then second // last element and then second // element and so on. $i = 0; $j = $n - 1; while ($i < $j) { echo $arr[$j--]." "; echo $arr[$i++]." "; } // If the total element in array // is odd then print the last // middle element. if ($n % 2 != 0) echo $arr[$i];} // Driver code$arr= array(1, 12, 4, 6, 7, 10);$n = sizeof($arr) / sizeof($arr[0]); alternateSort($arr, $n); // This code is contributed by Mithun Kumar?> <script> // JavaScript program to print an array in alternate // sorted manner. // Function to print alternate sorted values function alternateSort(arr, n) { // Sorting the array console.log(arr); arr.sort(function (a, b) { return a - b; }); console.log(arr); // Printing the last element of array // first and then first element and then // second last element and then second // element and so on. var i = 0, j = n - 1; while (i < j) { document.write(arr[j--] + " "); document.write(arr[i++] + " "); } // If the total element in array is odd // then print the last middle element. if (n % 2 != 0) document.write(arr[i]); } // Driver code var arr = [1, 12, 4, 6, 7, 10]; var n = arr.length; alternateSort(arr, n); // This code is contributed by rdtank. </script> Output : 12 1 10 4 7 6 Time Complexity: O(n Log n) Auxiliary Space : O(1)This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Varun Bothra Mithun Kumar rdtank array-rearrange Zoho Arrays Sorting Zoho Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
[ { "code": null, "e": 24473, "s": 24445, "text": "\n26 Mar, 2021" }, { "code": null, "e": 24630, "s": 24473, "text": "Given an array of integers, print the array in such a way that the first element is first maximum and second element is first minimum and so on.Examples : " }, { "code": null, "e": 24758, "s": 24630, "text": "Input : arr[] = {7, 1, 2, 3, 4, 5, 6}\nOutput : 7 1 6 2 5 3 4\n\nInput : arr[] = {1, 6, 9, 4, 3, 7, 8, 2}\nOutput : 9 1 8 2 7 3 6 4" }, { "code": null, "e": 25171, "s": 24760, "text": "A simple solution is to first print maximum element, then minimum, then second maximum, and so on. Time complexity of this approach is O(n2).An efficient solution involves following steps. 1) Sort input array using a O(n Log n) algorithm. 2) We maintain two pointers, one from beginning and one from end in sorted array. We alternatively print elements pointed by two pointers and move them toward each other. " }, { "code": null, "e": 25175, "s": 25171, "text": "C++" }, { "code": null, "e": 25180, "s": 25175, "text": "Java" }, { "code": null, "e": 25188, "s": 25180, "text": "Python3" }, { "code": null, "e": 25191, "s": 25188, "text": "C#" }, { "code": null, "e": 25195, "s": 25191, "text": "PHP" }, { "code": null, "e": 25206, "s": 25195, "text": "Javascript" }, { "code": "// C++ program to print an array in alternate// sorted manner.#include <bits/stdc++.h>using namespace std; // Function to print alternate sorted valuesvoid alternateSort(int arr[], int n){ // Sorting the array sort(arr, arr+n); // Printing the last element of array // first and then first element and then // second last element and then second // element and so on. int i = 0, j = n-1; while (i < j) { cout << arr[j--] << \" \"; cout << arr[i++] << \" \"; } // If the total element in array is odd // then print the last middle element. if (n % 2 != 0) cout << arr[i];} // Driver codeint main(){ int arr[] = {1, 12, 4, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); alternateSort(arr, n); return 0;}", "e": 25975, "s": 25206, "text": null }, { "code": "// Java program to print an array in alternate// sorted mannerimport java.io.*;import java.util.Arrays; class AlternativeString{ // Function to print alternate sorted values static void alternateSort(int arr[], int n) { Arrays.sort(arr); // Printing the last element of array // first and then first element and then // second last element and then second // element and so on. int i = 0, j = n-1; while (i < j) { System.out.print(arr[j--] + \" \"); System.out.print(arr[i++] + \" \"); } // If the total element in array is odd // then print the last middle element. if (n % 2 != 0) System.out.print(arr[i]); } /* Driver program to test above functions */ public static void main (String[] args) { int arr[] = {1, 12, 4, 6, 7, 10}; int n = arr.length; alternateSort(arr, n); }}/*This code is contributed by Prakriti Gupta*/", "e": 26959, "s": 25975, "text": null }, { "code": "# Python 3 program to print an array# in alternate sorted manner. # Function to print alternate sorted# valuesdef alternateSort(arr, n): # Sorting the array arr.sort() # Printing the last element of array # first and then first element and then # second last element and then second # element and so on. i = 0 j = n-1 while (i < j): print(arr[j], end =\" \") j-= 1 print(arr[i], end =\" \") i+= 1 # If the total element in array is odd # then print the last middle element. if (n % 2 != 0): print(arr[i]) # Driver codearr = [1, 12, 4, 6, 7, 10]n = len(arr) alternateSort(arr, n) # This code is contributed by# Smitha Dinesh Semwal", "e": 27671, "s": 26959, "text": null }, { "code": "// C# program to print an array in alternate// sorted mannerusing System; class AlternativeString { // Function to print alternate sorted values static void alternateSort(int[] arr, int n) { Array.Sort(arr); // Printing the last element of array // first and then first element and then // second last element and then second // element and so on. int i = 0, j = n - 1; while (i < j) { Console.Write(arr[j--] + \" \"); Console.Write(arr[i++] + \" \"); } // If the total element in array is odd // then print the last middle element. if (n % 2 != 0) Console.WriteLine(arr[i]); } /* Driver program to test above functions */ public static void Main() { int[] arr = { 1, 12, 4, 6, 7, 10 }; int n = arr.Length; alternateSort(arr, n); }} // This article is contributed by vt_m.", "e": 28603, "s": 27671, "text": null }, { "code": "<?php// PHP program to print an array in// alternate sorted manner. // Function to print alternate// sorted valuesfunction alternateSort($arr, $n){ // Sorting the array sort($arr); // Printing the last element // of array first and then // first element and then second // last element and then second // element and so on. $i = 0; $j = $n - 1; while ($i < $j) { echo $arr[$j--].\" \"; echo $arr[$i++].\" \"; } // If the total element in array // is odd then print the last // middle element. if ($n % 2 != 0) echo $arr[$i];} // Driver code$arr= array(1, 12, 4, 6, 7, 10);$n = sizeof($arr) / sizeof($arr[0]); alternateSort($arr, $n); // This code is contributed by Mithun Kumar?>", "e": 29353, "s": 28603, "text": null }, { "code": "<script> // JavaScript program to print an array in alternate // sorted manner. // Function to print alternate sorted values function alternateSort(arr, n) { // Sorting the array console.log(arr); arr.sort(function (a, b) { return a - b; }); console.log(arr); // Printing the last element of array // first and then first element and then // second last element and then second // element and so on. var i = 0, j = n - 1; while (i < j) { document.write(arr[j--] + \" \"); document.write(arr[i++] + \" \"); } // If the total element in array is odd // then print the last middle element. if (n % 2 != 0) document.write(arr[i]); } // Driver code var arr = [1, 12, 4, 6, 7, 10]; var n = arr.length; alternateSort(arr, n); // This code is contributed by rdtank. </script>", "e": 30348, "s": 29353, "text": null }, { "code": null, "e": 30359, "s": 30348, "text": "Output : " }, { "code": null, "e": 30374, "s": 30359, "text": "12 1 10 4 7 6 " }, { "code": null, "e": 30845, "s": 30374, "text": "Time Complexity: O(n Log n) Auxiliary Space : O(1)This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30858, "s": 30845, "text": "Varun Bothra" }, { "code": null, "e": 30871, "s": 30858, "text": "Mithun Kumar" }, { "code": null, "e": 30878, "s": 30871, "text": "rdtank" }, { "code": null, "e": 30894, "s": 30878, "text": "array-rearrange" }, { "code": null, "e": 30899, "s": 30894, "text": "Zoho" }, { "code": null, "e": 30906, "s": 30899, "text": "Arrays" }, { "code": null, "e": 30914, "s": 30906, "text": "Sorting" }, { "code": null, "e": 30919, "s": 30914, "text": "Zoho" }, { "code": null, "e": 30926, "s": 30919, "text": "Arrays" }, { "code": null, "e": 30934, "s": 30926, "text": "Sorting" }, { "code": null, "e": 31032, "s": 30934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31041, "s": 31032, "text": "Comments" }, { "code": null, "e": 31054, "s": 31041, "text": "Old Comments" }, { "code": null, "e": 31098, "s": 31054, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31121, "s": 31098, "text": "Introduction to Arrays" }, { "code": null, "e": 31153, "s": 31121, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31167, "s": 31153, "text": "Linear Search" } ]
UnitTest Framework - Quick Guide
Unit testing is a software testing method by which individual units of source code, such as functions, methods, and class are tested to determine whether they are fit for use. Intuitively, one can view a unit as the smallest testable part of an application. Unit tests are short code fragments created by programmers during the development process. It forms the basis for component testing. Unit testing can be done in the following two ways − Executing the test cases manually without any tool support is known as manual testing. Since test cases are executed by human resources so it is very time consuming and tedious. Since test cases are executed by human resources so it is very time consuming and tedious. As test cases need to be executed manually so more testers are required in manual testing. As test cases need to be executed manually so more testers are required in manual testing. It is less reliable as tests may not be performed with precision each time because of human errors. It is less reliable as tests may not be performed with precision each time because of human errors. No programming can be done to write sophisticated tests which fetch hidden information. No programming can be done to write sophisticated tests which fetch hidden information. Taking tool support and executing the test cases by using automation tool is known as automation testing. Fast Automation runs test cases significantly faster than human resources. Fast Automation runs test cases significantly faster than human resources. The investment over human resources is less as test cases are executed by using automation tool. The investment over human resources is less as test cases are executed by using automation tool. Automation tests perform precisely same operation each time they are run and are more reliable. Automation tests perform precisely same operation each time they are run and are more reliable. Testers can program sophisticated tests to bring out hidden information. Testers can program sophisticated tests to bring out hidden information. JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks collectively known as xUnit that originated with JUnit. You can find out JUnit Tutorial here. The Python unit testing framework, sometimes referred to as “PyUnit,” is a Python language version of JUnit developed by Kent Beck and Erich Gamma. PyUnit forms part of the Python Standard Library as of Python version 2.1. Python unit testing framework supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. The unittest module provides classes that make it easy to support these qualities for a set of tests. This tutorial has been prepared for the beginners to help them understand the basic functionality of Python testing framework. After completing this tutorial you will find yourself at a moderate level of expertise in using Python testing framework from where you can take yourself to the next levels. You should have reasonable expertise in software development using Python language. Our Python tutorial is a good place to start learning Python. Knowledge of basics of software testing is also desirable. The classes needed to write tests are to be found in the 'unittest' module. If you are using older versions of Python (prior to Python 2.1), the module can be downloaded from http://pyunit.sourceforge.net/. However, unittest module is now a part of the standard Python distribution; hence it requires no separate installation. 'unittest' supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. The unittest module provides classes that make it easy to support these qualities for a set of tests. To achieve this, unittest supports the following important concepts − test fixture − This represents the preparation needed to perform one or more tests, and any associate cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process. test fixture − This represents the preparation needed to perform one or more tests, and any associate cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process. test case − This is the smallest unit of testing. This checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases. test case − This is the smallest unit of testing. This checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases. test suite − This is a collection of test cases, test suites, or both. This is used to aggregate tests that should be executed together. Test suites are implemented by the TestSuite class. test suite − This is a collection of test cases, test suites, or both. This is used to aggregate tests that should be executed together. Test suites are implemented by the TestSuite class. test runner − This is a component which orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests. test runner − This is a component which orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests. The following steps are involved in writing a simple unit test − Step 1 − Import the unittest module in your program. Step 2 − Define a function to be tested. In the following example, add() function is to be subjected to test. Step 3 − Create a testcase by subclassing unittest.TestCase. Step 4 − Define a test as a method inside the class. Name of method must start with 'test'. Step 5 − Each test calls assert function of TestCase class. There are many types of asserts. Following example calls assertEquals() function. Step 6 − assertEquals() function compares result of add() function with arg2 argument and throws assertionError if comparison fails. Step 7 − Finally, call main() method from the unittest module. import unittest def add(x,y): return x + y class SimpleTest(unittest.TestCase): def testadd1(self): self.assertEquals(add(4,5),9) if __name__ == '__main__': unittest.main() Step 8 − Run the above script from the command line. C:\Python27>python SimpleTest.py . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK Step 9 − The following three could be the possible outcomes of a test − OK The test passes. ‘A’ is displayed on console. FAIL The test does not pass, and raises an AssertionError exception. ‘F’ is displayed on console. ERROR The test raises an exception other than AssertionError. ‘E’ is displayed on console. These outcomes are displayed on the console by '.', 'F' and 'E' respectively. The unittest module can be used from the command line to run single or multiple tests. python -m unittest test1 python -m unittest test_module.TestClass python -m unittest test_module.TestClass.test_method unittest supports the following command line options. For a list of all the command-line options, use the following command − Python –m unittest -h -h, --help Show this message v, --verbose Verbose output -q, --quiet Minimal output -f, --failfast Stop on first failure -c, --catch Catch control-C and display results -b, --buffer Buffer stdout and stderr during test runs This chapter discusses the classes and methods defined in the unittest module. There are five major classes in this module. Object of this class represents the smallest testable unit. It holds the test routines and provides hooks for preparing each routine and for cleaning up thereafter. The following methods are defined in the TestCase class − setUp() Method called to prepare the test fixture. This is called immediately before calling the test method tearDown() Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, setUpClass() A class method called before tests in an individual class run. tearDownClass() A class method called after tests in an individual class have run. run(result = None) Run the test, collecting the result into the test result object passed as result. skipTest(reason) Calling this during a test method or setUp() skips the current test. debug() Run the test without collecting the result. shortDescription() Returns a one-line description of the test. There can be numerous tests written inside a TestCase class. These test methods may need database connection, temporary files or other resources to be initialized. These are called fixtures. TestCase includes a special hook to configure and clean up any fixtures needed by your tests. To configure the fixtures, override setUp(). To clean up, override tearDown(). In the following example, two tests are written inside the TestCase class. They test result of addition and subtraction of two values. The setup() method initializes the arguments based on shortDescription() of each test. teardown() method will be executed at the end of each test. import unittest class simpleTest2(unittest.TestCase): def setUp(self): self.a = 10 self.b = 20 name = self.shortDescription() if name == "Add": self.a = 10 self.b = 20 print name, self.a, self.b if name == "sub": self.a = 50 self.b = 60 print name, self.a, self.b def tearDown(self): print '\nend of test',self.shortDescription() def testadd(self): """Add""" result = self.a+self.b self.assertTrue(result == 100) def testsub(self): """sub""" result = self.a-self.b self.assertTrue(result == -10) if __name__ == '__main__': unittest.main() Run the above code from the command line. It gives the following output − C:\Python27>python test2.py Add 10 20 F end of test Add sub 50 60 end of test sub . ================================================================ FAIL: testadd (__main__.simpleTest2) Add ---------------------------------------------------------------------- Traceback (most recent call last): File "test2.py", line 21, in testadd self.assertTrue(result == 100) AssertionError: False is not true ---------------------------------------------------------------------- Ran 2 tests in 0.015s FAILED (failures = 1) TestCase class has a setUpClass() method which can be overridden to execute before the execution of individual tests inside a TestCase class. Similarly, tearDownClass() method will be executed after all test in the class. Both the methods are class methods. Hence, they must be decorated with @classmethod directive. The following example demonstrates the use of these class methods − import unittest class TestFixtures(unittest.TestCase): @classmethod def setUpClass(cls): print 'called once before any tests in class' @classmethod def tearDownClass(cls): print '\ncalled once after all tests in class' def setUp(self): self.a = 10 self.b = 20 name = self.shortDescription() print '\n',name def tearDown(self): print '\nend of test',self.shortDescription() def test1(self): """One""" result = self.a+self.b self.assertTrue(True) def test2(self): """Two""" result = self.a-self.b self.assertTrue(False) if __name__ == '__main__': unittest.main() Python's testing framework provides a useful mechanism by which test case instances can be grouped together according to the features they test. This mechanism is made available by TestSuite class in unittest module. The following steps are involved in creating and running a test suite. Step 1 − Create an instance of TestSuite class. suite = unittest.TestSuite() Step 2 − Add tests inside a TestCase class in the suite. suite.addTest(testcase class) Step 3 − You can also use makeSuite() method to add tests from a class suite = unittest.makeSuite(test case class) Step 4 − Individual tests can also be added in the suite. suite.addTest(testcaseclass(""testmethod") Step 5 − Create an object of the TestTestRunner class. runner = unittest.TextTestRunner() Step 6 − Call the run() method to run all the tests in the suite runner.run (suite) The following methods are defined in TestSuite class − addTest() Adds a test method in the test suite. addTests() Adds tests from multiple TestCase classes. run() Runs the tests associated with this suite, collecting the result into the test result object debug() Runs the tests associated with this suite without collecting the result. countTestCases() Returns the number of tests represented by this test object The following example shows how to use TestSuite class − import unittest class suiteTest(unittest.TestCase): def setUp(self): self.a = 10 self.b = 20 def testadd(self): """Add""" result = self.a+self.b self.assertTrue(result == 100) def testsub(self): """sub""" result = self.a-self.b self.assertTrue(result == -10) def suite(): suite = unittest.TestSuite() ## suite.addTest (simpleTest3("testadd")) ## suite.addTest (simpleTest3("testsub")) suite.addTest(unittest.makeSuite(simpleTest3)) return suite if __name__ == '__main__': runner = unittest.TextTestRunner() test_suite = suite() runner.run (test_suite) You can experiment with the addTest() method by uncommenting the lines and comment statement having makeSuite() method. The unittest package has the TestLoader class which is used to create test suites from classes and modules. By default, the unittest.defaultTestLoader instance is automatically created when the unittest.main(0 method is called. An explicit instance, however enables the customization of certain properties. In the following code, tests from two classes are collected in a List by using the TestLoader object. import unittest testList = [Test1, Test2] testLoad = unittest.TestLoader() TestList = [] for testCase in testList: testSuite = testLoad.loadTestsFromTestCase(testCase) TestList.append(testSuite) newSuite = unittest.TestSuite(TestList) runner = unittest.TextTestRunner() runner.run(newSuite) The following table shows a list of methods in the TestLoader class − loadTestsFromTestCase() Return a suite of all tests cases contained in a TestCase class loadTestsFromModule() Return a suite of all tests cases contained in the given module. loadTestsFromName() Return a suite of all tests cases given a string specifier. discover() Find all the test modules by recursing into subdirectories from the specified start directory, and return a TestSuite object This class is used to compile information about the tests that have been successful and the tests that have met failure. A TestResult object stores the results of a set of tests. A TestResult instance is returned by the TestRunner.run() method. TestResult instances have the following attributes − Errors A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test which raised an unexpected exception. Failures A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test where a failure was explicitly signalled using the TestCase.assert*() methods. Skipped A list containing 2-tuples of TestCase instances and strings holding the reason for skipping the test. wasSuccessful() Return True if all tests run so far have passed, otherwise returns False. stop() This method can be called to signal that the set of tests being run should be aborted. startTestRun() Called once before any tests are executed. stopTestRun() Called once after all tests are executed. testsRun The total number of tests run so far. Buffer If set to true, sys.stdout and sys.stderr will be buffered in between startTest() and stopTest() being called. The following code executes a test suite − if __name__ == '__main__': runner = unittest.TextTestRunner() test_suite = suite() result = runner.run (test_suite) print "---- START OF TEST RESULTS" print result print "result::errors" print result.errors print "result::failures" print result.failures print "result::skipped" print result.skipped print "result::successful" print result.wasSuccessful() print "result::test-run" print result.testsRun print "---- END OF TEST RESULTS" The code when executed displays the following output − ---- START OF TEST RESULTS <unittest.runner.TextTestResult run = 2 errors = 0 failures = 1> result::errors [] result::failures [(<__main__.suiteTest testMethod = testadd>, 'Traceback (most recent call last):\n File "test3.py", line 10, in testadd\n self.assertTrue(result == 100)\nAssert ionError: False is not true\n')] result::skipped [] result::successful False result::test-run 2 ---- END OF TEST RESULTS Python testing framework uses Python's built-in assert() function which tests a particular condition. If the assertion fails, an AssertionError will be raised. The testing framework will then identify the test as Failure. Other exceptions are treated as Error. The following three sets of assertion functions are defined in unittest module − Basic Boolean Asserts Comparative Asserts Asserts for Collections Basic assert functions evaluate whether the result of an operation is True or False. All the assert methods accept a msg argument that, if specified, is used as the error message on failure. assertEqual(arg1, arg2, msg = None) Test that arg1 and arg2 are equal. If the values do not compare equal, the test will fail. assertNotEqual(arg1, arg2, msg = None) Test that arg1 and arg2 are not equal. If the values do compare equal, the test will fail. assertTrue(expr, msg = None) Test that expr is true. If false, test fails assertFalse(expr, msg = None) Test that expr is false. If true, test fails assertIs(arg1, arg2, msg = None) Test that arg1 and arg2 evaluate to the same object. assertIsNot(arg1, arg2, msg = None) Test that arg1 and arg2 don’t evaluate to the same object. assertIsNone(expr, msg = None) Test that expr is None. If not None, test fails assertIsNotNone(expr, msg = None) Test that expr is not None. If None, test fails assertIn(arg1, arg2, msg = None) Test that arg1 is in arg2. assertNotIn(arg1, arg2, msg = None) Test that arg1 is not in arg2. assertIsInstance(obj, cls, msg = None) Test that obj is an instance of cls assertNotIsInstance(obj, cls, msg = None) Test that obj is not an instance of cls Some of the above assertion functions are implemented in the following code − import unittest class SimpleTest(unittest.TestCase): def test1(self): self.assertEqual(4 + 5,9) def test2(self): self.assertNotEqual(5 * 2,10) def test3(self): self.assertTrue(4 + 5 == 9,"The result is False") def test4(self): self.assertTrue(4 + 5 == 10,"assertion fails") def test5(self): self.assertIn(3,[1,2,3]) def test6(self): self.assertNotIn(3, range(5)) if __name__ == '__main__': unittest.main() When the above script is run, test2, test4 and test6 will show failure and others run successfully. FAIL: test2 (__main__.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Python27\SimpleTest.py", line 9, in test2 self.assertNotEqual(5*2,10) AssertionError: 10 == 10 FAIL: test4 (__main__.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Python27\SimpleTest.py", line 13, in test4 self.assertTrue(4+5==10,"assertion fails") AssertionError: assertion fails FAIL: test6 (__main__.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Python27\SimpleTest.py", line 17, in test6 self.assertNotIn(3, range(5)) AssertionError: 3 unexpectedly found in [0, 1, 2, 3, 4] ---------------------------------------------------------------------- Ran 6 tests in 0.001s FAILED (failures = 3) The second set of assertion functions are comparative asserts − assertAlmostEqual (first, second, places = 7, msg = None, delta = None) Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7), assertAlmostEqual (first, second, places = 7, msg = None, delta = None) Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7), assertNotAlmostEqual (first, second, places, msg, delta) Test that first and second are not approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero. In both the above functions, if delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta. Supplying both delta and places raises a TypeError. assertNotAlmostEqual (first, second, places, msg, delta) Test that first and second are not approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero. In both the above functions, if delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta. Supplying both delta and places raises a TypeError. assertGreater (first, second, msg = None) Test that first is greater than second depending on the method name. If not, the test will fail. assertGreater (first, second, msg = None) Test that first is greater than second depending on the method name. If not, the test will fail. assertGreaterEqual (first, second, msg = None) Test that first is greater than or equal to second depending on the method name. If not, the test will fail assertGreaterEqual (first, second, msg = None) Test that first is greater than or equal to second depending on the method name. If not, the test will fail assertLess (first, second, msg = None) Test that first is less than second depending on the method name. If not, the test will fail assertLess (first, second, msg = None) Test that first is less than second depending on the method name. If not, the test will fail assertLessEqual (first, second, msg = None) Test that first is less than or equal to second depending upon the method name. If not, the test will fail. assertLessEqual (first, second, msg = None) Test that first is less than or equal to second depending upon the method name. If not, the test will fail. assertRegexpMatches (text, regexp, msg = None) Test that a regexp search matches the text. In case of failure, the error message will include the pattern and the text. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search(). assertRegexpMatches (text, regexp, msg = None) Test that a regexp search matches the text. In case of failure, the error message will include the pattern and the text. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search(). assertNotRegexpMatches (text, regexp, msg = None) Verifies that a regexp search does not match text. Fails with an error message including the pattern and the part of text that matches. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search(). assertNotRegexpMatches (text, regexp, msg = None) Verifies that a regexp search does not match text. Fails with an error message including the pattern and the part of text that matches. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search(). The assertion functions are implemented in the following example − import unittest import math import re class SimpleTest(unittest.TestCase): def test1(self): self.assertAlmostEqual(22.0/7,3.14) def test2(self): self.assertNotAlmostEqual(10.0/3,3) def test3(self): self.assertGreater(math.pi,3) def test4(self): self.assertNotRegexpMatches("Tutorials Point (I) Private Limited","Point") if __name__ == '__main__': unittest.main() The above script reports test1 and test4 as Failure. In test1, the division of 22/7 is not within 7 decimal places of 3.14. Similarly, since the second argument matches with the text in first argument, test4 results in AssertionError. =====================================================FAIL: test1 (__main__.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "asserttest.py", line 7, in test1 self.assertAlmostEqual(22.0/7,3.14) AssertionError: 3.142857142857143 != 3.14 within 7 places ================================================================ FAIL: test4 (__main__.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "asserttest.py", line 13, in test4 self.assertNotRegexpMatches("Tutorials Point (I) Private Limited","Point") AssertionError: Regexp matched: 'Point' matches 'Point' in 'Tutorials Point (I) Private Limited' ---------------------------------------------------------------------- Ran 4 tests in 0.001s FAILED (failures = 2) This set of assert functions are meant to be used with collection data types in Python, such as List, Tuple, Dictionary and Set. assertListEqual (list1, list2, msg = None) Tests that two lists are equal. If not, an error message is constructed that shows only the differences between the two. assertTupleEqual (tuple1, tuple2, msg = None) Tests that two tuples are equal. If not, an error message is constructed that shows only the differences between the two. assertSetEqual (set1, set2, msg = None) Tests that two sets are equal. If not, an error message is constructed that lists the differences between the sets. assertDictEqual (expected, actual, msg = None) Test that two dictionaries are equal. If not, an error message is constructed that shows the differences in the dictionaries. The following example implements the above methods − import unittest class SimpleTest(unittest.TestCase): def test1(self): self.assertListEqual([2,3,4], [1,2,3,4,5]) def test2(self): self.assertTupleEqual((1*2,2*2,3*2), (2,4,6)) def test3(self): self.assertDictEqual({1:11,2:22},{3:33,2:22,1:11}) if __name__ == '__main__': unittest.main() In the above example, test1 and test3 show AssertionError. Error message displays the differences in List and Dictionary objects. FAIL: test1 (__main__.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "asserttest.py", line 5, in test1 self.assertListEqual([2,3,4], [1,2,3,4,5]) AssertionError: Lists differ: [2, 3, 4] != [1, 2, 3, 4, 5] First differing element 0: 2 1 Second list contains 2 additional elements. First extra element 3: 4 - [2, 3, 4] + [1, 2, 3, 4, 5] ? +++ +++ FAIL: test3 (__main__.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "asserttest.py", line 9, in test3 self.assertDictEqual({1:11,2:22},{3:33,2:22,1:11}) AssertionError: {1: 11, 2: 22} != {1: 11, 2: 22, 3: 33} - {1: 11, 2: 22} + {1: 11, 2: 22, 3: 33} ? +++++++ ---------------------------------------------------------------------- Ran 3 tests in 0.001s FAILED (failures = 2) The TestLoader class has a discover() function. Python testing framework uses this for simple test discovery. In order to be compatible, modules and packages containing tests must be importable from top level directory. The following is the basic command line usage of test discovery − Python –m unittest discover Interpreter tries to load all modules containing test from current directory and inner directories recursively. Other command line options are − -v, --verbose Verbose output -s, --start-directory directory Directory to start discovery (. default) -p, --pattern pattern Pattern to match test files (test*.py default) -t, --top-level-directory directory Top level directory of project (defaults to start directory) For example, in order to discover the tests in modules whose names start with 'assert' in 'tests' directory, the following command line is used − C:\python27>python –m unittest –v –s "c:\test" –p "assert*.py" Test discovery loads tests by importing them. Once test discovery has found all the test files from the start directory you specify, it turns the paths into package names to import. If you supply the start directory as a package name rather than a path to a directory then discover assumes that whichever location it imports from is the location you intended, so you will not get the warning. Support for skipping tests has been added since Python 2.7. It is possible to skip individual test method or TestCase class, conditionally as well as unconditionally. The framework allows a certain test to be marked as an 'expected failure'. This test will 'fail' but will not be counted as failed in TestResult. To skip a method unconditionally, the following unittest.skip() class method can be used − import unittest def add(x,y): return x+y class SimpleTest(unittest.TestCase): @unittest.skip("demonstrating skipping") def testadd1(self): self.assertEquals(add(4,5),9) if __name__ == '__main__': unittest.main() Since skip() is a class method, it is prefixed by @ token. The method takes one argument: a log message describing the reason for the skip. When the above script is executed, the following result is displayed on console − C:\Python27>python skiptest.py s ---------------------------------------------------------------------- Ran 1 test in 0.000s OK (skipped = 1) The character 's' indicates that a test has been skipped. Alternate syntax for skipping test is using instance method skipTest() inside the test function. def testadd2(self): self.skipTest("another method for skipping") self.assertTrue(add(4 + 5) == 10) The following decorators implement test skipping and expected failures − unittest.skip(reason) Unconditionally skip the decorated test. reason should describe why the test is being skipped. unittest.skipIf(condition, reason) Skip the decorated test if condition is true. unittest.skipUnless(condition, reason) Skip the decorated test unless condition is true. unittest.expectedFailure() Mark the test as an expected failure. If the test fails when run, the test is not counted as a failure. The following example demonstrates the use of conditional skipping and expected failure. import unittest class suiteTest(unittest.TestCase): a = 50 b = 40 def testadd(self): """Add""" result = self.a+self.b self.assertEqual(result,100) @unittest.skipIf(a>b, "Skip over this routine") def testsub(self): """sub""" result = self.a-self.b self.assertTrue(result == -10) @unittest.skipUnless(b == 0, "Skip over this routine") def testdiv(self): """div""" result = self.a/self.b self.assertTrue(result == 1) @unittest.expectedFailure def testmul(self): """mul""" result = self.a*self.b self.assertEqual(result == 0) if __name__ == '__main__': unittest.main() In the above example, testsub() and testdiv() will be skipped. In the first case a>b is true, while in the second case b == 0 is not true. On the other hand, testmul() has been marked as expected failure. When the above script is run, two skipped tests show 's' and the expected failure is shown as 'x'. C:\Python27>python skiptest.py Fsxs ================================================================ FAIL: testadd (__main__.suiteTest) Add ---------------------------------------------------------------------- Traceback (most recent call last): File "skiptest.py", line 9, in testadd self.assertEqual(result,100) AssertionError: 90 != 100 ---------------------------------------------------------------------- Ran 4 tests in 0.000s FAILED (failures = 1, skipped = 2, expected failures = 1) Python testing framework provides the following assertion methods to check that exceptions are raised. Test that an exception (first argument) is raised when a function is called with any positional or keyword arguments. The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception. In the example below, a test function is defined to check whether ZeroDivisionError is raised. import unittest def div(a,b): return a/b class raiseTest(unittest.TestCase): def testraise(self): self.assertRaises(ZeroDivisionError, div, 1,0) if __name__ == '__main__': unittest.main() The testraise() function uses assertRaises() function to see if division by zero occurs when div() function is called. The above code will raise an exception. But changes arguments to div() function as follows − self.assertRaises(ZeroDivisionError, div, 1,1) When a code is run with these changes, the test fails as ZeroDivisionError doesn't occur. F ================================================================ FAIL: testraise (__main__.raiseTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "raisetest.py", line 7, in testraise self.assertRaises(ZeroDivisionError, div, 1,1) AssertionError: ZeroDivisionError not raised ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (failures = 1) Tests that regexp matches on the string representation of the raised exception. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search(). The following example shows how assertRaisesRegexp() is used − import unittest import re class raiseTest(unittest.TestCase): def testraiseRegex(self): self.assertRaisesRegexp(TypeError, "invalid", reg,"Point","TutorialsPoint") if __name__ == '__main__': unittest.main() Here, testraseRegex() test doesn't fail as first argument. "Point" is found in the second argument string. ================================================================ FAIL: testraiseRegex (__main__.raiseTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:/Python27/raiseTest.py", line 11, in testraiseRegex self.assertRaisesRegexp(TypeError, "invalid", reg,"Point","TutorialsPoint") AssertionError: TypeError not raised ---------------------------------------------------------------------- However, the change is as shown below − self.assertRaisesRegexp(TypeError, "invalid", reg,123,"TutorialsPoint") TypeError exception will be thrown. Hence, the following result will be displayed − ================================================================ FAIL: testraiseRegex (__main__.raiseTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "raisetest.py", line 11, in testraiseRegex self.assertRaisesRegexp(TypeError, "invalid", reg,123,"TutorialsPoint") AssertionError: "invalid" does not match "first argument must be string or compiled pattern" ---------------------------------------------------------------------- Junit, the Java unit testing framework (Pyunit is implementation of JUnit) has a handy option of timeout. If a test takes more than specified time, it will be marked as failed. Python's testing framework doesn't contain any support for time out. However, a third part module called timeout-decorator can do the job. Download and install the module from − https://pypi.python.org/packages/source/t/timeout-decorator/timeout-decorator-0.3.2.tar.gz Import timeout_decorator in the code Put timeout decorator before the test @timeout_decorator.timeout(10) If a test method below this line takes more than the timeout mentioned (10 mins) here, a TimeOutError will be raised. For example − import time import timeout_decorator class timeoutTest(unittest.TestCase): @timeout_decorator.timeout(5) def testtimeout(self): print "Start" for i in range(1,10): time.sleep(1) print "%d seconds have passed" % i if __name__ == '__main__': unittest.main() unittest2 is a backport of additional features added to the Python testing framework in Python 2.7 and onwards. It is tested to run on Python 2.6, 2.7, and 3.*. Latest version can be downloaded from https://pypi.python.org/pypi/unittest2 To use unittest2 instead of unittest, simply replace import unittest with import unittest2. Classes in unittest2 derive from the appropriate classes in unittest, so it should be possible to use the unittest2 test running infrastructure without having to switch all your tests to using unittest2 immediately. In case you intend to implement new features, subclass your testcase from unittest2.TestCase instead of unittest.TestCase The following are the new features of unittest2 − addCleanups for better resource management addCleanups for better resource management Contains many new assert methods Contains many new assert methods assertRaises as context manager, with access to the exception afterwards assertRaises as context manager, with access to the exception afterwards Has module level fixtures such as setUpModule and tearDownModule Has module level fixtures such as setUpModule and tearDownModule Includes load_tests protocol for loading tests from modules or packages Includes load_tests protocol for loading tests from modules or packages startTestRun and stopTestRun methods on TestResult startTestRun and stopTestRun methods on TestResult In Python 2.7, you invoke the unittest command line features (including test discover) with python -m unittest <args>. Instead, unittest2 comes with a script unit2. unit2 discover unit2 -v test_module More efficient handling of control-C during a test run is provided by The -c/--catch command-line option to unittest, along with the catchbreak parameter. With catch break behavior enabled, control-C will allow the currently running test to complete, and the test run will then end and report all the results so far. A second control-c will raise a KeyboardInterrupt in the usual way. If the unittest handler is called but signal.SIGINT handler isn’t installed, then it calls for the default handler. This will normally be the expected behavior by code that replaces an installed handler and delegates to it. For individual tests that need unittest control-c handling disabled, the removeHandler() decorator can be used. The following utility functions enable control-c handling functionality within test frameworks − Install the control-c handler. When a signal.SIGINT is received all registered results have TestResult.stop() called. Register a TestResult object for control-c handling. Registering a result stores a weak reference to it, so it doesn’t prevent the result from being garbage collected. Remove a registered result. Once a result has been removed then TestResult.stop() will no longer be called on that result object in response to a control-c. When called without arguments, this function removes the control-c handler if it has been installed. This function can also be used as a test decorator to temporarily remove the handler whilst the test is being executed. The unittest module is installed to discover and run tests interactively. This utility, a Python script 'inittestgui.py' uses Tkinter module which is a Python port for TK graphics tool kit. It gives an easy to use GUI for discovery and running tests. Python unittestgui.py Click the 'Discover Tests' button. A small dialog box appears where you can select directory and modules from which test are to be run. Finally, click the start button. Tests will be discovered from the selected path and module names, and the result pane will display the results. In order to see the details of individual test, select and click on test in the result box − If you do not find this utility in the Python installation, you can obtain it from the project page http://pyunit.sourceforge.net/. Similar, utility based on wxpython toolkit is also available there. Python' standard distribution contains 'Doctest' module. This module's functionality makes it possible to search for pieces of text that look like interactive Python sessions, and executes these sessions to see if they work exactly as shown. Doctest can be very useful in the following scenarios − To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented. To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented. To perform regression testing by verifying that interactive examples from a test file or a test object work as expected. To perform regression testing by verifying that interactive examples from a test file or a test object work as expected. To write tutorial documentation for a package, liberally illustrated with input-output examples To write tutorial documentation for a package, liberally illustrated with input-output examples In Python, a 'docstring' is a string literal which appears as the first expression in a class, function or module. It is ignored when the suite is executed, but it is recognized by the compiler and put into the __doc__ attribute of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object. It is a usual practice to put example usage of different parts of Python code inside the docstring. The doctest module allows to verify that these docstrings are up-to-date with the intermittent revisions in code. In the following code, a factorial function is defined interspersed with example usage. In order to verify if the example usage is correct, call the testmod() function in doctest module. """ This is the "example" module. The example module supplies one function, factorial(). For example, >>> factorial(5) 120 """ def factorial(x): """Return the factorial of n, an exact integer >= 0. >>> factorial(-1) Traceback (most recent call last): ... ValueError: x must be >= 0 """ if not x >= 0: raise ValueError("x must be >= 0") f = 1 for i in range(1,x+1): f = f*i return f if __name__ == "__main__": import doctest doctest.testmod() Enter and save the above script as FactDocTest.py and try to execute this script from the command line. Python FactDocTest.py No output will be shown unless the example fails. Now, change the command line to the following − Python FactDocTest.py –v The console will now show the following output − C:\Python27>python FactDocTest.py -v Trying: factorial(5) Expecting: 120 ok Trying: factorial(-1) Expecting: Traceback (most recent call last): ... ValueError: x must be >= 0 ok 2 items passed all tests: 1 tests in __main__ 1 tests in __main__.factorial 2 tests in 2 items. 2 passed and 0 failed. Test passed. If, on the other hand, the code of factorial() function doesn't give expected result in docstring, failure result will be displayed. For instance, change f = 2 in place of f = 1 in the above script and run the doctest again. The result will be as follows − Trying: factorial(5) Expecting: 120 ********************************************************************** File "docfacttest.py", line 6, in __main__ Failed example: factorial(5) Expected: 120 Got: 240 Trying: factorial(-1) Expecting: Traceback (most recent call last): ... ValueError: x must be >= 0 ok 1 items passed all tests: 1 tests in __main__.factorial ********************************************************************** 1 items had failures: 1 of 1 in __main__ 2 tests in 2 items. 1 passed and 1 failed. ***Test Failed*** 1 failures. Another simple application of doctest is testing interactive examples in a text file. This can be done with the testfile() function. The following text is stored in a text file named 'example.txt'. Using ''factorial'' ------------------- This is an example text file in reStructuredText format. First import ''factorial'' from the ''example'' module: >>> from example import factorial Now use it: >>> factorial(5) 120 The file content is treated as docstring. In order to verify the examples in the text file, use the testfile() function of doctest module. def factorial(x): if not x >= 0: raise ValueError("x must be >= 0") f = 1 for i in range(1,x+1): f = f*i return f if __name__ == "__main__": import doctest doctest.testfile("example.txt") As with the testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to console, using the same format as testmod(). As with the testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to console, using the same format as testmod(). In most cases a copy-and-paste of an interactive console session works fine, but doctest isn’t trying to do an exact emulation of any specific Python shell. In most cases a copy-and-paste of an interactive console session works fine, but doctest isn’t trying to do an exact emulation of any specific Python shell. Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line. Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line. Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put <BLANKLINE> in your doctest example each place a blank line is expected. Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put <BLANKLINE> in your doctest example each place a blank line is expected. The doctest API revolves around the following two container classes used to store interactive examples from docstrings − Example − A single Python statement, paired with its expected output. Example − A single Python statement, paired with its expected output. DocTest − A collection of Examples, typically extracted from a single docstring or a text file. DocTest − A collection of Examples, typically extracted from a single docstring or a text file. The following additional processing classes are defined to find, parse, and run, and check doctest examples − DocTestFinder − Finds all docstrings in a given module, and uses a DocTestParser to create a DocTest from every docstring that contains interactive examples. DocTestFinder − Finds all docstrings in a given module, and uses a DocTestParser to create a DocTest from every docstring that contains interactive examples. DocTestParser − Creates a doctest object from a string (such as an object’s docstring). DocTestParser − Creates a doctest object from a string (such as an object’s docstring). DocTestRunner − Executes the examples in a doctest, and uses an OutputChecker to verify their output. DocTestRunner − Executes the examples in a doctest, and uses an OutputChecker to verify their output. OutputChecker − Compares the actual output from a doctest example with the expected output, and decides whether they match. OutputChecker − Compares the actual output from a doctest example with the expected output, and decides whether they match. It is a processing class used to extract the doctests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types — modules, functions, classes, methods, staticmethods, classmethods, and properties. This class defines the find() method. It returns a list of the DocTests that are defined by the object‘s docstring, or by any of its contained objects’ docstrings. It is a processing class used to extract interactive examples from a string, and use them to create a DocTest object. This class defines the following methods − get_doctest() − Extract all doctest examples from the given string, and collect them into a DocTest object. get_doctest() − Extract all doctest examples from the given string, and collect them into a DocTest object. get_examples(string[, name]) − Extract all doctest examples from the given string, and return them as a list of Example objects. Line numbers are 0-based. The optional argument name is a name identifying this string, and is only used for error messages. get_examples(string[, name]) − Extract all doctest examples from the given string, and return them as a list of Example objects. Line numbers are 0-based. The optional argument name is a name identifying this string, and is only used for error messages. parse(string[, name]) − Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument name is a name identifying this string, and is only used for error messages. parse(string[, name]) − Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument name is a name identifying this string, and is only used for error messages. This is a processing class used to execute and verify the interactive examples in a DocTest. The following methods are defined in it − Report that the test runner is about to process the given example. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly Report that the given example ran successfully. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly. Report that the given example failed. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly. Report that the given example raised an unexpected exception. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly. Run the examples in test (a DocTest object), and display the results using the writer function out. Print a summary of all the test cases that have been run by this DocTestRunner, and return a named tuple TestResults(failed, attempted). The optional verbose argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner‘s verbosity is used. This class is used to check whether the actual output from a doctest example matches the expected output. The following methods are defined in this class − Return True if the actual output from an example (got) matches with the expected output (want). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See section Option Flags and Directives for more information about option flags. Return a string describing the differences between the expected output for a given example (example) and the actual output (got). The doctest module provides two functions that can be used to create unittest test suites from modules and text files containing doctests. To integrate with unittest test discovery, include a load_tests() function in your test module − import unittest import doctest import doctestexample def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(doctestexample)) return tests A combined TestSuite of tests from unittest as well as doctest will be formed and it can now be executed by unittest module's main() method or run() method. The following are the two main functions for creating unittest.TestSuite instances from text files and modules with the doctests − It is used to convert doctest tests from one or more text files to a unittest.TestSuite. The returned unittest.TestSuite is to be run by the unittest framework and runs the interactive examples in each file. If any of the examples in a file fails, then the synthesized unit test fails, and a failureException exception is raised showing the name of the file containing the test and a (sometimes approximate) line number. It is used to convert doctest tests for a module to a unittest.TestSuite. The returned unittest.TestSuite is to be run by the unittest framework and runs each doctest in the module. If any of the doctests fail, then the synthesized unit test fails, and a failureException exception is raised showing the name of the file containing the test and a (sometimes approximate) line number Under the covers, DocTestSuite() creates a unittest.TestSuite out of doctest.DocTestCase instances, and DocTestCase is a subclass of unittest.TestCase. Similarly, DocFileSuite() creates a unittest.TestSuite out of doctest.DocFileCase instances, and DocFileCase is a subclass of DocTestCase. So both ways of creating a unittest.TestSuite run instances of DocTestCase. When you run doctest functions yourself, you can control the doctest options in use directly, by passing option flags to doctest functions. However, if you’re writing a unittest framework, unittest ultimately controls when and how the tests get run. The framework author typically wants to control doctest reporting options (perhaps, e.g., specified by command line options), but there’s no way to pass options through unittest to doctest test runners. It was in 2004 that Holger Krekel renamed his std package, whose name was often confused with that of the Standard Library that ships with Python, to the (only slightly less confusing) name 'py.' Though the package contains several sub-packages, it is now known almost entirely for its py.test framework. The py.test framework has set up a new standard for Python testing, and has become very popular with many developers today. The elegant and Pythonic idioms it introduced for test writing have made it possible for test suites to be written in a far more compact style. py.test is a no-boilerplate alternative to Python’s standard unittest module. Despite being a fully-featured and extensible test tool, it boasts of a simple syntax. Creating a test suite is as easy as writing a module with a couple of functions. py.test runs on all POSIX operating systems and WINDOWS (XP/7/8) with Python versions 2.6 and above. Use the following code to load the pytest module in the current Python distribution as well as a py.test.exe utility. Tests can be run using both. pip install pytest You can simply use the assert statement for asserting test expectations. pytest’s assert introspection will intelligently report intermediate values of the assert expression freeing you from the need to learn the many names of JUnit legacy methods. # content of test_sample.py def func(x): return x + 1 def test_answer(): assert func(3) == 5 Use the following command line to run the above test. Once the test is run, the following result is displayed on console − C:\Python27>scripts\py.test -v test_sample.py ============================= test session starts ===================== platform win32 -- Python 2.7.9, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- C:\Pyth on27\python.exe cachedir: .cache rootdir: C:\Python27, inifile: collected 1 items test_sample.py::test_answer FAILED ================================== FAILURES ===================== _________________________________ test_answer _________________________________ def test_answer(): > assert func(3) == 5 E assert 4 == 5 E + where 4 = func(3) test_sample.py:7: AssertionError ========================== 1 failed in 0.05 seconds ==================== The test can also be run from the command line by including pytest module using –m switch. python -m pytest test_sample.py Once you start to have more than a few tests it often makes sense to group tests logically, in classes and modules. Let’s write a class containing two tests − class TestClass: def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check') The following test result will be displayed − C:\Python27>scripts\py.test -v test_class.py ============================= test session starts ===================== platform win32 -- Python 2.7.9, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- C:\Pyt on27\python.exe cachedir: .cache rootdir: C:\Python27, inifile: collected 2 items test_class.py::TestClass::test_one PASSED test_class.py::TestClass::test_two FAILED ================================== FAILURES ===================== _____________________________ TestClass.test_two ______________________________ self = <test_class.TestClass instance at 0x01309DA0> def test_two(self): x = "hello" > assert hasattr(x, 'check') E assert hasattr('hello', 'check') test_class.py:7: AssertionError ===================== 1 failed, 1 passed in 0.06 seconds ====================== The nose project was released in 2005, the year after py.test received its modern guise. It was written by Jason Pellerin to support the same test idioms that had been pioneered by py.test, but in a package that is easier to install and maintain. The nose module can be installed with the help of pip utility pip install nose This will install the nose module in the current Python distribution as well as a nosetest.exe, which means the test can be run using this utility as well as using –m switch. C:\python>nosetests –v test_sample.py Or C:\python>python –m nose test_sample.py nose collects tests from unittest.TestCase subclasses, of course. We can also write simple test functions, as well as test classes that are not subclasses of unittest.TestCase. nose also supplies a number of helpful functions for writing timed tests, testing for exceptions, and other common use cases. nose collects tests automatically. There’s no need to manually collect test cases into test suites. Running tests is responsive, since nose begins running tests as soon as the first test module is loaded. As with the unittest module, nose supports fixtures at the package, module, class, and test case level, so expensive initialization can be done as infrequently as possible. Let us consider nosetest.py similar to the script used earlier − # content of nosetest.py def func(x): return x + 1 def test_answer(): assert func(3) == 5 In order to run the above test, use the following command line syntax − C:\python>nosetests –v nosetest.py The output displayed on console will be as follows − nosetest.test_answer ... FAIL ================================================================ FAIL: nosetest.test_answer ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Python34\lib\site-packages\nose\case.py", line 198, in runTest self.test(*self.arg) File "C:\Python34\nosetest.py", line 6, in test_answer assert func(3) == 5 AssertionError ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (failures = 1) nose can be integrated with DocTest by using with-doctest option in athe bove command line. \nosetests --with-doctest -v nosetest.py You may use nose in a test script − import nose nose.main() If you do not wish the test script to exit with 0 on success and 1 on failure (like unittest.main), use nose.run() instead − import nose result = nose.run() The result will be true if the test run is successful, or false if it fails or raises an uncaught exception. nose supports fixtures (setup and teardown methods) at the package, module, class, and test level. As with py.test or unittest fixtures, setup always runs before any test (or collection of tests for test packages and modules); teardown runs if setup has completed successfully, regardless of the status of the test run. The nose.tools module provides a number of testing aids that you may find useful, including decorators for restricting test execution time and testing for exceptions, and all of the same assertX methods found in unittest.TestCase. nose.tools.ok_(expr, msg = None) − Shorthand for assert. nose.tools.ok_(expr, msg = None) − Shorthand for assert. nose.tools.eq_(a, b, msg = None) − Shorthand for ‘assert a == b, “%r != %r” % (a, b) nose.tools.eq_(a, b, msg = None) − Shorthand for ‘assert a == b, “%r != %r” % (a, b) nose.tools.make_decorator(func) − Wraps a test decorator so as to properly replicate metadata of the decorated function, including nose’s additional stuff (namely, setup and teardown). nose.tools.make_decorator(func) − Wraps a test decorator so as to properly replicate metadata of the decorated function, including nose’s additional stuff (namely, setup and teardown). nose.tools.raises(*exceptions) − Test must raise one of expected exceptions to pass. nose.tools.raises(*exceptions) − Test must raise one of expected exceptions to pass. nose.tools.timed(limit) − Test must finish within specified time limit to pass nose.tools.timed(limit) − Test must finish within specified time limit to pass nose.tools.istest(func) − Decorator to mark a function or method as a test nose.tools.istest(func) − Decorator to mark a function or method as a test nose.tools.nottest(func) − Decorator to mark a function or method as not a test nose.tools.nottest(func) − Decorator to mark a function or method as not a test Python's testing framework, unittest, doesn't have a simple way of running parametrized test cases. In other words, you can't easily pass arguments into a unittest.TestCase from outside. However, pytest module ports test parametrization in several well-integrated ways − pytest.fixture() allows you to define parametrization at the level of fixture functions. pytest.fixture() allows you to define parametrization at the level of fixture functions. @pytest.mark.parametrize allows to define parametrization at the function or class level. It provides multiple argument/fixture sets for a particular test function or class. @pytest.mark.parametrize allows to define parametrization at the function or class level. It provides multiple argument/fixture sets for a particular test function or class. pytest_generate_tests enables implementing your own custom dynamic parametrization scheme or extensions. pytest_generate_tests enables implementing your own custom dynamic parametrization scheme or extensions. A third party module 'nose-parameterized' allows Parameterized testing with any Python test framework. It can be downloaded from this link − https://github.com/wolever/nose-parameterized Print Add Notes Bookmark this page
[ { "code": null, "e": 2489, "s": 2098, "text": "Unit testing is a software testing method by which individual units of source code, such as functions, methods, and class are tested to determine whether they are fit for use. Intuitively, one can view a unit as the smallest testable part of an application. Unit tests are short code fragments created by programmers during the development process. It forms the basis for component testing." }, { "code": null, "e": 2542, "s": 2489, "text": "Unit testing can be done in the following two ways −" }, { "code": null, "e": 2629, "s": 2542, "text": "Executing the test cases manually without any tool support is known as manual testing." }, { "code": null, "e": 2720, "s": 2629, "text": "Since test cases are executed by human resources so it is very time consuming and tedious." }, { "code": null, "e": 2811, "s": 2720, "text": "Since test cases are executed by human resources so it is very time consuming and tedious." }, { "code": null, "e": 2902, "s": 2811, "text": "As test cases need to be executed manually so more testers are required in manual testing." }, { "code": null, "e": 2993, "s": 2902, "text": "As test cases need to be executed manually so more testers are required in manual testing." }, { "code": null, "e": 3093, "s": 2993, "text": "It is less reliable as tests may not be performed with precision each time because of human errors." }, { "code": null, "e": 3193, "s": 3093, "text": "It is less reliable as tests may not be performed with precision each time because of human errors." }, { "code": null, "e": 3281, "s": 3193, "text": "No programming can be done to write sophisticated tests which fetch hidden information." }, { "code": null, "e": 3369, "s": 3281, "text": "No programming can be done to write sophisticated tests which fetch hidden information." }, { "code": null, "e": 3475, "s": 3369, "text": "Taking tool support and executing the test cases by using automation tool is known as automation testing." }, { "code": null, "e": 3550, "s": 3475, "text": "Fast Automation runs test cases significantly faster than human resources." }, { "code": null, "e": 3625, "s": 3550, "text": "Fast Automation runs test cases significantly faster than human resources." }, { "code": null, "e": 3722, "s": 3625, "text": "The investment over human resources is less as test cases are executed by using automation tool." }, { "code": null, "e": 3819, "s": 3722, "text": "The investment over human resources is less as test cases are executed by using automation tool." }, { "code": null, "e": 3915, "s": 3819, "text": "Automation tests perform precisely same operation each time they are run and are more reliable." }, { "code": null, "e": 4011, "s": 3915, "text": "Automation tests perform precisely same operation each time they are run and are more reliable." }, { "code": null, "e": 4084, "s": 4011, "text": "Testers can program sophisticated tests to bring out hidden information." }, { "code": null, "e": 4157, "s": 4084, "text": "Testers can program sophisticated tests to bring out hidden information." }, { "code": null, "e": 4442, "s": 4157, "text": "JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks collectively known as xUnit that originated with JUnit. You can find out JUnit Tutorial here." }, { "code": null, "e": 4665, "s": 4442, "text": "The Python unit testing framework, sometimes referred to as “PyUnit,” is a Python language version of JUnit developed by Kent Beck and Erich Gamma. PyUnit forms part of the Python Standard Library as of Python version 2.1." }, { "code": null, "e": 4968, "s": 4665, "text": "Python unit testing framework supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. The unittest module provides classes that make it easy to support these qualities for a set of tests." }, { "code": null, "e": 5269, "s": 4968, "text": "This tutorial has been prepared for the beginners to help them understand the basic functionality of Python testing framework. After completing this tutorial you will find yourself at a moderate level of expertise in using Python testing framework from where you can take yourself to the next levels." }, { "code": null, "e": 5474, "s": 5269, "text": "You should have reasonable expertise in software development using Python language. Our Python tutorial is a good place to start learning Python. Knowledge of basics of software testing is also desirable." }, { "code": null, "e": 5801, "s": 5474, "text": "The classes needed to write tests are to be found in the 'unittest' module. If you are using older versions of Python (prior to Python 2.1), the module can be downloaded from http://pyunit.sourceforge.net/. However, unittest module is now a part of the standard Python distribution; hence it requires no separate installation." }, { "code": null, "e": 5983, "s": 5801, "text": "'unittest' supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework." }, { "code": null, "e": 6085, "s": 5983, "text": "The unittest module provides classes that make it easy to support these qualities for a set of tests." }, { "code": null, "e": 6155, "s": 6085, "text": "To achieve this, unittest supports the following important concepts −" }, { "code": null, "e": 6387, "s": 6155, "text": "test fixture − This represents the preparation needed to perform one or more tests, and any associate cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process." }, { "code": null, "e": 6619, "s": 6387, "text": "test fixture − This represents the preparation needed to perform one or more tests, and any associate cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process." }, { "code": null, "e": 6822, "s": 6619, "text": "test case − This is the smallest unit of testing. This checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases." }, { "code": null, "e": 7025, "s": 6822, "text": "test case − This is the smallest unit of testing. This checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases." }, { "code": null, "e": 7214, "s": 7025, "text": "test suite − This is a collection of test cases, test suites, or both. This is used to aggregate tests that should be executed together. Test suites are implemented by the TestSuite class." }, { "code": null, "e": 7403, "s": 7214, "text": "test suite − This is a collection of test cases, test suites, or both. This is used to aggregate tests that should be executed together. Test suites are implemented by the TestSuite class." }, { "code": null, "e": 7654, "s": 7403, "text": "test runner − This is a component which orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests." }, { "code": null, "e": 7905, "s": 7654, "text": "test runner − This is a component which orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests." }, { "code": null, "e": 7970, "s": 7905, "text": "The following steps are involved in writing a simple unit test −" }, { "code": null, "e": 8023, "s": 7970, "text": "Step 1 − Import the unittest module in your program." }, { "code": null, "e": 8133, "s": 8023, "text": "Step 2 − Define a function to be tested. In the following example, add() function is to be subjected to test." }, { "code": null, "e": 8194, "s": 8133, "text": "Step 3 − Create a testcase by subclassing unittest.TestCase." }, { "code": null, "e": 8286, "s": 8194, "text": "Step 4 − Define a test as a method inside the class. Name of method must start with 'test'." }, { "code": null, "e": 8428, "s": 8286, "text": "Step 5 − Each test calls assert function of TestCase class. There are many types of asserts. Following example calls assertEquals() function." }, { "code": null, "e": 8561, "s": 8428, "text": "Step 6 − assertEquals() function compares result of add() function with arg2 argument and throws assertionError if comparison fails." }, { "code": null, "e": 8624, "s": 8561, "text": "Step 7 − Finally, call main() method from the unittest module." }, { "code": null, "e": 8823, "s": 8624, "text": "import unittest\ndef add(x,y):\n return x + y\n \nclass SimpleTest(unittest.TestCase):\n def testadd1(self):\n self.assertEquals(add(4,5),9)\n \nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 8876, "s": 8823, "text": "Step 8 − Run the above script from the command line." }, { "code": null, "e": 9007, "s": 8876, "text": "C:\\Python27>python SimpleTest.py\n.\n----------------------------------------------------------------------\nRan 1 test in 0.000s\nOK\n" }, { "code": null, "e": 9079, "s": 9007, "text": "Step 9 − The following three could be the possible outcomes of a test −" }, { "code": null, "e": 9082, "s": 9079, "text": "OK" }, { "code": null, "e": 9128, "s": 9082, "text": "The test passes. ‘A’ is displayed on console." }, { "code": null, "e": 9133, "s": 9128, "text": "FAIL" }, { "code": null, "e": 9226, "s": 9133, "text": "The test does not pass, and raises an AssertionError exception. ‘F’ is displayed on console." }, { "code": null, "e": 9232, "s": 9226, "text": "ERROR" }, { "code": null, "e": 9317, "s": 9232, "text": "The test raises an exception other than AssertionError. ‘E’ is displayed on console." }, { "code": null, "e": 9395, "s": 9317, "text": "These outcomes are displayed on the console by '.', 'F' and 'E' respectively." }, { "code": null, "e": 9482, "s": 9395, "text": "The unittest module can be used from the command line to run single or multiple tests." }, { "code": null, "e": 9602, "s": 9482, "text": "python -m unittest test1\npython -m unittest test_module.TestClass\npython -m unittest test_module.TestClass.test_method\n" }, { "code": null, "e": 9728, "s": 9602, "text": "unittest supports the following command line options. For a list of all the command-line options, use the following command −" }, { "code": null, "e": 9751, "s": 9728, "text": "Python –m unittest -h\n" }, { "code": null, "e": 9762, "s": 9751, "text": "-h, --help" }, { "code": null, "e": 9780, "s": 9762, "text": "Show this message" }, { "code": null, "e": 9793, "s": 9780, "text": "v, --verbose" }, { "code": null, "e": 9808, "s": 9793, "text": "Verbose output" }, { "code": null, "e": 9820, "s": 9808, "text": "-q, --quiet" }, { "code": null, "e": 9835, "s": 9820, "text": "Minimal output" }, { "code": null, "e": 9850, "s": 9835, "text": "-f, --failfast" }, { "code": null, "e": 9872, "s": 9850, "text": "Stop on first failure" }, { "code": null, "e": 9884, "s": 9872, "text": "-c, --catch" }, { "code": null, "e": 9920, "s": 9884, "text": "Catch control-C and display results" }, { "code": null, "e": 9933, "s": 9920, "text": "-b, --buffer" }, { "code": null, "e": 9975, "s": 9933, "text": "Buffer stdout and stderr during test runs" }, { "code": null, "e": 10099, "s": 9975, "text": "This chapter discusses the classes and methods defined in the unittest module. There are five major classes in this module." }, { "code": null, "e": 10264, "s": 10099, "text": "Object of this class represents the smallest testable unit. It holds the test routines and provides hooks for preparing each routine and for cleaning up thereafter." }, { "code": null, "e": 10322, "s": 10264, "text": "The following methods are defined in the TestCase class −" }, { "code": null, "e": 10330, "s": 10322, "text": "setUp()" }, { "code": null, "e": 10431, "s": 10330, "text": "Method called to prepare the test fixture. This is called immediately before calling the test method" }, { "code": null, "e": 10442, "s": 10431, "text": "tearDown()" }, { "code": null, "e": 10591, "s": 10442, "text": "Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception," }, { "code": null, "e": 10604, "s": 10591, "text": "setUpClass()" }, { "code": null, "e": 10667, "s": 10604, "text": "A class method called before tests in an individual class run." }, { "code": null, "e": 10683, "s": 10667, "text": "tearDownClass()" }, { "code": null, "e": 10750, "s": 10683, "text": "A class method called after tests in an individual class have run." }, { "code": null, "e": 10769, "s": 10750, "text": "run(result = None)" }, { "code": null, "e": 10851, "s": 10769, "text": "Run the test, collecting the result into the test result object passed as result." }, { "code": null, "e": 10868, "s": 10851, "text": "skipTest(reason)" }, { "code": null, "e": 10937, "s": 10868, "text": "Calling this during a test method or setUp() skips the current test." }, { "code": null, "e": 10945, "s": 10937, "text": "debug()" }, { "code": null, "e": 10989, "s": 10945, "text": "Run the test without collecting the result." }, { "code": null, "e": 11008, "s": 10989, "text": "shortDescription()" }, { "code": null, "e": 11052, "s": 11008, "text": "Returns a one-line description of the test." }, { "code": null, "e": 11416, "s": 11052, "text": "There can be numerous tests written inside a TestCase class. These test methods may need database connection, temporary files or other resources to be initialized. These are called fixtures. TestCase includes a special hook to configure and clean up any fixtures needed by your tests. To configure the fixtures, override setUp(). To clean up, override tearDown()." }, { "code": null, "e": 11698, "s": 11416, "text": "In the following example, two tests are written inside the TestCase class. They test result of addition and subtraction of two values. The setup() method initializes the arguments based on shortDescription() of each test. teardown() method will be executed at the end of each test." }, { "code": null, "e": 12387, "s": 11698, "text": "import unittest\n\nclass simpleTest2(unittest.TestCase):\n def setUp(self):\n self.a = 10\n self.b = 20\n name = self.shortDescription()\n if name == \"Add\":\n self.a = 10\n self.b = 20\n print name, self.a, self.b\n if name == \"sub\":\n self.a = 50\n self.b = 60\n print name, self.a, self.b\n def tearDown(self):\n print '\\nend of test',self.shortDescription()\n\n def testadd(self):\n \"\"\"Add\"\"\"\n result = self.a+self.b\n self.assertTrue(result == 100)\n def testsub(self):\n \"\"\"sub\"\"\"\n result = self.a-self.b\n self.assertTrue(result == -10)\n \nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 12461, "s": 12387, "text": "Run the above code from the command line. It gives the following output −" }, { "code": null, "e": 12985, "s": 12461, "text": "C:\\Python27>python test2.py\nAdd 10 20\nF\nend of test Add\nsub 50 60\nend of test sub\n.\n================================================================\nFAIL: testadd (__main__.simpleTest2)\nAdd\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"test2.py\", line 21, in testadd\n self.assertTrue(result == 100)\nAssertionError: False is not true\n----------------------------------------------------------------------\nRan 2 tests in 0.015s\n\nFAILED (failures = 1)\n" }, { "code": null, "e": 13302, "s": 12985, "text": "TestCase class has a setUpClass() method which can be overridden to execute before the execution of individual tests inside a TestCase class. Similarly, tearDownClass() method will be executed after all test in the class. Both the methods are class methods. Hence, they must be decorated with @classmethod directive." }, { "code": null, "e": 13370, "s": 13302, "text": "The following example demonstrates the use of these class methods −" }, { "code": null, "e": 14045, "s": 13370, "text": "import unittest\n\nclass TestFixtures(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print 'called once before any tests in class'\n\n @classmethod\n def tearDownClass(cls):\n print '\\ncalled once after all tests in class'\n\n def setUp(self):\n self.a = 10\n self.b = 20\n name = self.shortDescription()\n print '\\n',name\n def tearDown(self):\n print '\\nend of test',self.shortDescription()\n\n def test1(self):\n \"\"\"One\"\"\"\n result = self.a+self.b\n self.assertTrue(True)\n def test2(self):\n \"\"\"Two\"\"\"\n result = self.a-self.b\n self.assertTrue(False)\n \nif __name__ == '__main__':\nunittest.main()" }, { "code": null, "e": 14262, "s": 14045, "text": "Python's testing framework provides a useful mechanism by which test case instances can be grouped together according to the features they test. This mechanism is made available by TestSuite class in unittest module." }, { "code": null, "e": 14333, "s": 14262, "text": "The following steps are involved in creating and running a test suite." }, { "code": null, "e": 14381, "s": 14333, "text": "Step 1 − Create an instance of TestSuite class." }, { "code": null, "e": 14410, "s": 14381, "text": "suite = unittest.TestSuite()" }, { "code": null, "e": 14467, "s": 14410, "text": "Step 2 − Add tests inside a TestCase class in the suite." }, { "code": null, "e": 14497, "s": 14467, "text": "suite.addTest(testcase class)" }, { "code": null, "e": 14568, "s": 14497, "text": "Step 3 − You can also use makeSuite() method to add tests from a class" }, { "code": null, "e": 14612, "s": 14568, "text": "suite = unittest.makeSuite(test case class)" }, { "code": null, "e": 14670, "s": 14612, "text": "Step 4 − Individual tests can also be added in the suite." }, { "code": null, "e": 14713, "s": 14670, "text": "suite.addTest(testcaseclass(\"\"testmethod\")" }, { "code": null, "e": 14768, "s": 14713, "text": "Step 5 − Create an object of the TestTestRunner class." }, { "code": null, "e": 14803, "s": 14768, "text": "runner = unittest.TextTestRunner()" }, { "code": null, "e": 14868, "s": 14803, "text": "Step 6 − Call the run() method to run all the tests in the suite" }, { "code": null, "e": 14887, "s": 14868, "text": "runner.run (suite)" }, { "code": null, "e": 14942, "s": 14887, "text": "The following methods are defined in TestSuite class −" }, { "code": null, "e": 14952, "s": 14942, "text": "addTest()" }, { "code": null, "e": 14990, "s": 14952, "text": "Adds a test method in the test suite." }, { "code": null, "e": 15001, "s": 14990, "text": "addTests()" }, { "code": null, "e": 15044, "s": 15001, "text": "Adds tests from multiple TestCase classes." }, { "code": null, "e": 15050, "s": 15044, "text": "run()" }, { "code": null, "e": 15143, "s": 15050, "text": "Runs the tests associated with this suite, collecting the result into the test result object" }, { "code": null, "e": 15151, "s": 15143, "text": "debug()" }, { "code": null, "e": 15224, "s": 15151, "text": "Runs the tests associated with this suite without collecting the result." }, { "code": null, "e": 15241, "s": 15224, "text": "countTestCases()" }, { "code": null, "e": 15301, "s": 15241, "text": "Returns the number of tests represented by this test object" }, { "code": null, "e": 15358, "s": 15301, "text": "The following example shows how to use TestSuite class −" }, { "code": null, "e": 16007, "s": 15358, "text": "import unittest\nclass suiteTest(unittest.TestCase):\n def setUp(self):\n self.a = 10\n self.b = 20\n \n def testadd(self):\n \"\"\"Add\"\"\"\n result = self.a+self.b\n self.assertTrue(result == 100)\n def testsub(self):\n \"\"\"sub\"\"\"\n result = self.a-self.b\n self.assertTrue(result == -10)\n \ndef suite():\n suite = unittest.TestSuite()\n## suite.addTest (simpleTest3(\"testadd\"))\n## suite.addTest (simpleTest3(\"testsub\"))\n suite.addTest(unittest.makeSuite(simpleTest3))\n return suite\n \nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n test_suite = suite()\n runner.run (test_suite)" }, { "code": null, "e": 16127, "s": 16007, "text": "You can experiment with the addTest() method by uncommenting the lines and comment statement having makeSuite() method." }, { "code": null, "e": 16434, "s": 16127, "text": "The unittest package has the TestLoader class which is used to create test suites from classes and modules. By default, the unittest.defaultTestLoader instance is automatically created when the unittest.main(0 method is called. An explicit instance, however enables the customization of certain properties." }, { "code": null, "e": 16536, "s": 16434, "text": "In the following code, tests from two classes are collected in a List by using the TestLoader object." }, { "code": null, "e": 16838, "s": 16536, "text": "import unittest\ntestList = [Test1, Test2]\ntestLoad = unittest.TestLoader()\n\nTestList = []\nfor testCase in testList:\n testSuite = testLoad.loadTestsFromTestCase(testCase)\n TestList.append(testSuite)\n \nnewSuite = unittest.TestSuite(TestList)\nrunner = unittest.TextTestRunner()\nrunner.run(newSuite)" }, { "code": null, "e": 16908, "s": 16838, "text": "The following table shows a list of methods in the TestLoader class −" }, { "code": null, "e": 16932, "s": 16908, "text": "loadTestsFromTestCase()" }, { "code": null, "e": 16996, "s": 16932, "text": "Return a suite of all tests cases contained in a TestCase class" }, { "code": null, "e": 17018, "s": 16996, "text": "loadTestsFromModule()" }, { "code": null, "e": 17083, "s": 17018, "text": "Return a suite of all tests cases contained in the given module." }, { "code": null, "e": 17103, "s": 17083, "text": "loadTestsFromName()" }, { "code": null, "e": 17163, "s": 17103, "text": "Return a suite of all tests cases given a string specifier." }, { "code": null, "e": 17174, "s": 17163, "text": "discover()" }, { "code": null, "e": 17299, "s": 17174, "text": "Find all the test modules by recursing into subdirectories from the specified start directory, and return a TestSuite object" }, { "code": null, "e": 17544, "s": 17299, "text": "This class is used to compile information about the tests that have been successful and the tests that have met failure. A TestResult object stores the results of a set of tests. A TestResult instance is returned by the TestRunner.run() method." }, { "code": null, "e": 17597, "s": 17544, "text": "TestResult instances have the following attributes −" }, { "code": null, "e": 17604, "s": 17597, "text": "Errors" }, { "code": null, "e": 17762, "s": 17604, "text": "A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test which raised an unexpected exception." }, { "code": null, "e": 17771, "s": 17762, "text": "Failures" }, { "code": null, "e": 17970, "s": 17771, "text": "A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test where a failure was explicitly signalled using the TestCase.assert*() methods." }, { "code": null, "e": 17978, "s": 17970, "text": "Skipped" }, { "code": null, "e": 18081, "s": 17978, "text": "A list containing 2-tuples of TestCase instances and strings holding the reason for skipping the test." }, { "code": null, "e": 18097, "s": 18081, "text": "wasSuccessful()" }, { "code": null, "e": 18171, "s": 18097, "text": "Return True if all tests run so far have passed, otherwise returns False." }, { "code": null, "e": 18178, "s": 18171, "text": "stop()" }, { "code": null, "e": 18265, "s": 18178, "text": "This method can be called to signal that the set of tests being run should be aborted." }, { "code": null, "e": 18280, "s": 18265, "text": "startTestRun()" }, { "code": null, "e": 18323, "s": 18280, "text": "Called once before any tests are executed." }, { "code": null, "e": 18337, "s": 18323, "text": "stopTestRun()" }, { "code": null, "e": 18379, "s": 18337, "text": "Called once after all tests are executed." }, { "code": null, "e": 18388, "s": 18379, "text": "testsRun" }, { "code": null, "e": 18426, "s": 18388, "text": "The total number of tests run so far." }, { "code": null, "e": 18433, "s": 18426, "text": "Buffer" }, { "code": null, "e": 18544, "s": 18433, "text": "If set to true, sys.stdout and sys.stderr will be buffered in between startTest() and stopTest() being called." }, { "code": null, "e": 18587, "s": 18544, "text": "The following code executes a test suite −" }, { "code": null, "e": 19082, "s": 18587, "text": "if __name__ == '__main__':\n runner = unittest.TextTestRunner()\n test_suite = suite()\n result = runner.run (test_suite)\n \n print \"---- START OF TEST RESULTS\"\n print result\n\n print \"result::errors\"\n print result.errors\n\n print \"result::failures\"\n print result.failures\n\n print \"result::skipped\"\n print result.skipped\n\n print \"result::successful\"\n print result.wasSuccessful()\n \n print \"result::test-run\"\n print result.testsRun\n print \"---- END OF TEST RESULTS\"" }, { "code": null, "e": 19137, "s": 19082, "text": "The code when executed displays the following output −" }, { "code": null, "e": 19557, "s": 19137, "text": "---- START OF TEST RESULTS\n<unittest.runner.TextTestResult run = 2 errors = 0 failures = 1>\nresult::errors\n[]\nresult::failures\n[(<__main__.suiteTest testMethod = testadd>, 'Traceback (most recent call last):\\n\n File \"test3.py\", line 10, in testadd\\n \n self.assertTrue(result == 100)\\nAssert\n ionError: False is not true\\n')]\nresult::skipped\n[]\nresult::successful\nFalse\nresult::test-run\n2\n---- END OF TEST RESULTS\n" }, { "code": null, "e": 19818, "s": 19557, "text": "Python testing framework uses Python's built-in assert() function which tests a particular condition. If the assertion fails, an AssertionError will be raised. The testing framework will then identify the test as Failure. Other exceptions are treated as Error." }, { "code": null, "e": 19899, "s": 19818, "text": "The following three sets of assertion functions are defined in unittest module −" }, { "code": null, "e": 19921, "s": 19899, "text": "Basic Boolean Asserts" }, { "code": null, "e": 19941, "s": 19921, "text": "Comparative Asserts" }, { "code": null, "e": 19965, "s": 19941, "text": "Asserts for Collections" }, { "code": null, "e": 20156, "s": 19965, "text": "Basic assert functions evaluate whether the result of an operation is True or False. All the assert methods accept a msg argument that, if specified, is used as the error message on failure." }, { "code": null, "e": 20192, "s": 20156, "text": "assertEqual(arg1, arg2, msg = None)" }, { "code": null, "e": 20283, "s": 20192, "text": "Test that arg1 and arg2 are equal. If the values do not compare equal, the test will fail." }, { "code": null, "e": 20322, "s": 20283, "text": "assertNotEqual(arg1, arg2, msg = None)" }, { "code": null, "e": 20413, "s": 20322, "text": "Test that arg1 and arg2 are not equal. If the values do compare equal, the test will fail." }, { "code": null, "e": 20442, "s": 20413, "text": "assertTrue(expr, msg = None)" }, { "code": null, "e": 20487, "s": 20442, "text": "Test that expr is true. If false, test fails" }, { "code": null, "e": 20517, "s": 20487, "text": "assertFalse(expr, msg = None)" }, { "code": null, "e": 20562, "s": 20517, "text": "Test that expr is false. If true, test fails" }, { "code": null, "e": 20595, "s": 20562, "text": "assertIs(arg1, arg2, msg = None)" }, { "code": null, "e": 20648, "s": 20595, "text": "Test that arg1 and arg2 evaluate to the same object." }, { "code": null, "e": 20684, "s": 20648, "text": "assertIsNot(arg1, arg2, msg = None)" }, { "code": null, "e": 20743, "s": 20684, "text": "Test that arg1 and arg2 don’t evaluate to the same object." }, { "code": null, "e": 20774, "s": 20743, "text": "assertIsNone(expr, msg = None)" }, { "code": null, "e": 20822, "s": 20774, "text": "Test that expr is None. If not None, test fails" }, { "code": null, "e": 20856, "s": 20822, "text": "assertIsNotNone(expr, msg = None)" }, { "code": null, "e": 20904, "s": 20856, "text": "Test that expr is not None. If None, test fails" }, { "code": null, "e": 20937, "s": 20904, "text": "assertIn(arg1, arg2, msg = None)" }, { "code": null, "e": 20964, "s": 20937, "text": "Test that arg1 is in arg2." }, { "code": null, "e": 21000, "s": 20964, "text": "assertNotIn(arg1, arg2, msg = None)" }, { "code": null, "e": 21031, "s": 21000, "text": "Test that arg1 is not in arg2." }, { "code": null, "e": 21070, "s": 21031, "text": "assertIsInstance(obj, cls, msg = None)" }, { "code": null, "e": 21106, "s": 21070, "text": "Test that obj is an instance of cls" }, { "code": null, "e": 21148, "s": 21106, "text": "assertNotIsInstance(obj, cls, msg = None)" }, { "code": null, "e": 21188, "s": 21148, "text": "Test that obj is not an instance of cls" }, { "code": null, "e": 21266, "s": 21188, "text": "Some of the above assertion functions are implemented in the following code −" }, { "code": null, "e": 21731, "s": 21266, "text": "import unittest\n\nclass SimpleTest(unittest.TestCase):\n def test1(self):\n self.assertEqual(4 + 5,9)\n def test2(self):\n self.assertNotEqual(5 * 2,10)\n def test3(self):\n self.assertTrue(4 + 5 == 9,\"The result is False\")\n def test4(self):\n self.assertTrue(4 + 5 == 10,\"assertion fails\")\n def test5(self):\n self.assertIn(3,[1,2,3])\n def test6(self):\n self.assertNotIn(3, range(5))\n\nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 21831, "s": 21731, "text": "When the above script is run, test2, test4 and test6 will show failure and others run successfully." }, { "code": null, "e": 22922, "s": 21831, "text": "FAIL: test2 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"C:\\Python27\\SimpleTest.py\", line 9, in test2\n self.assertNotEqual(5*2,10)\nAssertionError: 10 == 10\n\nFAIL: test4 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"C:\\Python27\\SimpleTest.py\", line 13, in test4\n self.assertTrue(4+5==10,\"assertion fails\")\nAssertionError: assertion fails\n\nFAIL: test6 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"C:\\Python27\\SimpleTest.py\", line 17, in test6\n self.assertNotIn(3, range(5))\nAssertionError: 3 unexpectedly found in [0, 1, 2, 3, 4]\n\n---------------------------------------------------------------------- \nRan 6 tests in 0.001s \n \nFAILED (failures = 3)\n" }, { "code": null, "e": 22986, "s": 22922, "text": "The second set of assertion functions are comparative asserts −" }, { "code": null, "e": 23221, "s": 22986, "text": "assertAlmostEqual (first, second, places = 7, msg = None, delta = None)\nTest that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7)," }, { "code": null, "e": 23293, "s": 23221, "text": "assertAlmostEqual (first, second, places = 7, msg = None, delta = None)" }, { "code": null, "e": 23456, "s": 23293, "text": "Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7)," }, { "code": null, "e": 23895, "s": 23456, "text": "assertNotAlmostEqual (first, second, places, msg, delta)\nTest that first and second are not approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero.\nIn both the above functions, if delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta.\nSupplying both delta and places raises a TypeError." }, { "code": null, "e": 23952, "s": 23895, "text": "assertNotAlmostEqual (first, second, places, msg, delta)" }, { "code": null, "e": 24119, "s": 23952, "text": "Test that first and second are not approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero." }, { "code": null, "e": 24282, "s": 24119, "text": "In both the above functions, if delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta." }, { "code": null, "e": 24334, "s": 24282, "text": "Supplying both delta and places raises a TypeError." }, { "code": null, "e": 24473, "s": 24334, "text": "assertGreater (first, second, msg = None)\nTest that first is greater than second depending on the method name. If not, the test will fail." }, { "code": null, "e": 24515, "s": 24473, "text": "assertGreater (first, second, msg = None)" }, { "code": null, "e": 24612, "s": 24515, "text": "Test that first is greater than second depending on the method name. If not, the test will fail." }, { "code": null, "e": 24767, "s": 24612, "text": "assertGreaterEqual (first, second, msg = None)\nTest that first is greater than or equal to second depending on the method name. If not, the test will fail" }, { "code": null, "e": 24814, "s": 24767, "text": "assertGreaterEqual (first, second, msg = None)" }, { "code": null, "e": 24922, "s": 24814, "text": "Test that first is greater than or equal to second depending on the method name. If not, the test will fail" }, { "code": null, "e": 25054, "s": 24922, "text": "assertLess (first, second, msg = None)\nTest that first is less than second depending on the method name. If not, the test will fail" }, { "code": null, "e": 25093, "s": 25054, "text": "assertLess (first, second, msg = None)" }, { "code": null, "e": 25186, "s": 25093, "text": "Test that first is less than second depending on the method name. If not, the test will fail" }, { "code": null, "e": 25338, "s": 25186, "text": "assertLessEqual (first, second, msg = None)\nTest that first is less than or equal to second depending upon the method name. If not, the test will fail." }, { "code": null, "e": 25382, "s": 25338, "text": "assertLessEqual (first, second, msg = None)" }, { "code": null, "e": 25490, "s": 25382, "text": "Test that first is less than or equal to second depending upon the method name. If not, the test will fail." }, { "code": null, "e": 25777, "s": 25490, "text": "assertRegexpMatches (text, regexp, msg = None)\nTest that a regexp search matches the text. In case of failure, the error message will include the pattern and the text. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search()." }, { "code": null, "e": 25824, "s": 25777, "text": "assertRegexpMatches (text, regexp, msg = None)" }, { "code": null, "e": 26064, "s": 25824, "text": "Test that a regexp search matches the text. In case of failure, the error message will include the pattern and the text. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search()." }, { "code": null, "e": 26369, "s": 26064, "text": "assertNotRegexpMatches (text, regexp, msg = None)\nVerifies that a regexp search does not match text. Fails with an error message including the pattern and the part of text that matches. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search()." }, { "code": null, "e": 26419, "s": 26369, "text": "assertNotRegexpMatches (text, regexp, msg = None)" }, { "code": null, "e": 26674, "s": 26419, "text": "Verifies that a regexp search does not match text. Fails with an error message including the pattern and the part of text that matches. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search()." }, { "code": null, "e": 26741, "s": 26674, "text": "The assertion functions are implemented in the following example −" }, { "code": null, "e": 27145, "s": 26741, "text": "import unittest\nimport math\nimport re\n\nclass SimpleTest(unittest.TestCase):\n def test1(self):\n self.assertAlmostEqual(22.0/7,3.14)\n def test2(self):\n self.assertNotAlmostEqual(10.0/3,3)\n def test3(self):\n self.assertGreater(math.pi,3)\n def test4(self):\n self.assertNotRegexpMatches(\"Tutorials Point (I) Private Limited\",\"Point\")\n\nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 27380, "s": 27145, "text": "The above script reports test1 and test4 as Failure. In test1, the division of 22/7 is not within 7 decimal places of 3.14. Similarly, since the second argument matches with the text in first argument, test4 results in AssertionError." }, { "code": null, "e": 28402, "s": 27380, "text": "=====================================================FAIL: test1 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"asserttest.py\", line 7, in test1\n self.assertAlmostEqual(22.0/7,3.14)\nAssertionError: 3.142857142857143 != 3.14 within 7 places\n================================================================\nFAIL: test4 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"asserttest.py\", line 13, in test4\n self.assertNotRegexpMatches(\"Tutorials Point (I) Private Limited\",\"Point\")\nAssertionError: Regexp matched: 'Point' matches 'Point' in 'Tutorials Point (I)\nPrivate Limited'\n----------------------------------------------------------------------\n\nRan 4 tests in 0.001s \n \nFAILED (failures = 2)\n" }, { "code": null, "e": 28531, "s": 28402, "text": "This set of assert functions are meant to be used with collection data types in Python, such as List, Tuple, Dictionary and Set." }, { "code": null, "e": 28574, "s": 28531, "text": "assertListEqual (list1, list2, msg = None)" }, { "code": null, "e": 28695, "s": 28574, "text": "Tests that two lists are equal. If not, an error message is constructed that shows only the differences between the two." }, { "code": null, "e": 28741, "s": 28695, "text": "assertTupleEqual (tuple1, tuple2, msg = None)" }, { "code": null, "e": 28863, "s": 28741, "text": "Tests that two tuples are equal. If not, an error message is constructed that shows only the differences between the two." }, { "code": null, "e": 28903, "s": 28863, "text": "assertSetEqual (set1, set2, msg = None)" }, { "code": null, "e": 29019, "s": 28903, "text": "Tests that two sets are equal. If not, an error message is constructed that lists the differences between the sets." }, { "code": null, "e": 29066, "s": 29019, "text": "assertDictEqual (expected, actual, msg = None)" }, { "code": null, "e": 29192, "s": 29066, "text": "Test that two dictionaries are equal. If not, an error message is constructed that shows the differences in the dictionaries." }, { "code": null, "e": 29245, "s": 29192, "text": "The following example implements the above methods −" }, { "code": null, "e": 29564, "s": 29245, "text": "import unittest\n\nclass SimpleTest(unittest.TestCase):\n def test1(self):\n self.assertListEqual([2,3,4], [1,2,3,4,5])\n def test2(self):\n self.assertTupleEqual((1*2,2*2,3*2), (2,4,6))\n def test3(self):\n self.assertDictEqual({1:11,2:22},{3:33,2:22,1:11})\n\nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 29694, "s": 29564, "text": "In the above example, test1 and test3 show AssertionError. Error message displays the differences in List and Dictionary objects." }, { "code": null, "e": 30848, "s": 29694, "text": "FAIL: test1 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"asserttest.py\", line 5, in test1\n self.assertListEqual([2,3,4], [1,2,3,4,5])\nAssertionError: Lists differ: [2, 3, 4] != [1, 2, 3, 4, 5]\n\nFirst differing element 0:\n2\n1\n\nSecond list contains 2 additional elements.\nFirst extra element 3:\n4\n\n- [2, 3, 4]\n+ [1, 2, 3, 4, 5]\n? +++ +++\n\nFAIL: test3 (__main__.SimpleTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"asserttest.py\", line 9, in test3\n self.assertDictEqual({1:11,2:22},{3:33,2:22,1:11})\nAssertionError: {1: 11, 2: 22} != {1: 11, 2: 22, 3: 33}\n- {1: 11, 2: 22}\n+ {1: 11, 2: 22, 3: 33}\n? +++++++\n \n---------------------------------------------------------------------- \nRan 3 tests in 0.001s \n \nFAILED (failures = 2)\n" }, { "code": null, "e": 31068, "s": 30848, "text": "The TestLoader class has a discover() function. Python testing framework uses this for simple test discovery. In order to be compatible, modules and packages containing tests must be importable from top level directory." }, { "code": null, "e": 31134, "s": 31068, "text": "The following is the basic command line usage of test discovery −" }, { "code": null, "e": 31163, "s": 31134, "text": "Python –m unittest discover\n" }, { "code": null, "e": 31308, "s": 31163, "text": "Interpreter tries to load all modules containing test from current directory and inner directories recursively. Other command line options are −" }, { "code": null, "e": 31322, "s": 31308, "text": "-v, --verbose" }, { "code": null, "e": 31337, "s": 31322, "text": "Verbose output" }, { "code": null, "e": 31359, "s": 31337, "text": "-s, --start-directory" }, { "code": null, "e": 31410, "s": 31359, "text": "directory Directory to start discovery (. default)" }, { "code": null, "e": 31424, "s": 31410, "text": "-p, --pattern" }, { "code": null, "e": 31479, "s": 31424, "text": "pattern Pattern to match test files (test*.py default)" }, { "code": null, "e": 31505, "s": 31479, "text": "-t, --top-level-directory" }, { "code": null, "e": 31576, "s": 31505, "text": "directory Top level directory of project (defaults to start directory)" }, { "code": null, "e": 31722, "s": 31576, "text": "For example, in order to discover the tests in modules whose names start with 'assert' in 'tests' directory, the following command line is used −" }, { "code": null, "e": 31786, "s": 31722, "text": "C:\\python27>python –m unittest –v –s \"c:\\test\" –p \"assert*.py\"\n" }, { "code": null, "e": 31968, "s": 31786, "text": "Test discovery loads tests by importing them. Once test discovery has found all the test files from the start directory you specify, it turns the paths into package names to import." }, { "code": null, "e": 32179, "s": 31968, "text": "If you supply the start directory as a package name rather than a path to a directory then discover assumes that whichever location it imports from is the location you intended, so you will not get the warning." }, { "code": null, "e": 32492, "s": 32179, "text": "Support for skipping tests has been added since Python 2.7. It is possible to skip individual test method or TestCase class, conditionally as well as unconditionally. The framework allows a certain test to be marked as an 'expected failure'. This test will 'fail' but will not be counted as failed in TestResult." }, { "code": null, "e": 32583, "s": 32492, "text": "To skip a method unconditionally, the following unittest.skip() class method can be used −" }, { "code": null, "e": 32822, "s": 32583, "text": "import unittest\n\n def add(x,y):\n return x+y\n\nclass SimpleTest(unittest.TestCase):\n @unittest.skip(\"demonstrating skipping\")\n def testadd1(self):\n self.assertEquals(add(4,5),9)\n\nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 32962, "s": 32822, "text": "Since skip() is a class method, it is prefixed by @ token. The method takes one argument: a log message describing the reason for the skip." }, { "code": null, "e": 33044, "s": 32962, "text": "When the above script is executed, the following result is displayed on console −" }, { "code": null, "e": 33188, "s": 33044, "text": "C:\\Python27>python skiptest.py\ns\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK (skipped = 1)\n" }, { "code": null, "e": 33246, "s": 33188, "text": "The character 's' indicates that a test has been skipped." }, { "code": null, "e": 33343, "s": 33246, "text": "Alternate syntax for skipping test is using instance method skipTest() inside the test function." }, { "code": null, "e": 33448, "s": 33343, "text": "def testadd2(self):\n self.skipTest(\"another method for skipping\")\n self.assertTrue(add(4 + 5) == 10)" }, { "code": null, "e": 33521, "s": 33448, "text": "The following decorators implement test skipping and expected failures −" }, { "code": null, "e": 33543, "s": 33521, "text": "unittest.skip(reason)" }, { "code": null, "e": 33638, "s": 33543, "text": "Unconditionally skip the decorated test. reason should describe why the test is being skipped." }, { "code": null, "e": 33673, "s": 33638, "text": "unittest.skipIf(condition, reason)" }, { "code": null, "e": 33719, "s": 33673, "text": "Skip the decorated test if condition is true." }, { "code": null, "e": 33758, "s": 33719, "text": "unittest.skipUnless(condition, reason)" }, { "code": null, "e": 33808, "s": 33758, "text": "Skip the decorated test unless condition is true." }, { "code": null, "e": 33835, "s": 33808, "text": "unittest.expectedFailure()" }, { "code": null, "e": 33939, "s": 33835, "text": "Mark the test as an expected failure. If the test fails when run, the test is not counted as a failure." }, { "code": null, "e": 34028, "s": 33939, "text": "The following example demonstrates the use of conditional skipping and expected failure." }, { "code": null, "e": 34707, "s": 34028, "text": "import unittest\n\nclass suiteTest(unittest.TestCase):\n a = 50\n b = 40\n \n def testadd(self):\n \"\"\"Add\"\"\"\n result = self.a+self.b\n self.assertEqual(result,100)\n\n @unittest.skipIf(a>b, \"Skip over this routine\")\n def testsub(self):\n \"\"\"sub\"\"\"\n result = self.a-self.b\n self.assertTrue(result == -10)\n \n @unittest.skipUnless(b == 0, \"Skip over this routine\")\n def testdiv(self):\n \"\"\"div\"\"\"\n result = self.a/self.b\n self.assertTrue(result == 1)\n\n @unittest.expectedFailure\n def testmul(self):\n \"\"\"mul\"\"\"\n result = self.a*self.b\n self.assertEqual(result == 0)\n\nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 34912, "s": 34707, "text": "In the above example, testsub() and testdiv() will be skipped. In the first case a>b is true, while in the second case b == 0 is not true. On the other hand, testmul() has been marked as expected failure." }, { "code": null, "e": 35011, "s": 34912, "text": "When the above script is run, two skipped tests show 's' and the expected failure is shown as 'x'." }, { "code": null, "e": 35514, "s": 35011, "text": "C:\\Python27>python skiptest.py\nFsxs\n================================================================\nFAIL: testadd (__main__.suiteTest)\nAdd\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"skiptest.py\", line 9, in testadd\n self.assertEqual(result,100)\nAssertionError: 90 != 100\n\n----------------------------------------------------------------------\nRan 4 tests in 0.000s\n\nFAILED (failures = 1, skipped = 2, expected failures = 1)\n" }, { "code": null, "e": 35617, "s": 35514, "text": "Python testing framework provides the following assertion methods to check that exceptions are raised." }, { "code": null, "e": 35976, "s": 35617, "text": "Test that an exception (first argument) is raised when a function is called with any positional or keyword arguments. The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception." }, { "code": null, "e": 36071, "s": 35976, "text": "In the example below, a test function is defined to check whether ZeroDivisionError is raised." }, { "code": null, "e": 36276, "s": 36071, "text": "import unittest\n\ndef div(a,b):\n return a/b\nclass raiseTest(unittest.TestCase):\n def testraise(self):\n self.assertRaises(ZeroDivisionError, div, 1,0)\n\nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 36488, "s": 36276, "text": "The testraise() function uses assertRaises() function to see if division by zero occurs when div() function is called. The above code will raise an exception. But changes arguments to div() function as follows −" }, { "code": null, "e": 36535, "s": 36488, "text": "self.assertRaises(ZeroDivisionError, div, 1,1)" }, { "code": null, "e": 36625, "s": 36535, "text": "When a code is run with these changes, the test fails as ZeroDivisionError doesn't occur." }, { "code": null, "e": 37095, "s": 36625, "text": "F\n================================================================\nFAIL: testraise (__main__.raiseTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"raisetest.py\", line 7, in testraise\n self.assertRaises(ZeroDivisionError, div, 1,1)\nAssertionError: ZeroDivisionError not raised\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (failures = 1)\n" }, { "code": null, "e": 37294, "s": 37095, "text": "Tests that regexp matches on the string representation of the raised exception. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search()." }, { "code": null, "e": 37357, "s": 37294, "text": "The following example shows how assertRaisesRegexp() is used −" }, { "code": null, "e": 37584, "s": 37357, "text": "import unittest\nimport re\n\nclass raiseTest(unittest.TestCase):\n def testraiseRegex(self):\n self.assertRaisesRegexp(TypeError, \"invalid\", reg,\"Point\",\"TutorialsPoint\")\n \nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 37691, "s": 37584, "text": "Here, testraseRegex() test doesn't fail as first argument. \"Point\" is found in the second argument string." }, { "code": null, "e": 38158, "s": 37691, "text": "================================================================\nFAIL: testraiseRegex (__main__.raiseTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"C:/Python27/raiseTest.py\", line 11, in testraiseRegex\n self.assertRaisesRegexp(TypeError, \"invalid\", reg,\"Point\",\"TutorialsPoint\")\nAssertionError: TypeError not raised\n----------------------------------------------------------------------\n" }, { "code": null, "e": 38198, "s": 38158, "text": "However, the change is as shown below −" }, { "code": null, "e": 38270, "s": 38198, "text": "self.assertRaisesRegexp(TypeError, \"invalid\", reg,123,\"TutorialsPoint\")" }, { "code": null, "e": 38354, "s": 38270, "text": "TypeError exception will be thrown. Hence, the following result will be displayed −" }, { "code": null, "e": 38865, "s": 38354, "text": "================================================================\nFAIL: testraiseRegex (__main__.raiseTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"raisetest.py\", line 11, in testraiseRegex\n self.assertRaisesRegexp(TypeError, \"invalid\", reg,123,\"TutorialsPoint\")\nAssertionError: \"invalid\" does not match \n \"first argument must be string or compiled pattern\"\n----------------------------------------------------------------------\n" }, { "code": null, "e": 39042, "s": 38865, "text": "Junit, the Java unit testing framework (Pyunit is implementation of JUnit) has a handy option of timeout. If a test takes more than specified time, it will be marked as failed." }, { "code": null, "e": 39181, "s": 39042, "text": "Python's testing framework doesn't contain any support for time out. However, a third part module called timeout-decorator can do the job." }, { "code": null, "e": 39220, "s": 39181, "text": "Download and install the module from −" }, { "code": null, "e": 39311, "s": 39220, "text": "https://pypi.python.org/packages/source/t/timeout-decorator/timeout-decorator-0.3.2.tar.gz" }, { "code": null, "e": 39348, "s": 39311, "text": "Import timeout_decorator in the code" }, { "code": null, "e": 39386, "s": 39348, "text": "Put timeout decorator before the test" }, { "code": null, "e": 39417, "s": 39386, "text": "@timeout_decorator.timeout(10)" }, { "code": null, "e": 39549, "s": 39417, "text": "If a test method below this line takes more than the timeout mentioned (10 mins) here, a TimeOutError will be raised. For example −" }, { "code": null, "e": 39844, "s": 39549, "text": "import time\nimport timeout_decorator\n\nclass timeoutTest(unittest.TestCase):\n\n @timeout_decorator.timeout(5)\n def testtimeout(self):\n print \"Start\"\n for i in range(1,10):\n time.sleep(1)\n print \"%d seconds have passed\" % i\n \nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 40082, "s": 39844, "text": "unittest2 is a backport of additional features added to the Python testing framework in Python 2.7 and onwards. It is tested to run on Python 2.6, 2.7, and 3.*. Latest version can be downloaded from https://pypi.python.org/pypi/unittest2" }, { "code": null, "e": 40174, "s": 40082, "text": "To use unittest2 instead of unittest, simply replace import unittest with import unittest2." }, { "code": null, "e": 40512, "s": 40174, "text": "Classes in unittest2 derive from the appropriate classes in unittest, so it should be possible to use the unittest2 test running infrastructure without having to switch all your tests to using unittest2 immediately. In case you intend to implement new features, subclass your testcase from unittest2.TestCase instead of unittest.TestCase" }, { "code": null, "e": 40562, "s": 40512, "text": "The following are the new features of unittest2 −" }, { "code": null, "e": 40605, "s": 40562, "text": "addCleanups for better resource management" }, { "code": null, "e": 40648, "s": 40605, "text": "addCleanups for better resource management" }, { "code": null, "e": 40681, "s": 40648, "text": "Contains many new assert methods" }, { "code": null, "e": 40714, "s": 40681, "text": "Contains many new assert methods" }, { "code": null, "e": 40787, "s": 40714, "text": "assertRaises as context manager, with access to the exception afterwards" }, { "code": null, "e": 40860, "s": 40787, "text": "assertRaises as context manager, with access to the exception afterwards" }, { "code": null, "e": 40925, "s": 40860, "text": "Has module level fixtures such as setUpModule and tearDownModule" }, { "code": null, "e": 40990, "s": 40925, "text": "Has module level fixtures such as setUpModule and tearDownModule" }, { "code": null, "e": 41062, "s": 40990, "text": "Includes load_tests protocol for loading tests from modules or packages" }, { "code": null, "e": 41134, "s": 41062, "text": "Includes load_tests protocol for loading tests from modules or packages" }, { "code": null, "e": 41185, "s": 41134, "text": "startTestRun and stopTestRun methods on TestResult" }, { "code": null, "e": 41236, "s": 41185, "text": "startTestRun and stopTestRun methods on TestResult" }, { "code": null, "e": 41355, "s": 41236, "text": "In Python 2.7, you invoke the unittest command line features (including test discover) with python -m unittest <args>." }, { "code": null, "e": 41401, "s": 41355, "text": "Instead, unittest2 comes with a script unit2." }, { "code": null, "e": 41438, "s": 41401, "text": "unit2 discover\nunit2 -v test_module\n" }, { "code": null, "e": 41823, "s": 41438, "text": "More efficient handling of control-C during a test run is provided by The -c/--catch command-line option to unittest, along with the catchbreak parameter. With catch break behavior enabled, control-C will allow the currently running test to complete, and the test run will then end and report all the results so far. A second control-c will raise a KeyboardInterrupt in the usual way." }, { "code": null, "e": 42159, "s": 41823, "text": "If the unittest handler is called but signal.SIGINT handler isn’t installed, then it calls for the default handler. This will normally be the expected behavior by code that replaces an installed handler and delegates to it. For individual tests that need unittest control-c handling disabled, the removeHandler() decorator can be used." }, { "code": null, "e": 42256, "s": 42159, "text": "The following utility functions enable control-c handling functionality within test frameworks −" }, { "code": null, "e": 42374, "s": 42256, "text": "Install the control-c handler. When a signal.SIGINT is received all registered results have TestResult.stop() called." }, { "code": null, "e": 42542, "s": 42374, "text": "Register a TestResult object for control-c handling. Registering a result stores a weak reference to it, so it doesn’t prevent the result from being garbage collected." }, { "code": null, "e": 42699, "s": 42542, "text": "Remove a registered result. Once a result has been removed then TestResult.stop() will no longer be called on that result object in response to a control-c." }, { "code": null, "e": 42920, "s": 42699, "text": "When called without arguments, this function removes the control-c handler if it has been installed. This function can also be used as a test decorator to temporarily remove the handler whilst the test is being executed." }, { "code": null, "e": 43171, "s": 42920, "text": "The unittest module is installed to discover and run tests interactively. This utility, a Python script 'inittestgui.py' uses Tkinter module which is a Python port for TK graphics tool kit. It gives an easy to use GUI for discovery and running tests." }, { "code": null, "e": 43194, "s": 43171, "text": "Python unittestgui.py\n" }, { "code": null, "e": 43330, "s": 43194, "text": "Click the 'Discover Tests' button. A small dialog box appears where you can select directory and modules from which test are to be run." }, { "code": null, "e": 43475, "s": 43330, "text": "Finally, click the start button. Tests will be discovered from the selected path and module names, and the result pane will display the results." }, { "code": null, "e": 43568, "s": 43475, "text": "In order to see the details of individual test, select and click on test in the result box −" }, { "code": null, "e": 43700, "s": 43568, "text": "If you do not find this utility in the Python installation, you can obtain it from the project page http://pyunit.sourceforge.net/." }, { "code": null, "e": 43768, "s": 43700, "text": "Similar, utility based on wxpython toolkit is also available there." }, { "code": null, "e": 44010, "s": 43768, "text": "Python' standard distribution contains 'Doctest' module. This module's functionality makes it possible to search for pieces of text that look like interactive Python sessions, and executes these sessions to see if they work exactly as shown." }, { "code": null, "e": 44066, "s": 44010, "text": "Doctest can be very useful in the following scenarios −" }, { "code": null, "e": 44186, "s": 44066, "text": "To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented." }, { "code": null, "e": 44306, "s": 44186, "text": "To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented." }, { "code": null, "e": 44427, "s": 44306, "text": "To perform regression testing by verifying that interactive examples from a test file or a test object work as expected." }, { "code": null, "e": 44548, "s": 44427, "text": "To perform regression testing by verifying that interactive examples from a test file or a test object work as expected." }, { "code": null, "e": 44644, "s": 44548, "text": "To write tutorial documentation for a package, liberally illustrated with input-output examples" }, { "code": null, "e": 44740, "s": 44644, "text": "To write tutorial documentation for a package, liberally illustrated with input-output examples" }, { "code": null, "e": 45113, "s": 44740, "text": "In Python, a 'docstring' is a string literal which appears as the first expression in a class, function or module. It is ignored when the suite is executed, but it is recognized by the compiler and put into the __doc__ attribute of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object." }, { "code": null, "e": 45327, "s": 45113, "text": "It is a usual practice to put example usage of different parts of Python code inside the docstring. The doctest module allows to verify that these docstrings are up-to-date with the intermittent revisions in code." }, { "code": null, "e": 45514, "s": 45327, "text": "In the following code, a factorial function is defined interspersed with example usage. In order to verify if the example usage is correct, call the testmod() function in doctest module." }, { "code": null, "e": 46018, "s": 45514, "text": "\"\"\"\nThis is the \"example\" module.\n\nThe example module supplies one function, factorial(). For example,\n\n>>> factorial(5)\n120\n\"\"\"\n\ndef factorial(x):\n \"\"\"Return the factorial of n, an exact integer >= 0.\n >>> factorial(-1)\n Traceback (most recent call last):\n ...\n ValueError: x must be >= 0\n \"\"\"\n \n if not x >= 0:\n raise ValueError(\"x must be >= 0\")\n f = 1\n for i in range(1,x+1):\n f = f*i\n return f\n \nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()" }, { "code": null, "e": 46122, "s": 46018, "text": "Enter and save the above script as FactDocTest.py and try to execute this script from the command line." }, { "code": null, "e": 46145, "s": 46122, "text": "Python FactDocTest.py\n" }, { "code": null, "e": 46243, "s": 46145, "text": "No output will be shown unless the example fails. Now, change the command line to the following −" }, { "code": null, "e": 46269, "s": 46243, "text": "Python FactDocTest.py –v\n" }, { "code": null, "e": 46318, "s": 46269, "text": "The console will now show the following output −" }, { "code": null, "e": 46656, "s": 46318, "text": "C:\\Python27>python FactDocTest.py -v\nTrying:\n factorial(5)\nExpecting:\n 120\nok\nTrying:\n factorial(-1)\nExpecting:\n Traceback (most recent call last):\n ...\n ValueError: x must be >= 0\nok\n2 items passed all tests:\n 1 tests in __main__\n 1 tests in __main__.factorial\n2 tests in 2 items.\n2 passed and 0 failed.\nTest passed.\n" }, { "code": null, "e": 46913, "s": 46656, "text": "If, on the other hand, the code of factorial() function doesn't give expected result in docstring, failure result will be displayed. For instance, change f = 2 in place of f = 1 in the above script and run the doctest again. The result will be as follows −" }, { "code": null, "e": 47492, "s": 46913, "text": "Trying:\n factorial(5)\nExpecting:\n 120\n**********************************************************************\nFile \"docfacttest.py\", line 6, in __main__\nFailed example:\nfactorial(5)\nExpected:\n 120\nGot:\n 240\nTrying:\n factorial(-1)\nExpecting:\n Traceback (most recent call last):\n ...\n ValueError: x must be >= 0\nok\n1 items passed all tests:\n 1 tests in __main__.factorial\n**********************************************************************\n1 items had failures:\n 1 of 1 in __main__\n2 tests in 2 items.\n1 passed and 1 failed.\n***Test Failed*** 1 failures.\n" }, { "code": null, "e": 47625, "s": 47492, "text": "Another simple application of doctest is testing interactive examples in a text file. This can be done with the testfile() function." }, { "code": null, "e": 47690, "s": 47625, "text": "The following text is stored in a text file named 'example.txt'." }, { "code": null, "e": 47919, "s": 47690, "text": "Using ''factorial''\n-------------------\nThis is an example text file in reStructuredText format. First import\n''factorial'' from the ''example'' module:\n >>> from example import factorial\nNow use it:\n >>> factorial(5)\n 120" }, { "code": null, "e": 48058, "s": 47919, "text": "The file content is treated as docstring. In order to verify the examples in the text file, use the testfile() function of doctest module." }, { "code": null, "e": 48280, "s": 48058, "text": "def factorial(x):\n if not x >= 0:\n raise ValueError(\"x must be >= 0\")\n f = 1\n for i in range(1,x+1):\n f = f*i\n return f\n \nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"example.txt\")" }, { "code": null, "e": 48510, "s": 48280, "text": "As with the testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to console, using the same format as testmod()." }, { "code": null, "e": 48740, "s": 48510, "text": "As with the testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to console, using the same format as testmod()." }, { "code": null, "e": 48897, "s": 48740, "text": "In most cases a copy-and-paste of an interactive console session works fine, but doctest isn’t trying to do an exact emulation of any specific Python shell." }, { "code": null, "e": 49054, "s": 48897, "text": "In most cases a copy-and-paste of an interactive console session works fine, but doctest isn’t trying to do an exact emulation of any specific Python shell." }, { "code": null, "e": 49235, "s": 49054, "text": "Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line." }, { "code": null, "e": 49416, "s": 49235, "text": "Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line." }, { "code": null, "e": 49659, "s": 49416, "text": "Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put <BLANKLINE> in your doctest example each place a blank line is expected." }, { "code": null, "e": 49902, "s": 49659, "text": "Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put <BLANKLINE> in your doctest example each place a blank line is expected." }, { "code": null, "e": 50023, "s": 49902, "text": "The doctest API revolves around the following two container classes used to store interactive examples from docstrings −" }, { "code": null, "e": 50093, "s": 50023, "text": "Example − A single Python statement, paired with its expected output." }, { "code": null, "e": 50163, "s": 50093, "text": "Example − A single Python statement, paired with its expected output." }, { "code": null, "e": 50259, "s": 50163, "text": "DocTest − A collection of Examples, typically extracted from a single docstring or a text file." }, { "code": null, "e": 50355, "s": 50259, "text": "DocTest − A collection of Examples, typically extracted from a single docstring or a text file." }, { "code": null, "e": 50465, "s": 50355, "text": "The following additional processing classes are defined to find, parse, and run, and check doctest examples −" }, { "code": null, "e": 50623, "s": 50465, "text": "DocTestFinder − Finds all docstrings in a given module, and uses a DocTestParser to create a DocTest from every docstring that contains interactive examples." }, { "code": null, "e": 50781, "s": 50623, "text": "DocTestFinder − Finds all docstrings in a given module, and uses a DocTestParser to create a DocTest from every docstring that contains interactive examples." }, { "code": null, "e": 50869, "s": 50781, "text": "DocTestParser − Creates a doctest object from a string (such as an object’s docstring)." }, { "code": null, "e": 50957, "s": 50869, "text": "DocTestParser − Creates a doctest object from a string (such as an object’s docstring)." }, { "code": null, "e": 51059, "s": 50957, "text": "DocTestRunner − Executes the examples in a doctest, and uses an OutputChecker to verify their output." }, { "code": null, "e": 51161, "s": 51059, "text": "DocTestRunner − Executes the examples in a doctest, and uses an OutputChecker to verify their output." }, { "code": null, "e": 51285, "s": 51161, "text": "OutputChecker − Compares the actual output from a doctest example with the expected output, and decides whether they match." }, { "code": null, "e": 51409, "s": 51285, "text": "OutputChecker − Compares the actual output from a doctest example with the expected output, and decides whether they match." }, { "code": null, "e": 51717, "s": 51409, "text": "It is a processing class used to extract the doctests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types — modules, functions, classes, methods, staticmethods, classmethods, and properties." }, { "code": null, "e": 51881, "s": 51717, "text": "This class defines the find() method. It returns a list of the DocTests that are defined by the object‘s docstring, or by any of its contained objects’ docstrings." }, { "code": null, "e": 52042, "s": 51881, "text": "It is a processing class used to extract interactive examples from a string, and use them to create a DocTest object. This class defines the following methods −" }, { "code": null, "e": 52150, "s": 52042, "text": "get_doctest() − Extract all doctest examples from the given string, and collect them into a DocTest object." }, { "code": null, "e": 52258, "s": 52150, "text": "get_doctest() − Extract all doctest examples from the given string, and collect them into a DocTest object." }, { "code": null, "e": 52512, "s": 52258, "text": "get_examples(string[, name]) − Extract all doctest examples from the given string, and return them as a list of Example objects. Line numbers are 0-based. The optional argument name is a name identifying this string, and is only used for error messages." }, { "code": null, "e": 52766, "s": 52512, "text": "get_examples(string[, name]) − Extract all doctest examples from the given string, and return them as a list of Example objects. Line numbers are 0-based. The optional argument name is a name identifying this string, and is only used for error messages." }, { "code": null, "e": 53055, "s": 52766, "text": "parse(string[, name]) − Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument name is a name identifying this string, and is only used for error messages." }, { "code": null, "e": 53344, "s": 53055, "text": "parse(string[, name]) − Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument name is a name identifying this string, and is only used for error messages." }, { "code": null, "e": 53479, "s": 53344, "text": "This is a processing class used to execute and verify the interactive examples in a DocTest. The following methods are defined in it −" }, { "code": null, "e": 53667, "s": 53479, "text": "Report that the test runner is about to process the given example. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly" }, { "code": null, "e": 53837, "s": 53667, "text": "Report that the given example ran successfully. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly." }, { "code": null, "e": 53997, "s": 53837, "text": "Report that the given example failed. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly." }, { "code": null, "e": 54181, "s": 53997, "text": "Report that the given example raised an unexpected exception. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly." }, { "code": null, "e": 54281, "s": 54181, "text": "Run the examples in test (a DocTest object), and display the results using the writer function out." }, { "code": null, "e": 54565, "s": 54281, "text": "Print a summary of all the test cases that have been run by this DocTestRunner, and return a named tuple TestResults(failed, attempted). The optional verbose argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner‘s verbosity is used." }, { "code": null, "e": 54671, "s": 54565, "text": "This class is used to check whether the actual output from a doctest example matches the expected output." }, { "code": null, "e": 54721, "s": 54671, "text": "The following methods are defined in this class −" }, { "code": null, "e": 55076, "s": 54721, "text": "Return True if the actual output from an example (got) matches with the expected output (want). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See section Option Flags and Directives for more information about option flags." }, { "code": null, "e": 55206, "s": 55076, "text": "Return a string describing the differences between the expected output for a given example (example) and the actual output (got)." }, { "code": null, "e": 55442, "s": 55206, "text": "The doctest module provides two functions that can be used to create unittest test suites from modules and text files containing doctests. To integrate with unittest test discovery, include a load_tests() function in your test module −" }, { "code": null, "e": 55607, "s": 55442, "text": "import unittest\nimport doctest\nimport doctestexample\n\ndef load_tests(loader, tests, ignore):\n tests.addTests(doctest.DocTestSuite(doctestexample))\n return tests" }, { "code": null, "e": 55764, "s": 55607, "text": "A combined TestSuite of tests from unittest as well as doctest will be formed and it can now be executed by unittest module's main() method or run() method." }, { "code": null, "e": 55895, "s": 55764, "text": "The following are the two main functions for creating unittest.TestSuite instances from text files and modules with the doctests −" }, { "code": null, "e": 56316, "s": 55895, "text": "It is used to convert doctest tests from one or more text files to a unittest.TestSuite. The returned unittest.TestSuite is to be run by the unittest framework and runs the interactive examples in each file. If any of the examples in a file fails, then the synthesized unit test fails, and a failureException exception is raised showing the name of the file containing the test and a (sometimes approximate) line number." }, { "code": null, "e": 56390, "s": 56316, "text": "It is used to convert doctest tests for a module to a unittest.TestSuite." }, { "code": null, "e": 56699, "s": 56390, "text": "The returned unittest.TestSuite is to be run by the unittest framework and runs each doctest in the module. If any of the doctests fail, then the synthesized unit test fails, and a failureException exception is raised showing the name of the file containing the test and a (sometimes approximate) line number" }, { "code": null, "e": 56851, "s": 56699, "text": "Under the covers, DocTestSuite() creates a unittest.TestSuite out of doctest.DocTestCase instances, and DocTestCase is a subclass of unittest.TestCase." }, { "code": null, "e": 56990, "s": 56851, "text": "Similarly, DocFileSuite() creates a unittest.TestSuite out of doctest.DocFileCase instances, and DocFileCase is a subclass of DocTestCase." }, { "code": null, "e": 57206, "s": 56990, "text": "So both ways of creating a unittest.TestSuite run instances of DocTestCase. When you run doctest functions yourself, you can control the doctest options in use directly, by passing option flags to doctest functions." }, { "code": null, "e": 57519, "s": 57206, "text": "However, if you’re writing a unittest framework, unittest ultimately controls when and how the tests get run. The framework author typically wants to control doctest reporting options (perhaps, e.g., specified by command line options), but there’s no way to pass options through unittest to doctest test runners." }, { "code": null, "e": 57824, "s": 57519, "text": "It was in 2004 that Holger Krekel renamed his std package, whose name was often confused with that of the Standard Library that ships with Python, to the (only slightly less confusing) name 'py.' Though the package contains several sub-packages, it is now known almost entirely for its py.test framework." }, { "code": null, "e": 58092, "s": 57824, "text": "The py.test framework has set up a new standard for Python testing, and has become very popular with many developers today. The elegant and Pythonic idioms it introduced for test writing have made it possible for test suites to be written in a far more compact style." }, { "code": null, "e": 58338, "s": 58092, "text": "py.test is a no-boilerplate alternative to Python’s standard unittest module. Despite being a fully-featured and extensible test tool, it boasts of a simple syntax. Creating a test suite is as easy as writing a module with a couple of functions." }, { "code": null, "e": 58439, "s": 58338, "text": "py.test runs on all POSIX operating systems and WINDOWS (XP/7/8) with Python versions 2.6 and above." }, { "code": null, "e": 58586, "s": 58439, "text": "Use the following code to load the pytest module in the current Python distribution as well as a py.test.exe utility. Tests can be run using both." }, { "code": null, "e": 58606, "s": 58586, "text": "pip install pytest\n" }, { "code": null, "e": 58855, "s": 58606, "text": "You can simply use the assert statement for asserting test expectations. pytest’s assert introspection will intelligently report intermediate values of the assert expression freeing you from the need to learn the many names of JUnit legacy methods." }, { "code": null, "e": 58958, "s": 58855, "text": "# content of test_sample.py\ndef func(x):\n return x + 1\n \ndef test_answer():\n assert func(3) == 5" }, { "code": null, "e": 59081, "s": 58958, "text": "Use the following command line to run the above test. Once the test is run, the following result is displayed on console −" }, { "code": null, "e": 59741, "s": 59081, "text": "C:\\Python27>scripts\\py.test -v test_sample.py\n============================= test session starts =====================\nplatform win32 -- Python 2.7.9, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- C:\\Pyth\non27\\python.exe\ncachedir: .cache\nrootdir: C:\\Python27, inifile:\ncollected 1 items\ntest_sample.py::test_answer FAILED\n================================== FAILURES =====================\n_________________________________ test_answer _________________________________\n def test_answer():\n> assert func(3) == 5\nE assert 4 == 5\nE + where 4 = func(3)\ntest_sample.py:7: AssertionError\n========================== 1 failed in 0.05 seconds ====================\n" }, { "code": null, "e": 59832, "s": 59741, "text": "The test can also be run from the command line by including pytest module using –m switch." }, { "code": null, "e": 59865, "s": 59832, "text": "python -m pytest test_sample.py\n" }, { "code": null, "e": 60024, "s": 59865, "text": "Once you start to have more than a few tests it often makes sense to group tests logically, in classes and modules. Let’s write a class containing two tests −" }, { "code": null, "e": 60177, "s": 60024, "text": "class TestClass:\n def test_one(self):\n x = \"this\"\n assert 'h' in x\n def test_two(self):\n x = \"hello\"\n assert hasattr(x, 'check')" }, { "code": null, "e": 60223, "s": 60177, "text": "The following test result will be displayed −" }, { "code": null, "e": 61010, "s": 60223, "text": "C:\\Python27>scripts\\py.test -v test_class.py\n============================= test session starts =====================\nplatform win32 -- Python 2.7.9, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- C:\\Pyt\non27\\python.exe\ncachedir: .cache\nrootdir: C:\\Python27, inifile:\ncollected 2 items\ntest_class.py::TestClass::test_one PASSED\ntest_class.py::TestClass::test_two FAILED\n================================== FAILURES =====================\n_____________________________ TestClass.test_two ______________________________\nself = <test_class.TestClass instance at 0x01309DA0>\n\n def test_two(self):\n x = \"hello\"\n> assert hasattr(x, 'check')\nE assert hasattr('hello', 'check')\n\ntest_class.py:7: AssertionError\n===================== 1 failed, 1 passed in 0.06 seconds ======================\n" }, { "code": null, "e": 61257, "s": 61010, "text": "The nose project was released in 2005, the year after py.test received its modern guise. It was written by Jason Pellerin to support the same test idioms that had been pioneered by py.test, but in a package that is easier to install and maintain." }, { "code": null, "e": 61319, "s": 61257, "text": "The nose module can be installed with the help of pip utility" }, { "code": null, "e": 61337, "s": 61319, "text": "pip install nose\n" }, { "code": null, "e": 61512, "s": 61337, "text": "This will install the nose module in the current Python distribution as well as a nosetest.exe, which means the test can be run using this utility as well as using –m switch." }, { "code": null, "e": 61594, "s": 61512, "text": "C:\\python>nosetests –v test_sample.py\nOr\nC:\\python>python –m nose test_sample.py\n" }, { "code": null, "e": 61897, "s": 61594, "text": "nose collects tests from unittest.TestCase subclasses, of course. We can also write simple test functions, as well as test classes that are not subclasses of unittest.TestCase. nose also supplies a number of helpful functions for writing timed tests, testing for exceptions, and other common use cases." }, { "code": null, "e": 62102, "s": 61897, "text": "nose collects tests automatically. There’s no need to manually collect test cases into test suites. Running tests is responsive, since nose begins running tests as soon as the first test module is loaded." }, { "code": null, "e": 62275, "s": 62102, "text": "As with the unittest module, nose supports fixtures at the package, module, class, and test case level, so expensive initialization can be done as infrequently as possible." }, { "code": null, "e": 62340, "s": 62275, "text": "Let us consider nosetest.py similar to the script used earlier −" }, { "code": null, "e": 62440, "s": 62340, "text": "# content of nosetest.py\ndef func(x):\n return x + 1\n \ndef test_answer():\n assert func(3) == 5" }, { "code": null, "e": 62512, "s": 62440, "text": "In order to run the above test, use the following command line syntax −" }, { "code": null, "e": 62548, "s": 62512, "text": "C:\\python>nosetests –v nosetest.py\n" }, { "code": null, "e": 62601, "s": 62548, "text": "The output displayed on console will be as follows −" }, { "code": null, "e": 63145, "s": 62601, "text": "nosetest.test_answer ... FAIL\n================================================================\nFAIL: nosetest.test_answer\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"C:\\Python34\\lib\\site-packages\\nose\\case.py\", line 198, in runTest\n self.test(*self.arg)\n File \"C:\\Python34\\nosetest.py\", line 6, in test_answer\n assert func(3) == 5\nAssertionError\n----------------------------------------------------------------------\nRan 1 test in 0.000s\nFAILED (failures = 1)\n" }, { "code": null, "e": 63237, "s": 63145, "text": "nose can be integrated with DocTest by using with-doctest option in athe bove command line." }, { "code": null, "e": 63279, "s": 63237, "text": "\\nosetests --with-doctest -v nosetest.py\n" }, { "code": null, "e": 63315, "s": 63279, "text": "You may use nose in a test script −" }, { "code": null, "e": 63339, "s": 63315, "text": "import nose\nnose.main()" }, { "code": null, "e": 63464, "s": 63339, "text": "If you do not wish the test script to exit with 0 on success and 1 on failure (like unittest.main), use nose.run() instead −" }, { "code": null, "e": 63496, "s": 63464, "text": "import nose\nresult = nose.run()" }, { "code": null, "e": 63605, "s": 63496, "text": "The result will be true if the test run is successful, or false if it fails or raises an uncaught exception." }, { "code": null, "e": 63925, "s": 63605, "text": "nose supports fixtures (setup and teardown methods) at the package, module, class, and test level. As with py.test or unittest fixtures, setup always runs before any test (or collection of tests for test packages and modules); teardown runs if setup has completed successfully, regardless of the status of the test run." }, { "code": null, "e": 64156, "s": 63925, "text": "The nose.tools module provides a number of testing aids that you may find useful, including decorators for restricting test execution time and testing for exceptions, and all of the same assertX methods found in unittest.TestCase." }, { "code": null, "e": 64213, "s": 64156, "text": "nose.tools.ok_(expr, msg = None) − Shorthand for assert." }, { "code": null, "e": 64270, "s": 64213, "text": "nose.tools.ok_(expr, msg = None) − Shorthand for assert." }, { "code": null, "e": 64355, "s": 64270, "text": "nose.tools.eq_(a, b, msg = None) − Shorthand for ‘assert a == b, “%r != %r” % (a, b)" }, { "code": null, "e": 64440, "s": 64355, "text": "nose.tools.eq_(a, b, msg = None) − Shorthand for ‘assert a == b, “%r != %r” % (a, b)" }, { "code": null, "e": 64625, "s": 64440, "text": "nose.tools.make_decorator(func) − Wraps a test decorator so as to properly replicate metadata of the decorated function, including nose’s additional stuff (namely, setup and teardown)." }, { "code": null, "e": 64810, "s": 64625, "text": "nose.tools.make_decorator(func) − Wraps a test decorator so as to properly replicate metadata of the decorated function, including nose’s additional stuff (namely, setup and teardown)." }, { "code": null, "e": 64895, "s": 64810, "text": "nose.tools.raises(*exceptions) − Test must raise one of expected exceptions to pass." }, { "code": null, "e": 64980, "s": 64895, "text": "nose.tools.raises(*exceptions) − Test must raise one of expected exceptions to pass." }, { "code": null, "e": 65059, "s": 64980, "text": "nose.tools.timed(limit) − Test must finish within specified time limit to pass" }, { "code": null, "e": 65138, "s": 65059, "text": "nose.tools.timed(limit) − Test must finish within specified time limit to pass" }, { "code": null, "e": 65213, "s": 65138, "text": "nose.tools.istest(func) − Decorator to mark a function or method as a test" }, { "code": null, "e": 65288, "s": 65213, "text": "nose.tools.istest(func) − Decorator to mark a function or method as a test" }, { "code": null, "e": 65368, "s": 65288, "text": "nose.tools.nottest(func) − Decorator to mark a function or method as not a test" }, { "code": null, "e": 65448, "s": 65368, "text": "nose.tools.nottest(func) − Decorator to mark a function or method as not a test" }, { "code": null, "e": 65635, "s": 65448, "text": "Python's testing framework, unittest, doesn't have a simple way of running parametrized test cases. In other words, you can't easily pass arguments into a unittest.TestCase from outside." }, { "code": null, "e": 65719, "s": 65635, "text": "However, pytest module ports test parametrization in several well-integrated ways −" }, { "code": null, "e": 65808, "s": 65719, "text": "pytest.fixture() allows you to define parametrization at the level of fixture functions." }, { "code": null, "e": 65897, "s": 65808, "text": "pytest.fixture() allows you to define parametrization at the level of fixture functions." }, { "code": null, "e": 66071, "s": 65897, "text": "@pytest.mark.parametrize allows to define parametrization at the function or class level. It provides multiple argument/fixture sets for a particular test function or class." }, { "code": null, "e": 66245, "s": 66071, "text": "@pytest.mark.parametrize allows to define parametrization at the function or class level. It provides multiple argument/fixture sets for a particular test function or class." }, { "code": null, "e": 66350, "s": 66245, "text": "pytest_generate_tests enables implementing your own custom dynamic parametrization scheme or extensions." }, { "code": null, "e": 66455, "s": 66350, "text": "pytest_generate_tests enables implementing your own custom dynamic parametrization scheme or extensions." }, { "code": null, "e": 66642, "s": 66455, "text": "A third party module 'nose-parameterized' allows Parameterized testing with any Python test framework. It can be downloaded from this link − https://github.com/wolever/nose-parameterized" }, { "code": null, "e": 66649, "s": 66642, "text": " Print" }, { "code": null, "e": 66660, "s": 66649, "text": " Add Notes" } ]
Rexx - RANDOM
This method returns a random generated number. RANDOM() None None This method returns a random generated number. /* Main program */ say RANDOM() When we run the above program, we will get the following result. 971 Print Add Notes Bookmark this page
[ { "code": null, "e": 2386, "s": 2339, "text": "This method returns a random generated number." }, { "code": null, "e": 2397, "s": 2386, "text": "RANDOM() \n" }, { "code": null, "e": 2402, "s": 2397, "text": "None" }, { "code": null, "e": 2407, "s": 2402, "text": "None" }, { "code": null, "e": 2454, "s": 2407, "text": "This method returns a random generated number." }, { "code": null, "e": 2488, "s": 2454, "text": "/* Main program */ \nsay RANDOM() " }, { "code": null, "e": 2553, "s": 2488, "text": "When we run the above program, we will get the following result." }, { "code": null, "e": 2558, "s": 2553, "text": "971\n" }, { "code": null, "e": 2565, "s": 2558, "text": " Print" }, { "code": null, "e": 2576, "s": 2565, "text": " Add Notes" } ]
How to find and display the Multiplication Table in C#?
To display multiplication table, you need to set the numbers and format the output property. Let’s say you want to find the table of 4 from 1 to 10. For that, set a while loop first till 10. while (a <= 10) { } Now format the output to get the result as shown below. Here, n is 4 i.e. table of 4. Console.WriteLine(" {0} x {1} = {2} \n ", n, a, n * a); The above will give a formatted output − 4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 . . . The following is the complete example − using System; public class Demo { public static void Main() { int n = 4, a = 1; while (a <= 10) { Console.WriteLine(" {0} x {1} = {2} \n ", n, a, n * a); a++; } } }
[ { "code": null, "e": 1253, "s": 1062, "text": "To display multiplication table, you need to set the numbers and format the output property. Let’s say you want to find the table of 4 from 1 to 10. For that, set a while loop first till 10." }, { "code": null, "e": 1273, "s": 1253, "text": "while (a <= 10) {\n}" }, { "code": null, "e": 1359, "s": 1273, "text": "Now format the output to get the result as shown below. Here, n is 4 i.e. table of 4." }, { "code": null, "e": 1415, "s": 1359, "text": "Console.WriteLine(\" {0} x {1} = {2} \\n \", n, a, n * a);" }, { "code": null, "e": 1456, "s": 1415, "text": "The above will give a formatted output −" }, { "code": null, "e": 1493, "s": 1456, "text": "4 x 1 = 4\n4 x 2 = 8\n4 x 3 = 12\n.\n.\n." }, { "code": null, "e": 1533, "s": 1493, "text": "The following is the complete example −" }, { "code": null, "e": 1742, "s": 1533, "text": "using System;\npublic class Demo {\n\n public static void Main() {\n int n = 4, a = 1;\n\n while (a <= 10) {\n Console.WriteLine(\" {0} x {1} = {2} \\n \", n, a, n * a);\n a++;\n }\n }\n}" } ]
IPython - Installation
IPython is included by default in Anaconda distribution of Python. It can be downloaded from Anaconda’s download page www.anaconda.com/download/ Binaries for all major OS (Windows, MacOS and Linux) and architecture (32 bit and 64 bit) are available on this link. To install IPython separately in standard Python installation, you can use pip command as shown below − pip3 install ipython IPython internally uses following packages − colorama Cross-platform API for printing colored terminal text from Python jedi An autocompletion tool for Python pickleshare Small ‘shelve’ like datastore with concurrency support prompt_toolkit Library for building powerful interactive command lines in Python pygments Syntax highlighting package written in Python simplegeneric Simple generic functions traitlets Configuration system for Python applications. In general, all dependencies get installed automatically. Else, you can install them individually using pip. 22 Lectures 49 mins Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2923, "s": 2660, "text": "IPython is included by default in Anaconda distribution of Python. It can be downloaded from Anaconda’s download page www.anaconda.com/download/ Binaries for all major OS (Windows, MacOS and Linux) and architecture (32 bit and 64 bit) are available on this link." }, { "code": null, "e": 3027, "s": 2923, "text": "To install IPython separately in standard Python installation, you can use pip command as shown below −" }, { "code": null, "e": 3049, "s": 3027, "text": "pip3 install ipython\n" }, { "code": null, "e": 3094, "s": 3049, "text": "IPython internally uses following packages −" }, { "code": null, "e": 3103, "s": 3094, "text": "colorama" }, { "code": null, "e": 3169, "s": 3103, "text": "Cross-platform API for printing colored terminal text from Python" }, { "code": null, "e": 3174, "s": 3169, "text": "jedi" }, { "code": null, "e": 3208, "s": 3174, "text": "An autocompletion tool for Python" }, { "code": null, "e": 3220, "s": 3208, "text": "pickleshare" }, { "code": null, "e": 3275, "s": 3220, "text": "Small ‘shelve’ like datastore with concurrency support" }, { "code": null, "e": 3290, "s": 3275, "text": "prompt_toolkit" }, { "code": null, "e": 3356, "s": 3290, "text": "Library for building powerful interactive command lines in Python" }, { "code": null, "e": 3365, "s": 3356, "text": "pygments" }, { "code": null, "e": 3411, "s": 3365, "text": "Syntax highlighting package written in Python" }, { "code": null, "e": 3425, "s": 3411, "text": "simplegeneric" }, { "code": null, "e": 3450, "s": 3425, "text": "Simple generic functions" }, { "code": null, "e": 3460, "s": 3450, "text": "traitlets" }, { "code": null, "e": 3506, "s": 3460, "text": "Configuration system for Python applications." }, { "code": null, "e": 3615, "s": 3506, "text": "In general, all dependencies get installed automatically. Else, you can install them individually using pip." }, { "code": null, "e": 3647, "s": 3615, "text": "\n 22 Lectures \n 49 mins\n" }, { "code": null, "e": 3665, "s": 3647, "text": " Bigdata Engineer" }, { "code": null, "e": 3672, "s": 3665, "text": " Print" }, { "code": null, "e": 3683, "s": 3672, "text": " Add Notes" } ]
C++ String Library - find_last_not_of
It searches the string for the first character that does not match any of the characters specified in its arguments. Following is the declaration for std::string::find_last_not_of. size_t find_last_not_of (const string& str, size_t pos = npos) const; size_t find_last_not_of (const string& str, size_t pos = npos) const noexcept; size_t find_last_not_of (const string& str, size_t pos = npos) const noexcept; str − It is a string object. str − It is a string object. len − It is used to copy the characters. len − It is used to copy the characters. pos − Position of the first character to be copied. pos − Position of the first character to be copied. none if an exception is thrown, there are no changes in the string. In below example for std::string::find_last_not_of. #include <iostream> #include <string> #include <cstddef> int main () { std::string str ("It erases trailing white-spaces \n"); std::string whitespaces (" \t\f\v\n\r"); std::size_t found = str.find_last_not_of(whitespaces); if (found!=std::string::npos) str.erase(found+1); else str.clear(); std::cout << '[' << str << "]\n"; return 0; } The sample output should be like this − [It erases trailing white-spaces] Print Add Notes Bookmark this page
[ { "code": null, "e": 2720, "s": 2603, "text": "It searches the string for the first character that does not match any of the characters specified in its arguments." }, { "code": null, "e": 2784, "s": 2720, "text": "Following is the declaration for std::string::find_last_not_of." }, { "code": null, "e": 2854, "s": 2784, "text": "size_t find_last_not_of (const string& str, size_t pos = npos) const;" }, { "code": null, "e": 2933, "s": 2854, "text": "size_t find_last_not_of (const string& str, size_t pos = npos) const noexcept;" }, { "code": null, "e": 3012, "s": 2933, "text": "size_t find_last_not_of (const string& str, size_t pos = npos) const noexcept;" }, { "code": null, "e": 3041, "s": 3012, "text": "str − It is a string object." }, { "code": null, "e": 3070, "s": 3041, "text": "str − It is a string object." }, { "code": null, "e": 3111, "s": 3070, "text": "len − It is used to copy the characters." }, { "code": null, "e": 3152, "s": 3111, "text": "len − It is used to copy the characters." }, { "code": null, "e": 3204, "s": 3152, "text": "pos − Position of the first character to be copied." }, { "code": null, "e": 3256, "s": 3204, "text": "pos − Position of the first character to be copied." }, { "code": null, "e": 3261, "s": 3256, "text": "none" }, { "code": null, "e": 3324, "s": 3261, "text": "if an exception is thrown, there are no changes in the string." }, { "code": null, "e": 3376, "s": 3324, "text": "In below example for std::string::find_last_not_of." }, { "code": null, "e": 3752, "s": 3376, "text": "#include <iostream>\n#include <string>\n#include <cstddef>\n\nint main () {\n std::string str (\"It erases trailing white-spaces \\n\");\n std::string whitespaces (\" \\t\\f\\v\\n\\r\");\n\n std::size_t found = str.find_last_not_of(whitespaces);\n if (found!=std::string::npos)\n str.erase(found+1);\n else\n str.clear();\n\n std::cout << '[' << str << \"]\\n\";\n\n return 0;\n}" }, { "code": null, "e": 3792, "s": 3752, "text": "The sample output should be like this −" }, { "code": null, "e": 3827, "s": 3792, "text": "[It erases trailing white-spaces]\n" }, { "code": null, "e": 3834, "s": 3827, "text": " Print" }, { "code": null, "e": 3845, "s": 3834, "text": " Add Notes" } ]
How to convert JSON results into a date using JavaScript ? - GeeksforGeeks
31 Oct, 2019 The task is to convert a JSON result to JavaScript Date with the help of JavaScript. There are few two methods which are discussed below: Approach 1: Use substr() method to get the integer part of string. Use the parseInt() method followed by Date() to get the JavaScript date. Example: This example implements the above approach. <!DOCTYPE HTML> <html> <head> <title> How to convert JSON results into a date using JavaScript ? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var jsonDate = '/Date(1559083200000)/'; el_up.innerHTML = "Click on the button to convert" + " JSON result to JavaScript Date." + "<br>JSON Date - " + jsonDate; function gfg_Run() { var date = new Date(parseInt(jsonDate.substr(6))); el_down.innerHTML = date; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Use the regExp to get the integer part of string. Use the Date() method to get the JavaScript date. Example: This example implements the above approach. <!DOCTYPE HTML> <html> <head> <title> How to convert JSON results into a date using JavaScript ? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var jsonDate = '/Date(1559083200000)/'; el_up.innerHTML = "Click on the button to convert" + " JSON result to JavaScript Date." + "<br>JSON Date - " + jsonDate; function gfg_Run() { var date = new Date(jsonDate.match(/\d+/)[0] * 1); el_down.innerHTML = date; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JSON JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 37970, "s": 37942, "text": "\n31 Oct, 2019" }, { "code": null, "e": 38108, "s": 37970, "text": "The task is to convert a JSON result to JavaScript Date with the help of JavaScript. There are few two methods which are discussed below:" }, { "code": null, "e": 38120, "s": 38108, "text": "Approach 1:" }, { "code": null, "e": 38175, "s": 38120, "text": "Use substr() method to get the integer part of string." }, { "code": null, "e": 38248, "s": 38175, "text": "Use the parseInt() method followed by Date() to get the JavaScript date." }, { "code": null, "e": 38301, "s": 38248, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to convert JSON results into a date using JavaScript ? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var jsonDate = '/Date(1559083200000)/'; el_up.innerHTML = \"Click on the button to convert\" + \" JSON result to JavaScript Date.\" + \"<br>JSON Date - \" + jsonDate; function gfg_Run() { var date = new Date(parseInt(jsonDate.substr(6))); el_down.innerHTML = date; } </script> </body> </html>", "e": 39349, "s": 38301, "text": null }, { "code": null, "e": 39357, "s": 39349, "text": "Output:" }, { "code": null, "e": 39388, "s": 39357, "text": "Before clicking on the button:" }, { "code": null, "e": 39418, "s": 39388, "text": "After clicking on the button:" }, { "code": null, "e": 39430, "s": 39418, "text": "Approach 2:" }, { "code": null, "e": 39480, "s": 39430, "text": "Use the regExp to get the integer part of string." }, { "code": null, "e": 39530, "s": 39480, "text": "Use the Date() method to get the JavaScript date." }, { "code": null, "e": 39583, "s": 39530, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to convert JSON results into a date using JavaScript ? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var jsonDate = '/Date(1559083200000)/'; el_up.innerHTML = \"Click on the button to convert\" + \" JSON result to JavaScript Date.\" + \"<br>JSON Date - \" + jsonDate; function gfg_Run() { var date = new Date(jsonDate.match(/\\d+/)[0] * 1); el_down.innerHTML = date; } </script> </body> </html>", "e": 40631, "s": 39583, "text": null }, { "code": null, "e": 40639, "s": 40631, "text": "Output:" }, { "code": null, "e": 40670, "s": 40639, "text": "Before clicking on the button:" }, { "code": null, "e": 40700, "s": 40670, "text": "After clicking on the button:" }, { "code": null, "e": 40716, "s": 40700, "text": "JavaScript-Misc" }, { "code": null, "e": 40721, "s": 40716, "text": "JSON" }, { "code": null, "e": 40732, "s": 40721, "text": "JavaScript" }, { "code": null, "e": 40749, "s": 40732, "text": "Web Technologies" }, { "code": null, "e": 40776, "s": 40749, "text": "Web technologies Questions" }, { "code": null, "e": 40874, "s": 40776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40919, "s": 40874, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40980, "s": 40919, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 41049, "s": 40980, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 41121, "s": 41049, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 41173, "s": 41121, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 41215, "s": 41173, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 41248, "s": 41215, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 41291, "s": 41248, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 41353, "s": 41291, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Image Processing — OpenCV Vs PIL. Utilize the Python Libraries to Extract... | by Suraj Gurav | Towards Data Science
The work of a Data Analyst is not limited to work only on readily available data, rather sometimes the data need to be mined from the images also. This story is all about different types of image feature extraction using Python. Additionally, here you will find a classic comparison of the speed of two image processing libraries — OpenCV and PIL ____ OpenCV is 1.4 Times faster than PIL ____ 📌 Want to follow along? here is my Jupyter-Notebook.📌 More resources are always mentioned with 💡 In my recent project, I need to process 10000+ images per day and extract the data from them. And only Python can help me with this batch processing. I usually do the below processes on image:1. Extract the aspect ratio of the image.2. Crop the image.3. Change the image to grayscaled one.4. Image Rotation.However, my work doesn’t stop here. I do much more ad-hoc analysis. In my project, a lot of information is also hidden in the image name. And the string manipulation methods discussed here are quite handy in such tasks. towardsdatascience.com Image is simply a matrix of pixels and each pixel is the single, square-shaped point of colored light. This can be explained quickly with a grayscaled image. grayscaled image is the image where each pixel represents different shades of a gray color. In the picture above, the original image on the left side is actually the distribution of different shades of a gray color. On the right side, in the array of pixel gray values, the value 0 represents the black color and the value 255 represents the white color. All the values between 0 and 255 represent different shades of a gray color. Further information about this can be found here. A random google search 🔍 for image processing in Python points towards these frequently used image processing libraries. OpenCV is written in C and C++ whereas PIL is written using Python and C, hence just from this information, OpenCV seems faster. While dealing with 1000s of images for data extraction, the processing speed 🚀 matters.Here is a quick comparison of these two libraries. I mostly use OpenCV to complete my tasks as I find it 1.4 times quicker than PIL. First, let me show you step by step, how the image can be processed using both — OpenCV and PIL. First of all, install the OpenCV Python package and import the package into Jupyter-Notebook or Python IDE. pip install opencv-pythonimport cv2 Installation needed only for the 1st time usage. img = cv2.imread(path_to_the_image)Use this method from the OpenCV package to read the image into a variable img. As I mentioned earlier, OpenCV reads the image in BGR format by default. What are BGR and RGB formats?Both stand for the same colors (R) Red, (G) Green, (B) Blue but the order of arranging these colors areas is different. In BGR, the red color channel is considered as least important and in RGB, the blue color channel is the least important. For the sake of this article, I will convert it to RGB format using the cvtColor method. Let’s crop the image keeping the aspect ratio the same. So the area with the same aspect ratio will be cropped from the center of the image. The aspect ratio of an image is the ratio of its width to its height. It is commonly expressed as two numbers separated by a colon, as in width:height. for example, 16:9. In OpenCV, the image is a NumPy array and crops the image in the same way as NumPy array slicing. That’s why it is 8210X faster than PIL. Image rotation is quite straightforward here. The method rotate() in OpenCV allows image rotation in the multiples of 90°. 💡 More info about the method rotate() can be found here. “Grayscale” image is an image that is composed of different shades of gray only, varying from black to white. An 8-bit image has 256 different shades of Gray color. Meaning, each pixel of the image, takes a value between 0 and 255. Again using the method cvtColor() to convert the rotated image to the grayscale. 💡 All the color conversion codes can be found here. Pillow is the currently used library, which is derived from PIL.For the first-time usage, start with package installation. And then import the package into Jupyter-Notebook or Python IDE. pip install Pillowfrom PIL import Image, ImageEnhance Imported Image module has the method open() which comes in handy while reading the image in PIL. Just like OpenCV, the image name with the extension or the entire path can be passed to this method. The same class Image has the method crop() to crop the image. The image cropping with PIL is slightly different than OpenCV. Image.crop() takes a tuple as input. This tuple includes the coordinates for the upper left and the lower right corner of the area to be cropped. Image class includes also the method rotate(). And unlike OpenCV, only the anticlockwise rotation angle as an integer can be passed to this method. Just like the other tasks in PIL, the image format conversion is also straightforward. The method convert() returns the converted image. Well, the programmatical way of image data mining is commonly used for batch image processing. And there comes the game of speeds ⏳. I downloaded 880 images 🎁 from google and processed each image 10 times to have enough load on the program, to find out the time required for the image processing in OpenCV and in PIL. As expected, the time taken by OpenCV was less as compared to PIL i.e. OpenCV was faster than PIL. 💡 Theoretical explanation about how image processing is done in OpenCV can be found here. The beauty of OpenCV is, you can see numerous examples on its website in Python, C++, and Java. Similarly, more info about PIL can be gathered here. 💡 This was just an overview of the two most frequently used Python packages for image processing and how they work differently to return the same results. I hope you enjoyed and learned something from this read. Typically for my work, I found OpenCV more reliable and faster, however, the inverse is also possible depending on different image processes. As I always say, I am open to constructive feedback and knowledge sharing through LinkedIn. 📚 Have a look at my other articles about Data Analytics here. Visualize SQLite Data with Power BILabel Encoder and OneHot Encoder in PythonSQL Database with PythonWeb Scraping — Make your Own DatasetHypothesis Testing & p-ValueJoin the Tables Visualize SQLite Data with Power BI Label Encoder and OneHot Encoder in Python SQL Database with Python Web Scraping — Make your Own Dataset Hypothesis Testing & p-Value Join the Tables Become a Medium member today & get ⚡ unlimited ⚡ access to all the Medium stories. Sign up here and Join my email subscriptions When you sign-up here and choose to become a paid medium member, I will get a portion of your membership fee as a reward.
[ { "code": null, "e": 319, "s": 172, "text": "The work of a Data Analyst is not limited to work only on readily available data, rather sometimes the data need to be mined from the images also." }, { "code": null, "e": 519, "s": 319, "text": "This story is all about different types of image feature extraction using Python. Additionally, here you will find a classic comparison of the speed of two image processing libraries — OpenCV and PIL" }, { "code": null, "e": 565, "s": 519, "text": "____ OpenCV is 1.4 Times faster than PIL ____" }, { "code": null, "e": 662, "s": 565, "text": "📌 Want to follow along? here is my Jupyter-Notebook.📌 More resources are always mentioned with 💡" }, { "code": null, "e": 1037, "s": 662, "text": "In my recent project, I need to process 10000+ images per day and extract the data from them. And only Python can help me with this batch processing. I usually do the below processes on image:1. Extract the aspect ratio of the image.2. Crop the image.3. Change the image to grayscaled one.4. Image Rotation.However, my work doesn’t stop here. I do much more ad-hoc analysis." }, { "code": null, "e": 1189, "s": 1037, "text": "In my project, a lot of information is also hidden in the image name. And the string manipulation methods discussed here are quite handy in such tasks." }, { "code": null, "e": 1212, "s": 1189, "text": "towardsdatascience.com" }, { "code": null, "e": 1462, "s": 1212, "text": "Image is simply a matrix of pixels and each pixel is the single, square-shaped point of colored light. This can be explained quickly with a grayscaled image. grayscaled image is the image where each pixel represents different shades of a gray color." }, { "code": null, "e": 1852, "s": 1462, "text": "In the picture above, the original image on the left side is actually the distribution of different shades of a gray color. On the right side, in the array of pixel gray values, the value 0 represents the black color and the value 255 represents the white color. All the values between 0 and 255 represent different shades of a gray color. Further information about this can be found here." }, { "code": null, "e": 1973, "s": 1852, "text": "A random google search 🔍 for image processing in Python points towards these frequently used image processing libraries." }, { "code": null, "e": 2240, "s": 1973, "text": "OpenCV is written in C and C++ whereas PIL is written using Python and C, hence just from this information, OpenCV seems faster. While dealing with 1000s of images for data extraction, the processing speed 🚀 matters.Here is a quick comparison of these two libraries." }, { "code": null, "e": 2419, "s": 2240, "text": "I mostly use OpenCV to complete my tasks as I find it 1.4 times quicker than PIL. First, let me show you step by step, how the image can be processed using both — OpenCV and PIL." }, { "code": null, "e": 2527, "s": 2419, "text": "First of all, install the OpenCV Python package and import the package into Jupyter-Notebook or Python IDE." }, { "code": null, "e": 2563, "s": 2527, "text": "pip install opencv-pythonimport cv2" }, { "code": null, "e": 2612, "s": 2563, "text": "Installation needed only for the 1st time usage." }, { "code": null, "e": 2799, "s": 2612, "text": "img = cv2.imread(path_to_the_image)Use this method from the OpenCV package to read the image into a variable img. As I mentioned earlier, OpenCV reads the image in BGR format by default." }, { "code": null, "e": 3070, "s": 2799, "text": "What are BGR and RGB formats?Both stand for the same colors (R) Red, (G) Green, (B) Blue but the order of arranging these colors areas is different. In BGR, the red color channel is considered as least important and in RGB, the blue color channel is the least important." }, { "code": null, "e": 3159, "s": 3070, "text": "For the sake of this article, I will convert it to RGB format using the cvtColor method." }, { "code": null, "e": 3300, "s": 3159, "text": "Let’s crop the image keeping the aspect ratio the same. So the area with the same aspect ratio will be cropped from the center of the image." }, { "code": null, "e": 3471, "s": 3300, "text": "The aspect ratio of an image is the ratio of its width to its height. It is commonly expressed as two numbers separated by a colon, as in width:height. for example, 16:9." }, { "code": null, "e": 3609, "s": 3471, "text": "In OpenCV, the image is a NumPy array and crops the image in the same way as NumPy array slicing. That’s why it is 8210X faster than PIL." }, { "code": null, "e": 3732, "s": 3609, "text": "Image rotation is quite straightforward here. The method rotate() in OpenCV allows image rotation in the multiples of 90°." }, { "code": null, "e": 3789, "s": 3732, "text": "💡 More info about the method rotate() can be found here." }, { "code": null, "e": 4102, "s": 3789, "text": "“Grayscale” image is an image that is composed of different shades of gray only, varying from black to white. An 8-bit image has 256 different shades of Gray color. Meaning, each pixel of the image, takes a value between 0 and 255. Again using the method cvtColor() to convert the rotated image to the grayscale." }, { "code": null, "e": 4154, "s": 4102, "text": "💡 All the color conversion codes can be found here." }, { "code": null, "e": 4342, "s": 4154, "text": "Pillow is the currently used library, which is derived from PIL.For the first-time usage, start with package installation. And then import the package into Jupyter-Notebook or Python IDE." }, { "code": null, "e": 4396, "s": 4342, "text": "pip install Pillowfrom PIL import Image, ImageEnhance" }, { "code": null, "e": 4594, "s": 4396, "text": "Imported Image module has the method open() which comes in handy while reading the image in PIL. Just like OpenCV, the image name with the extension or the entire path can be passed to this method." }, { "code": null, "e": 4719, "s": 4594, "text": "The same class Image has the method crop() to crop the image. The image cropping with PIL is slightly different than OpenCV." }, { "code": null, "e": 4865, "s": 4719, "text": "Image.crop() takes a tuple as input. This tuple includes the coordinates for the upper left and the lower right corner of the area to be cropped." }, { "code": null, "e": 5013, "s": 4865, "text": "Image class includes also the method rotate(). And unlike OpenCV, only the anticlockwise rotation angle as an integer can be passed to this method." }, { "code": null, "e": 5150, "s": 5013, "text": "Just like the other tasks in PIL, the image format conversion is also straightforward. The method convert() returns the converted image." }, { "code": null, "e": 5283, "s": 5150, "text": "Well, the programmatical way of image data mining is commonly used for batch image processing. And there comes the game of speeds ⏳." }, { "code": null, "e": 5468, "s": 5283, "text": "I downloaded 880 images 🎁 from google and processed each image 10 times to have enough load on the program, to find out the time required for the image processing in OpenCV and in PIL." }, { "code": null, "e": 5567, "s": 5468, "text": "As expected, the time taken by OpenCV was less as compared to PIL i.e. OpenCV was faster than PIL." }, { "code": null, "e": 5753, "s": 5567, "text": "💡 Theoretical explanation about how image processing is done in OpenCV can be found here. The beauty of OpenCV is, you can see numerous examples on its website in Python, C++, and Java." }, { "code": null, "e": 5808, "s": 5753, "text": "Similarly, more info about PIL can be gathered here. 💡" }, { "code": null, "e": 6018, "s": 5808, "text": "This was just an overview of the two most frequently used Python packages for image processing and how they work differently to return the same results. I hope you enjoyed and learned something from this read." }, { "code": null, "e": 6160, "s": 6018, "text": "Typically for my work, I found OpenCV more reliable and faster, however, the inverse is also possible depending on different image processes." }, { "code": null, "e": 6252, "s": 6160, "text": "As I always say, I am open to constructive feedback and knowledge sharing through LinkedIn." }, { "code": null, "e": 6314, "s": 6252, "text": "📚 Have a look at my other articles about Data Analytics here." }, { "code": null, "e": 6495, "s": 6314, "text": "Visualize SQLite Data with Power BILabel Encoder and OneHot Encoder in PythonSQL Database with PythonWeb Scraping — Make your Own DatasetHypothesis Testing & p-ValueJoin the Tables" }, { "code": null, "e": 6531, "s": 6495, "text": "Visualize SQLite Data with Power BI" }, { "code": null, "e": 6574, "s": 6531, "text": "Label Encoder and OneHot Encoder in Python" }, { "code": null, "e": 6599, "s": 6574, "text": "SQL Database with Python" }, { "code": null, "e": 6636, "s": 6599, "text": "Web Scraping — Make your Own Dataset" }, { "code": null, "e": 6665, "s": 6636, "text": "Hypothesis Testing & p-Value" }, { "code": null, "e": 6681, "s": 6665, "text": "Join the Tables" }, { "code": null, "e": 6764, "s": 6681, "text": "Become a Medium member today & get ⚡ unlimited ⚡ access to all the Medium stories." }, { "code": null, "e": 6809, "s": 6764, "text": "Sign up here and Join my email subscriptions" } ]
Processing XML in Python — ElementTree | by Deepesh Nair | Towards Data Science
Learn how you can parse, explore, modify and populate XML files with the Python ElementTree package, for loops and XPath expressions. As a data scientist, you’ll find that understanding XML is powerful for both web-scraping and general practice in parsing a structured document Extensible Markup Language (XML) is a markup language which encodes documents by defining a set of rules in both machine-readable and human-readable format. Extended from SGML (Standard Generalized Markup Language), it lets us describe the structure of the document. In XML, we can define custom tags. We can also use XML as a standard format to exchange information. XML documents have sections, called elements, defined by a beginning and an ending tag. A tag is a markup construct that begins with < and ends with >. The characters between the start-tag and end-tag, if there are any, are the element's content. Elements can contain markup, including other elements, which are called "child elements". The largest, top-level element is called the root, which contains all other elements. Attributes are name–value pair that exist within a start-tag or empty-element tag. An XML attribute can only have a single value and each attribute can appear at most once on each element. Here’s a snapshot of movies.xml that we will be using for this tutorial: <?xml version="1.0"?><collection> <genre category="Action"> <decade years="1980s"> <movie favorite="True" title="Indiana Jones: The raiders of the lost Ark"> <format multiple="No">DVD</format> <year>1981</year> <rating>PG</rating> <description> 'Archaeologist and adventurer Indiana Jones is hired by the U.S. government to find the Ark of the Covenant before the Nazis.' </description> </movie> <movie favorite="True" title="THE KARATE KID"> <format multiple="Yes">DVD,Online</format> <year>1984</year> <rating>PG</rating> <description>None provided.</description> </movie> <movie favorite="False" title="Back 2 the Future"> <format multiple="False">Blu-ray</format> <year>1985</year> <rating>PG</rating> <description>Marty McFly</description> </movie> </decade> <decade years="1990s"> <movie favorite="False" title="X-Men"> <format multiple="Yes">dvd, digital</format> <year>2000</year> <rating>PG-13</rating> <description>Two mutants come to a private academy for their kind whose resident superhero team must oppose a terrorist organization with similar powers.</description> </movie> <movie favorite="True" title="Batman Returns"> <format multiple="No">VHS</format> <year>1992</year> <rating>PG13</rating> <description>NA.</description> </movie> <movie favorite="False" title="Reservoir Dogs"> <format multiple="No">Online</format> <year>1992</year> <rating>R</rating> <description>WhAtEvER I Want!!!?!</description> </movie> </decade> </genre> <genre category="Thriller"> <decade years="1970s"> <movie favorite="False" title="ALIEN"> <format multiple="Yes">DVD</format> <year>1979</year> <rating>R</rating> <description>"""""""""</description> </movie> </decade> <decade years="1980s"> <movie favorite="True" title="Ferris Bueller's Day Off"> <format multiple="No">DVD</format> <year>1986</year> <rating>PG13</rating> <description>Funny movie on funny guy </description> </movie> <movie favorite="FALSE" title="American Psycho"> <format multiple="No">blue-ray</format> <year>2000</year> <rating>Unrated</rating> <description>psychopathic Bateman</description> </movie> </decade> </genre> The XML tree structure makes navigation, modification, and removal relatively simple programmatically. Python has a built in library, ElementTree, that has functions to read and manipulate XMLs (and other similarly structured files). First, import ElementTree. It's a common practice to use the alias of ET: import xml.etree.ElementTree as ET In the XML file provided, there is a basic collection of movies described. The only problem is the data is a mess! There have been a lot of different curators of this collection and everyone has their own way of entering data into the file. The main goal in this tutorial will be to read and understand the file with Python — then fix the problems. First you need to read in the file with ElementTree. tree = ET.parse('movies.xml')root = tree.getroot() Now that you have initialized the tree, you should look at the XML and print out values in order to understand how the tree is structured. root.tag'collection' At the top level, you see that this XML is rooted in the collection tag. root.attrib{} You can easily iterate over subelements (commonly called “children”) in the root by using a simple “for” loop. for child in root: print(child.tag, child.attrib)genre {'category': 'Action'}genre {'category': 'Thriller'}genre {'category': 'Comedy'} Now you know that the children of the root collection are all genre. To designate the genre, the XML uses the attribute category. There are Action, Thriller, and Comedy movies according the genre element. Typically it is helpful to know all the elements in the entire tree. One useful function for doing that is root.iter(). [elem.tag for elem in root.iter()]['collection', 'genre', 'decade', 'movie', 'format', 'year', 'rating', 'description', 'movie', . . . . 'movie', 'format', 'year', 'rating', 'description'] There is a helpful way to see the whole document. If you pass the root into the .tostring() method, you can return the whole document. Within ElementTree, this method takes a slightly strange form. Since ElementTree is a powerful library that can interpret more than just XML, you must specify both the encoding and decoding of the document you are displaying as the string. You can expand the use of the iter() function to help with finding particular elements of interest. root.iter() will list all subelements under the root that match the element specified. Here, you will list all attributes of the movie element in the tree: for movie in root.iter('movie'): print(movie.attrib){'favorite': 'True', 'title': 'Indiana Jones: The raiders of the lost Ark'}{'favorite': 'True', 'title': 'THE KARATE KID'}{'favorite': 'False', 'title': 'Back 2 the Future'}{'favorite': 'False', 'title': 'X-Men'}{'favorite': 'True', 'title': 'Batman Returns'}{'favorite': 'False', 'title': 'Reservoir Dogs'}{'favorite': 'False', 'title': 'ALIEN'}{'favorite': 'True', 'title': "Ferris Bueller's Day Off"}{'favorite': 'FALSE', 'title': 'American Psycho'}{'favorite': 'False', 'title': 'Batman: The Movie'}{'favorite': 'True', 'title': 'Easy A'}{'favorite': 'True', 'title': 'Dinner for SCHMUCKS'}{'favorite': 'False', 'title': 'Ghostbusters'}{'favorite': 'True', 'title': 'Robin Hood: Prince of Thieves'} Many times elements will not have attributes, they will only have text content. Using the attribute .text, you can print out this content. Now, print out all the descriptions of the movies. for description in root.iter('description'): print(description.text)'Archaeologist and adventurer Indiana Jones is hired by the U.S. government to find the Ark of the Covenant before the Nazis.'None provided.Marty McFlyTwo mutants come to a private academy for their kind whose resident superhero team must oppose a terrorist organization with similar powers.NA.WhAtEvER I Want!!!?!"""""""""Funny movie about a funny guypsychopathic BatemanWhat a joke!Emma Stone = Hester PrynneTim (Rudd) is a rising executive who “succeeds” in finding the perfect guest, IRS employee Barry (Carell), for his boss’ monthly event, a so-called “dinner for idiots,” which offers certain advantages to the exec who shows up with the biggest buffoon.Who ya gonna call?Robin Hood slaying Printing out the XML is helpful, but XPath is a query language used to search through an XML quickly and easily. However, Understanding XPath is critically important to scanning and populating XMLs. ElementTree has a .findall() function that will traverse the immediate children of the referenced element. Here, you will search the tree for movies that came out in 1992: for movie in root.findall("./genre/decade/movie/[year='1992']"): print(movie.attrib){'favorite': 'True', 'title': 'Batman Returns'}{'favorite': 'False', 'title': 'Reservoir Dogs'} The function .findall() always begins at the element specified. This type of function is extremely powerful for a "find and replace". You can even search on attributes! Now, print out only the movies that are available in multiple formats (an attribute). for movie in root.findall("./genre/decade/movie/format/[@multiple='Yes']"): print(movie.attrib){'multiple': 'Yes'}{'multiple': 'Yes'}{'multiple': 'Yes'}{'multiple': 'Yes'}{'multiple': 'Yes'} Brainstorm why, in this case, the print statement returns the “Yes” values of multiple. Think about how the "for" loop is defined. Tip: use '...' inside of XPath to return the parent element of the current element. for movie in root.findall("./genre/decade/movie/format[@multiple='Yes']..."): print(movie.attrib){'favorite': 'True', 'title': 'THE KARATE KID'}{'favorite': 'False', 'title': 'X-Men'}{'favorite': 'False', 'title': 'ALIEN'}{'favorite': 'False', 'title': 'Batman: The Movie'}{'favorite': 'True', 'title': 'Dinner for SCHMUCKS'} Earlier, the movie titles were an absolute mess. Now, print them out again: for movie in root.iter('movie'): print(movie.attrib){'favorite': 'True', 'title': 'Indiana Jones: The raiders of the lost Ark'}{'favorite': 'True', 'title': 'THE KARATE KID'}{'favorite': 'False', 'title': 'Back 2 the Future'}{'favorite': 'False', 'title': 'X-Men'}{'favorite': 'True', 'title': 'Batman Returns'}{'favorite': 'False', 'title': 'Reservoir Dogs'}{'favorite': 'False', 'title': 'ALIEN'}{'favorite': 'True', 'title': "Ferris Bueller's Day Off"}{'favorite': 'FALSE', 'title': 'American Psycho'}{'favorite': 'False', 'title': 'Batman: The Movie'}{'favorite': 'True', 'title': 'Easy A'}{'favorite': 'True', 'title': 'Dinner for SCHMUCKS'}{'favorite': 'False', 'title': 'Ghostbusters'}{'favorite': 'True', 'title': 'Robin Hood: Prince of Thieves'} Fix the ‘2’ in Back 2 the Future. That should be a find and replace problem. Write code to find the title ‘Back 2 the Future’ and save it as a variable: b2tf = root.find("./genre/decade/movie[@title='Back 2 the Future']")print(b2tf)<Element 'movie' at 0x10ce00ef8> Notice that using the .find() method returns an element of the tree. Much of the time, it is more useful to edit the content within an element. Modify the title attribute of the Back 2 the Future element variable to read "Back to the Future". Then, print out the attributes of your variable to see your change. You can easily do this by accessing the attribute of an element and then assigning a new value to it: b2tf.attrib["title"] = "Back to the Future"print(b2tf.attrib){'favorite': 'False', 'title': 'Back to the Future'} Write out your changes back to the XML so they are permanently fixed in the document. Print out your movie attributes again to make sure your changes worked. Use the .write() method to do this: tree.write("movies.xml")tree = ET.parse('movies.xml')root = tree.getroot()for movie in root.iter('movie'): print(movie.attrib){'favorite': 'True', 'title': 'Indiana Jones: The raiders of the lost Ark'}{'favorite': 'True', 'title': 'THE KARATE KID'}{'favorite': 'False', 'title': 'Back to the Future'}{'favorite': 'False', 'title': 'X-Men'}{'favorite': 'True', 'title': 'Batman Returns'}{'favorite': 'False', 'title': 'Reservoir Dogs'}{'favorite': 'False', 'title': 'ALIEN'}{'favorite': 'True', 'title': "Ferris Bueller's Day Off"}{'favorite': 'FALSE', 'title': 'American Psycho'}{'favorite': 'False', 'title': 'Batman: The Movie'}{'favorite': 'True', 'title': 'Easy A'}{'favorite': 'True', 'title': 'Dinner for SCHMUCKS'}{'favorite': 'False', 'title': 'Ghostbusters'}{'favorite': 'True', 'title': 'Robin Hood: Prince of Thieves'} The multiple attribute is incorrect in some places. Use ElementTree to fix the designator based on how many formats the movie comes in. First, print the formatattribute and text to see which parts need to be fixed. for form in root.findall("./genre/decade/movie/format"): print(form.attrib, form.text){'multiple': 'No'} DVD{'multiple': 'Yes'} DVD,Online{'multiple': 'False'} Blu-ray{'multiple': 'Yes'} dvd, digital{'multiple': 'No'} VHS{'multiple': 'No'} Online{'multiple': 'Yes'} DVD{'multiple': 'No'} DVD{'multiple': 'No'} blue-ray{'multiple': 'Yes'} DVD,VHS{'multiple': 'No'} DVD{'multiple': 'Yes'} DVD,digital,Netflix{'multiple': 'No'} Online,VHS{'multiple': 'No'} Blu_Ray There is some work that needs to be done on this tag. You can use regex to find commas — that will tell whether the multiple attribute should be "Yes" or "No". Adding and modifying attributes can be done easily with the .set()method. import refor form in root.findall("./genre/decade/movie/format"): # Search for the commas in the format text match = re.search(',',form.text) if match: form.set('multiple','Yes') else: form.set('multiple','No')# Write out the tree to the file againtree.write("movies.xml")tree = ET.parse('movies.xml')root = tree.getroot()for form in root.findall("./genre/decade/movie/format"): print(form.attrib, form.text){'multiple': 'No'} DVD{'multiple': 'Yes'} DVD,Online{'multiple': 'No'} Blu-ray{'multiple': 'Yes'} dvd, digital{'multiple': 'No'} VHS{'multiple': 'No'} Online{'multiple': 'No'} DVD{'multiple': 'No'} DVD{'multiple': 'No'} blue-ray{'multiple': 'Yes'} DVD,VHS{'multiple': 'No'} DVD{'multiple': 'Yes'} DVD,digital,Netflix{'multiple': 'Yes'} Online,VHS{'multiple': 'No'} Blu_Ray Some of the data has been placed in the wrong decade. Use what you have learned about XML and ElementTree to find and fix the decade data errors. It will be useful to print out both the decade tags and the year tags throughout the document. for decade in root.findall("./genre/decade"): print(decade.attrib) for year in decade.findall("./movie/year"): print(year.text){'years': '1980s'}1981 1984 1985 {'years': '1990s'}2000 1992 1992 {'years': '1970s'}1979 {'years': '1980s'}1986 2000 {'years': '1960s'}1966 {'years': '2010s'}2010 2011 {'years': '1980s'}1984 {'years': '1990s'}1991 The two years that are in the wrong decade are the movies from the 2000s. Figure out what those movies are, using an XPath expression. for movie in root.findall("./genre/decade/movie/[year='2000']"): print(movie.attrib){'favorite': 'False', 'title': 'X-Men'}{'favorite': 'FALSE', 'title': 'American Psycho'} You have to add a new decade tag, the 2000s, to the Action genre in order to move the X-Men data. The .SubElement() method can be used to add this tag to the end of the XML. action = root.find("./genre[@category='Action']")new_dec = ET.SubElement(action, 'decade')new_dec.attrib["years"] = '2000s' Now append the X-Men movie to the 2000s and remove it from the 1990s, using .append() and .remove(), respectively. xmen = root.find("./genre/decade/movie[@title='X-Men']")dec2000s = root.find("./genre[@category='Action']/decade[@years='2000s']")dec2000s.append(xmen)dec1990s = root.find("./genre[@category='Action']/decade[@years='1990s']")dec1990s.remove(xmen) Nice, so you were able to essentially move an entire movie to a new decade. Save your changes back to the XML. tree.write("movies.xml")tree = ET.parse('movies.xml')root = tree.getroot()print(ET.tostring(root, encoding='utf8').decode('utf8')) ElementTree is an important Python library that allows you to parse and navigate an XML document. Using ElementTree breaks down the XML document in a tree structure that is easy to work with. When in doubt, print it out (print(ET.tostring(root, encoding='utf8').decode('utf8'))) - use this helpful print statement to view the entire XML document at once. Original Post as published by Steph Howson: Datacamp Python 3 Documentation: ElementTree
[ { "code": null, "e": 450, "s": 172, "text": "Learn how you can parse, explore, modify and populate XML files with the Python ElementTree package, for loops and XPath expressions. As a data scientist, you’ll find that understanding XML is powerful for both web-scraping and general practice in parsing a structured document" }, { "code": null, "e": 818, "s": 450, "text": "Extensible Markup Language (XML) is a markup language which encodes documents by defining a set of rules in both machine-readable and human-readable format. Extended from SGML (Standard Generalized Markup Language), it lets us describe the structure of the document. In XML, we can define custom tags. We can also use XML as a standard format to exchange information." }, { "code": null, "e": 1155, "s": 818, "text": "XML documents have sections, called elements, defined by a beginning and an ending tag. A tag is a markup construct that begins with < and ends with >. The characters between the start-tag and end-tag, if there are any, are the element's content. Elements can contain markup, including other elements, which are called \"child elements\"." }, { "code": null, "e": 1241, "s": 1155, "text": "The largest, top-level element is called the root, which contains all other elements." }, { "code": null, "e": 1430, "s": 1241, "text": "Attributes are name–value pair that exist within a start-tag or empty-element tag. An XML attribute can only have a single value and each attribute can appear at most once on each element." }, { "code": null, "e": 1503, "s": 1430, "text": "Here’s a snapshot of movies.xml that we will be using for this tutorial:" }, { "code": null, "e": 4440, "s": 1503, "text": "<?xml version=\"1.0\"?><collection> <genre category=\"Action\"> <decade years=\"1980s\"> <movie favorite=\"True\" title=\"Indiana Jones: The raiders of the lost Ark\"> <format multiple=\"No\">DVD</format> <year>1981</year> <rating>PG</rating> <description> 'Archaeologist and adventurer Indiana Jones is hired by the U.S. government to find the Ark of the Covenant before the Nazis.' </description> </movie> <movie favorite=\"True\" title=\"THE KARATE KID\"> <format multiple=\"Yes\">DVD,Online</format> <year>1984</year> <rating>PG</rating> <description>None provided.</description> </movie> <movie favorite=\"False\" title=\"Back 2 the Future\"> <format multiple=\"False\">Blu-ray</format> <year>1985</year> <rating>PG</rating> <description>Marty McFly</description> </movie> </decade> <decade years=\"1990s\"> <movie favorite=\"False\" title=\"X-Men\"> <format multiple=\"Yes\">dvd, digital</format> <year>2000</year> <rating>PG-13</rating> <description>Two mutants come to a private academy for their kind whose resident superhero team must oppose a terrorist organization with similar powers.</description> </movie> <movie favorite=\"True\" title=\"Batman Returns\"> <format multiple=\"No\">VHS</format> <year>1992</year> <rating>PG13</rating> <description>NA.</description> </movie> <movie favorite=\"False\" title=\"Reservoir Dogs\"> <format multiple=\"No\">Online</format> <year>1992</year> <rating>R</rating> <description>WhAtEvER I Want!!!?!</description> </movie> </decade> </genre> <genre category=\"Thriller\"> <decade years=\"1970s\"> <movie favorite=\"False\" title=\"ALIEN\"> <format multiple=\"Yes\">DVD</format> <year>1979</year> <rating>R</rating> <description>\"\"\"\"\"\"\"\"\"</description> </movie> </decade> <decade years=\"1980s\"> <movie favorite=\"True\" title=\"Ferris Bueller's Day Off\"> <format multiple=\"No\">DVD</format> <year>1986</year> <rating>PG13</rating> <description>Funny movie on funny guy </description> </movie> <movie favorite=\"FALSE\" title=\"American Psycho\"> <format multiple=\"No\">blue-ray</format> <year>2000</year> <rating>Unrated</rating> <description>psychopathic Bateman</description> </movie> </decade> </genre>" }, { "code": null, "e": 4674, "s": 4440, "text": "The XML tree structure makes navigation, modification, and removal relatively simple programmatically. Python has a built in library, ElementTree, that has functions to read and manipulate XMLs (and other similarly structured files)." }, { "code": null, "e": 4748, "s": 4674, "text": "First, import ElementTree. It's a common practice to use the alias of ET:" }, { "code": null, "e": 4783, "s": 4748, "text": "import xml.etree.ElementTree as ET" }, { "code": null, "e": 5132, "s": 4783, "text": "In the XML file provided, there is a basic collection of movies described. The only problem is the data is a mess! There have been a lot of different curators of this collection and everyone has their own way of entering data into the file. The main goal in this tutorial will be to read and understand the file with Python — then fix the problems." }, { "code": null, "e": 5185, "s": 5132, "text": "First you need to read in the file with ElementTree." }, { "code": null, "e": 5236, "s": 5185, "text": "tree = ET.parse('movies.xml')root = tree.getroot()" }, { "code": null, "e": 5375, "s": 5236, "text": "Now that you have initialized the tree, you should look at the XML and print out values in order to understand how the tree is structured." }, { "code": null, "e": 5396, "s": 5375, "text": "root.tag'collection'" }, { "code": null, "e": 5469, "s": 5396, "text": "At the top level, you see that this XML is rooted in the collection tag." }, { "code": null, "e": 5483, "s": 5469, "text": "root.attrib{}" }, { "code": null, "e": 5594, "s": 5483, "text": "You can easily iterate over subelements (commonly called “children”) in the root by using a simple “for” loop." }, { "code": null, "e": 5733, "s": 5594, "text": "for child in root: print(child.tag, child.attrib)genre {'category': 'Action'}genre {'category': 'Thriller'}genre {'category': 'Comedy'}" }, { "code": null, "e": 5938, "s": 5733, "text": "Now you know that the children of the root collection are all genre. To designate the genre, the XML uses the attribute category. There are Action, Thriller, and Comedy movies according the genre element." }, { "code": null, "e": 6058, "s": 5938, "text": "Typically it is helpful to know all the elements in the entire tree. One useful function for doing that is root.iter()." }, { "code": null, "e": 6247, "s": 6058, "text": "[elem.tag for elem in root.iter()]['collection', 'genre', 'decade', 'movie', 'format', 'year', 'rating', 'description', 'movie', . . . . 'movie', 'format', 'year', 'rating', 'description']" }, { "code": null, "e": 6445, "s": 6247, "text": "There is a helpful way to see the whole document. If you pass the root into the .tostring() method, you can return the whole document. Within ElementTree, this method takes a slightly strange form." }, { "code": null, "e": 6622, "s": 6445, "text": "Since ElementTree is a powerful library that can interpret more than just XML, you must specify both the encoding and decoding of the document you are displaying as the string." }, { "code": null, "e": 6878, "s": 6622, "text": "You can expand the use of the iter() function to help with finding particular elements of interest. root.iter() will list all subelements under the root that match the element specified. Here, you will list all attributes of the movie element in the tree:" }, { "code": null, "e": 7636, "s": 6878, "text": "for movie in root.iter('movie'): print(movie.attrib){'favorite': 'True', 'title': 'Indiana Jones: The raiders of the lost Ark'}{'favorite': 'True', 'title': 'THE KARATE KID'}{'favorite': 'False', 'title': 'Back 2 the Future'}{'favorite': 'False', 'title': 'X-Men'}{'favorite': 'True', 'title': 'Batman Returns'}{'favorite': 'False', 'title': 'Reservoir Dogs'}{'favorite': 'False', 'title': 'ALIEN'}{'favorite': 'True', 'title': \"Ferris Bueller's Day Off\"}{'favorite': 'FALSE', 'title': 'American Psycho'}{'favorite': 'False', 'title': 'Batman: The Movie'}{'favorite': 'True', 'title': 'Easy A'}{'favorite': 'True', 'title': 'Dinner for SCHMUCKS'}{'favorite': 'False', 'title': 'Ghostbusters'}{'favorite': 'True', 'title': 'Robin Hood: Prince of Thieves'}" }, { "code": null, "e": 7775, "s": 7636, "text": "Many times elements will not have attributes, they will only have text content. Using the attribute .text, you can print out this content." }, { "code": null, "e": 7826, "s": 7775, "text": "Now, print out all the descriptions of the movies." }, { "code": null, "e": 8595, "s": 7826, "text": "for description in root.iter('description'): print(description.text)'Archaeologist and adventurer Indiana Jones is hired by the U.S. government to find the Ark of the Covenant before the Nazis.'None provided.Marty McFlyTwo mutants come to a private academy for their kind whose resident superhero team must oppose a terrorist organization with similar powers.NA.WhAtEvER I Want!!!?!\"\"\"\"\"\"\"\"\"Funny movie about a funny guypsychopathic BatemanWhat a joke!Emma Stone = Hester PrynneTim (Rudd) is a rising executive who “succeeds” in finding the perfect guest, IRS employee Barry (Carell), for his boss’ monthly event, a so-called “dinner for idiots,” which offers certain advantages to the exec who shows up with the biggest buffoon.Who ya gonna call?Robin Hood slaying" }, { "code": null, "e": 8901, "s": 8595, "text": "Printing out the XML is helpful, but XPath is a query language used to search through an XML quickly and easily. However, Understanding XPath is critically important to scanning and populating XMLs. ElementTree has a .findall() function that will traverse the immediate children of the referenced element." }, { "code": null, "e": 8966, "s": 8901, "text": "Here, you will search the tree for movies that came out in 1992:" }, { "code": null, "e": 9149, "s": 8966, "text": "for movie in root.findall(\"./genre/decade/movie/[year='1992']\"): print(movie.attrib){'favorite': 'True', 'title': 'Batman Returns'}{'favorite': 'False', 'title': 'Reservoir Dogs'}" }, { "code": null, "e": 9318, "s": 9149, "text": "The function .findall() always begins at the element specified. This type of function is extremely powerful for a \"find and replace\". You can even search on attributes!" }, { "code": null, "e": 9404, "s": 9318, "text": "Now, print out only the movies that are available in multiple formats (an attribute)." }, { "code": null, "e": 9598, "s": 9404, "text": "for movie in root.findall(\"./genre/decade/movie/format/[@multiple='Yes']\"): print(movie.attrib){'multiple': 'Yes'}{'multiple': 'Yes'}{'multiple': 'Yes'}{'multiple': 'Yes'}{'multiple': 'Yes'}" }, { "code": null, "e": 9729, "s": 9598, "text": "Brainstorm why, in this case, the print statement returns the “Yes” values of multiple. Think about how the \"for\" loop is defined." }, { "code": null, "e": 9813, "s": 9729, "text": "Tip: use '...' inside of XPath to return the parent element of the current element." }, { "code": null, "e": 10142, "s": 9813, "text": "for movie in root.findall(\"./genre/decade/movie/format[@multiple='Yes']...\"): print(movie.attrib){'favorite': 'True', 'title': 'THE KARATE KID'}{'favorite': 'False', 'title': 'X-Men'}{'favorite': 'False', 'title': 'ALIEN'}{'favorite': 'False', 'title': 'Batman: The Movie'}{'favorite': 'True', 'title': 'Dinner for SCHMUCKS'}" }, { "code": null, "e": 10218, "s": 10142, "text": "Earlier, the movie titles were an absolute mess. Now, print them out again:" }, { "code": null, "e": 10976, "s": 10218, "text": "for movie in root.iter('movie'): print(movie.attrib){'favorite': 'True', 'title': 'Indiana Jones: The raiders of the lost Ark'}{'favorite': 'True', 'title': 'THE KARATE KID'}{'favorite': 'False', 'title': 'Back 2 the Future'}{'favorite': 'False', 'title': 'X-Men'}{'favorite': 'True', 'title': 'Batman Returns'}{'favorite': 'False', 'title': 'Reservoir Dogs'}{'favorite': 'False', 'title': 'ALIEN'}{'favorite': 'True', 'title': \"Ferris Bueller's Day Off\"}{'favorite': 'FALSE', 'title': 'American Psycho'}{'favorite': 'False', 'title': 'Batman: The Movie'}{'favorite': 'True', 'title': 'Easy A'}{'favorite': 'True', 'title': 'Dinner for SCHMUCKS'}{'favorite': 'False', 'title': 'Ghostbusters'}{'favorite': 'True', 'title': 'Robin Hood: Prince of Thieves'}" }, { "code": null, "e": 11129, "s": 10976, "text": "Fix the ‘2’ in Back 2 the Future. That should be a find and replace problem. Write code to find the title ‘Back 2 the Future’ and save it as a variable:" }, { "code": null, "e": 11241, "s": 11129, "text": "b2tf = root.find(\"./genre/decade/movie[@title='Back 2 the Future']\")print(b2tf)<Element 'movie' at 0x10ce00ef8>" }, { "code": null, "e": 11385, "s": 11241, "text": "Notice that using the .find() method returns an element of the tree. Much of the time, it is more useful to edit the content within an element." }, { "code": null, "e": 11654, "s": 11385, "text": "Modify the title attribute of the Back 2 the Future element variable to read \"Back to the Future\". Then, print out the attributes of your variable to see your change. You can easily do this by accessing the attribute of an element and then assigning a new value to it:" }, { "code": null, "e": 11768, "s": 11654, "text": "b2tf.attrib[\"title\"] = \"Back to the Future\"print(b2tf.attrib){'favorite': 'False', 'title': 'Back to the Future'}" }, { "code": null, "e": 11962, "s": 11768, "text": "Write out your changes back to the XML so they are permanently fixed in the document. Print out your movie attributes again to make sure your changes worked. Use the .write() method to do this:" }, { "code": null, "e": 12795, "s": 11962, "text": "tree.write(\"movies.xml\")tree = ET.parse('movies.xml')root = tree.getroot()for movie in root.iter('movie'): print(movie.attrib){'favorite': 'True', 'title': 'Indiana Jones: The raiders of the lost Ark'}{'favorite': 'True', 'title': 'THE KARATE KID'}{'favorite': 'False', 'title': 'Back to the Future'}{'favorite': 'False', 'title': 'X-Men'}{'favorite': 'True', 'title': 'Batman Returns'}{'favorite': 'False', 'title': 'Reservoir Dogs'}{'favorite': 'False', 'title': 'ALIEN'}{'favorite': 'True', 'title': \"Ferris Bueller's Day Off\"}{'favorite': 'FALSE', 'title': 'American Psycho'}{'favorite': 'False', 'title': 'Batman: The Movie'}{'favorite': 'True', 'title': 'Easy A'}{'favorite': 'True', 'title': 'Dinner for SCHMUCKS'}{'favorite': 'False', 'title': 'Ghostbusters'}{'favorite': 'True', 'title': 'Robin Hood: Prince of Thieves'}" }, { "code": null, "e": 13010, "s": 12795, "text": "The multiple attribute is incorrect in some places. Use ElementTree to fix the designator based on how many formats the movie comes in. First, print the formatattribute and text to see which parts need to be fixed." }, { "code": null, "e": 13475, "s": 13010, "text": "for form in root.findall(\"./genre/decade/movie/format\"): print(form.attrib, form.text){'multiple': 'No'} DVD{'multiple': 'Yes'} DVD,Online{'multiple': 'False'} Blu-ray{'multiple': 'Yes'} dvd, digital{'multiple': 'No'} VHS{'multiple': 'No'} Online{'multiple': 'Yes'} DVD{'multiple': 'No'} DVD{'multiple': 'No'} blue-ray{'multiple': 'Yes'} DVD,VHS{'multiple': 'No'} DVD{'multiple': 'Yes'} DVD,digital,Netflix{'multiple': 'No'} Online,VHS{'multiple': 'No'} Blu_Ray" }, { "code": null, "e": 13529, "s": 13475, "text": "There is some work that needs to be done on this tag." }, { "code": null, "e": 13709, "s": 13529, "text": "You can use regex to find commas — that will tell whether the multiple attribute should be \"Yes\" or \"No\". Adding and modifying attributes can be done easily with the .set()method." }, { "code": null, "e": 14519, "s": 13709, "text": "import refor form in root.findall(\"./genre/decade/movie/format\"): # Search for the commas in the format text match = re.search(',',form.text) if match: form.set('multiple','Yes') else: form.set('multiple','No')# Write out the tree to the file againtree.write(\"movies.xml\")tree = ET.parse('movies.xml')root = tree.getroot()for form in root.findall(\"./genre/decade/movie/format\"): print(form.attrib, form.text){'multiple': 'No'} DVD{'multiple': 'Yes'} DVD,Online{'multiple': 'No'} Blu-ray{'multiple': 'Yes'} dvd, digital{'multiple': 'No'} VHS{'multiple': 'No'} Online{'multiple': 'No'} DVD{'multiple': 'No'} DVD{'multiple': 'No'} blue-ray{'multiple': 'Yes'} DVD,VHS{'multiple': 'No'} DVD{'multiple': 'Yes'} DVD,digital,Netflix{'multiple': 'Yes'} Online,VHS{'multiple': 'No'} Blu_Ray" }, { "code": null, "e": 14665, "s": 14519, "text": "Some of the data has been placed in the wrong decade. Use what you have learned about XML and ElementTree to find and fix the decade data errors." }, { "code": null, "e": 14760, "s": 14665, "text": "It will be useful to print out both the decade tags and the year tags throughout the document." }, { "code": null, "e": 15115, "s": 14760, "text": "for decade in root.findall(\"./genre/decade\"): print(decade.attrib) for year in decade.findall(\"./movie/year\"): print(year.text){'years': '1980s'}1981 1984 1985 {'years': '1990s'}2000 1992 1992 {'years': '1970s'}1979 {'years': '1980s'}1986 2000 {'years': '1960s'}1966 {'years': '2010s'}2010 2011 {'years': '1980s'}1984 {'years': '1990s'}1991" }, { "code": null, "e": 15250, "s": 15115, "text": "The two years that are in the wrong decade are the movies from the 2000s. Figure out what those movies are, using an XPath expression." }, { "code": null, "e": 15426, "s": 15250, "text": "for movie in root.findall(\"./genre/decade/movie/[year='2000']\"): print(movie.attrib){'favorite': 'False', 'title': 'X-Men'}{'favorite': 'FALSE', 'title': 'American Psycho'}" }, { "code": null, "e": 15600, "s": 15426, "text": "You have to add a new decade tag, the 2000s, to the Action genre in order to move the X-Men data. The .SubElement() method can be used to add this tag to the end of the XML." }, { "code": null, "e": 15724, "s": 15600, "text": "action = root.find(\"./genre[@category='Action']\")new_dec = ET.SubElement(action, 'decade')new_dec.attrib[\"years\"] = '2000s'" }, { "code": null, "e": 15839, "s": 15724, "text": "Now append the X-Men movie to the 2000s and remove it from the 1990s, using .append() and .remove(), respectively." }, { "code": null, "e": 16086, "s": 15839, "text": "xmen = root.find(\"./genre/decade/movie[@title='X-Men']\")dec2000s = root.find(\"./genre[@category='Action']/decade[@years='2000s']\")dec2000s.append(xmen)dec1990s = root.find(\"./genre[@category='Action']/decade[@years='1990s']\")dec1990s.remove(xmen)" }, { "code": null, "e": 16197, "s": 16086, "text": "Nice, so you were able to essentially move an entire movie to a new decade. Save your changes back to the XML." }, { "code": null, "e": 16328, "s": 16197, "text": "tree.write(\"movies.xml\")tree = ET.parse('movies.xml')root = tree.getroot()print(ET.tostring(root, encoding='utf8').decode('utf8'))" }, { "code": null, "e": 16683, "s": 16328, "text": "ElementTree is an important Python library that allows you to parse and navigate an XML document. Using ElementTree breaks down the XML document in a tree structure that is easy to work with. When in doubt, print it out (print(ET.tostring(root, encoding='utf8').decode('utf8'))) - use this helpful print statement to view the entire XML document at once." }, { "code": null, "e": 16736, "s": 16683, "text": "Original Post as published by Steph Howson: Datacamp" } ]
What are nested rules in LESS ? - GeeksforGeeks
09 Jul, 2021 We can very easily define nested rules in LESS. Nested rules are defined as a set of CSS properties that allow the properties of one class to be used for another class and contain the class name as its property. In LESS, you can use class or ID selectors to declare mixin in the same way as CSS styles. It can store multiple values and can be reused in code as necessary. One must have heard the word nested probably referring to nested tables in old table design websites. With LESS, we’re basically doing the same concept, but with nesting LESS rules within other rules. The below examples will demonstrate this concept of nesting in LESS. Example 1: HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" type="text/css" href="style.css" /></head> <body> <div class="container"> <h1>Example of less</h1> <p>We will discuss LESS here.</p> <div class="MyClass"> <h1>Geeks for Geeks portal</h1> <p> Nested rules are clever about handling selector lists </p> </div> </div></body> </html> We will next create the style.less file. .container { h1 { font-size: 24px; color: red; } p { font-size: 24px; color: blue; } .myclass { h1 { font-size: 24px; color:red; } p { font-size: 24px; color:blue; } } } We can compile the style.less file to style.css using the following command. lessc style.less style.css After executing the above command, the style.css file is created with the following code. .container h1 { font-size: 24px; color: red; } .container p { font-size: 24px; color: blue; } .container .MyClass h1 { font-size: 24px; color: red; } .container .MyClass p { font-size: 24px; color: blue; } Output: Example 2: In this example, we will use the LESS JavaScript file that will cause the browser to automatically compile LESS code to CSS. However, it is not recommended to use this in production as it could affect the performance of the website. HTML <!DOCTYPE html><html> <head> <link rel="stylesheet/less" type="text/css" href="style.less" /> <script type="text/javascript" src= "https://cdn.jsdelivr.net/npm/[email protected]"> </script></head> <body> <div class="Important"> <div class="Different"> GeeksforGeeks </div> <div class="Nestedrules"> LESS Nesting example! </div> </div></body> </html> We will next create the style.less file. .Important { color: green; .Different { font-size: 40px;; } .Nestedrules { font-size: 20px; } } The browser will automatically compile the LESS code to CSS and the resulting page can be viewed in the browser. The final compiled CSS would be like the one below. .Important { color: green; } .Important .Different { font-size: 40px; } .Important .Nestedrules { font-size: 20px; } Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Questions Picked SASS CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25376, "s": 25348, "text": "\n09 Jul, 2021" }, { "code": null, "e": 25748, "s": 25376, "text": "We can very easily define nested rules in LESS. Nested rules are defined as a set of CSS properties that allow the properties of one class to be used for another class and contain the class name as its property. In LESS, you can use class or ID selectors to declare mixin in the same way as CSS styles. It can store multiple values and can be reused in code as necessary." }, { "code": null, "e": 26018, "s": 25748, "text": "One must have heard the word nested probably referring to nested tables in old table design websites. With LESS, we’re basically doing the same concept, but with nesting LESS rules within other rules. The below examples will demonstrate this concept of nesting in LESS." }, { "code": null, "e": 26029, "s": 26018, "text": "Example 1:" }, { "code": null, "e": 26034, "s": 26029, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /></head> <body> <div class=\"container\"> <h1>Example of less</h1> <p>We will discuss LESS here.</p> <div class=\"MyClass\"> <h1>Geeks for Geeks portal</h1> <p> Nested rules are clever about handling selector lists </p> </div> </div></body> </html>", "e": 26483, "s": 26034, "text": null }, { "code": null, "e": 26526, "s": 26485, "text": "We will next create the style.less file." }, { "code": null, "e": 26837, "s": 26526, "text": ".container {\n h1 {\n font-size: 24px;\n color: red;\n }\n p {\n font-size: 24px;\n color: blue;\n }\n \n .myclass {\n h1 {\n font-size: 24px;\n color:red;\n }\n p {\n font-size: 24px;\n color:blue;\n }\n }\n}" }, { "code": null, "e": 26914, "s": 26837, "text": "We can compile the style.less file to style.css using the following command." }, { "code": null, "e": 26941, "s": 26914, "text": "lessc style.less style.css" }, { "code": null, "e": 27031, "s": 26941, "text": "After executing the above command, the style.css file is created with the following code." }, { "code": null, "e": 27269, "s": 27031, "text": ".container h1 {\n font-size: 24px;\n color: red;\n}\n.container p {\n font-size: 24px;\n color: blue;\n}\n.container .MyClass h1 {\n font-size: 24px;\n color: red;\n}\n.container .MyClass p {\n font-size: 24px;\n color: blue;\n}" }, { "code": null, "e": 27277, "s": 27269, "text": "Output:" }, { "code": null, "e": 27521, "s": 27277, "text": "Example 2: In this example, we will use the LESS JavaScript file that will cause the browser to automatically compile LESS code to CSS. However, it is not recommended to use this in production as it could affect the performance of the website." }, { "code": null, "e": 27526, "s": 27521, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet/less\" type=\"text/css\" href=\"style.less\" /> <script type=\"text/javascript\" src= \"https://cdn.jsdelivr.net/npm/[email protected]\"> </script></head> <body> <div class=\"Important\"> <div class=\"Different\"> GeeksforGeeks </div> <div class=\"Nestedrules\"> LESS Nesting example! </div> </div></body> </html>", "e": 27960, "s": 27526, "text": null }, { "code": null, "e": 28001, "s": 27960, "text": "We will next create the style.less file." }, { "code": null, "e": 28139, "s": 28001, "text": ".Important {\n color: green;\n\n .Different {\n font-size: 40px;;\n }\n \n .Nestedrules {\n font-size: 20px;\n }\n}" }, { "code": null, "e": 28304, "s": 28139, "text": "The browser will automatically compile the LESS code to CSS and the resulting page can be viewed in the browser. The final compiled CSS would be like the one below." }, { "code": null, "e": 28433, "s": 28304, "text": ".Important {\n color: green;\n}\n.Important .Different {\n font-size: 40px;\n}\n.Important .Nestedrules {\n font-size: 20px;\n}" }, { "code": null, "e": 28441, "s": 28433, "text": "Output:" }, { "code": null, "e": 28578, "s": 28441, "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": 28592, "s": 28578, "text": "CSS-Questions" }, { "code": null, "e": 28599, "s": 28592, "text": "Picked" }, { "code": null, "e": 28604, "s": 28599, "text": "SASS" }, { "code": null, "e": 28608, "s": 28604, "text": "CSS" }, { "code": null, "e": 28613, "s": 28608, "text": "HTML" }, { "code": null, "e": 28630, "s": 28613, "text": "Web Technologies" }, { "code": null, "e": 28635, "s": 28630, "text": "HTML" }, { "code": null, "e": 28733, "s": 28635, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28742, "s": 28733, "text": "Comments" }, { "code": null, "e": 28755, "s": 28742, "text": "Old Comments" }, { "code": null, "e": 28792, "s": 28755, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28821, "s": 28792, "text": "Form validation using jQuery" }, { "code": null, "e": 28860, "s": 28821, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28902, "s": 28860, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28937, "s": 28902, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28997, "s": 28937, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29058, "s": 28997, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29111, "s": 29058, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29161, "s": 29111, "text": "How to Insert Form Data into Database using PHP ?" } ]
Splitter splitToList() method | Guava | Java - GeeksforGeeks
31 Jan, 2019 The method splitToList(CharSequence sequence) splits sequence into string components and returns them as an immutable list. Syntax: public List<String> splitToList(CharSequence sequence) Parameters: This method takes sequence as parameter which is the sequence of characters to split. Return Value: This method returns an immutable list of the segments split from the parameter. Below examples illustrate the working of splitToList() method: Example 1: // Java code to show implementation of// splitToList method// of Guava's Splitter Class import com.google.common.base.Splitter;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { // Creating a string variable String str = "Hello, geeks, for, geeks, noida"; // SplitToList returns a List of the strings. // This can be transformed to an ArrayList // or used directly in a loop. List<String> myList = Splitter.on(',').splitToList(str); for (String temp : myList) { System.out.println(temp); } }} Hello geeks for geeks noida Example 2: // Java code to show implementation of// splitToList method // of Guava's Splitter Class import com.google.common.base.Splitter;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { // Creating a string variable String str = "Everyone. should. Learn, Data. Structures"; // SplitToList returns a List of the strings. // This can be transformed to an ArrayList // or used directly in a loop. List<String> myList = Splitter.on('.').splitToList(str); for (String temp : myList) { System.out.println(temp); } }} Everyone should Learn, Data Structures Guava-Functions Guava-Splitter java-guava java-list Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java
[ { "code": null, "e": 25022, "s": 24994, "text": "\n31 Jan, 2019" }, { "code": null, "e": 25146, "s": 25022, "text": "The method splitToList(CharSequence sequence) splits sequence into string components and returns them as an immutable list." }, { "code": null, "e": 25154, "s": 25146, "text": "Syntax:" }, { "code": null, "e": 25215, "s": 25154, "text": "public List<String> \n splitToList(CharSequence sequence)\n" }, { "code": null, "e": 25313, "s": 25215, "text": "Parameters: This method takes sequence as parameter which is the sequence of characters to split." }, { "code": null, "e": 25407, "s": 25313, "text": "Return Value: This method returns an immutable list of the segments split from the parameter." }, { "code": null, "e": 25470, "s": 25407, "text": "Below examples illustrate the working of splitToList() method:" }, { "code": null, "e": 25481, "s": 25470, "text": "Example 1:" }, { "code": "// Java code to show implementation of// splitToList method// of Guava's Splitter Class import com.google.common.base.Splitter;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { // Creating a string variable String str = \"Hello, geeks, for, geeks, noida\"; // SplitToList returns a List of the strings. // This can be transformed to an ArrayList // or used directly in a loop. List<String> myList = Splitter.on(',').splitToList(str); for (String temp : myList) { System.out.println(temp); } }}", "e": 26105, "s": 25481, "text": null }, { "code": null, "e": 26138, "s": 26105, "text": "Hello\n geeks\n for\n geeks\n noida\n" }, { "code": null, "e": 26149, "s": 26138, "text": "Example 2:" }, { "code": "// Java code to show implementation of// splitToList method // of Guava's Splitter Class import com.google.common.base.Splitter;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { // Creating a string variable String str = \"Everyone. should. Learn, Data. Structures\"; // SplitToList returns a List of the strings. // This can be transformed to an ArrayList // or used directly in a loop. List<String> myList = Splitter.on('.').splitToList(str); for (String temp : myList) { System.out.println(temp); } }}", "e": 26784, "s": 26149, "text": null }, { "code": null, "e": 26827, "s": 26784, "text": "Everyone\n should\n Learn, Data\n Structures\n" }, { "code": null, "e": 26843, "s": 26827, "text": "Guava-Functions" }, { "code": null, "e": 26858, "s": 26843, "text": "Guava-Splitter" }, { "code": null, "e": 26869, "s": 26858, "text": "java-guava" }, { "code": null, "e": 26879, "s": 26869, "text": "java-list" }, { "code": null, "e": 26892, "s": 26879, "text": "Java-Strings" }, { "code": null, "e": 26897, "s": 26892, "text": "Java" }, { "code": null, "e": 26910, "s": 26897, "text": "Java-Strings" }, { "code": null, "e": 26915, "s": 26910, "text": "Java" }, { "code": null, "e": 27013, "s": 26915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27045, "s": 27013, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27096, "s": 27045, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27126, "s": 27096, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27145, "s": 27126, "text": "Interfaces in Java" }, { "code": null, "e": 27163, "s": 27145, "text": "ArrayList in Java" }, { "code": null, "e": 27194, "s": 27163, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27226, "s": 27194, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27246, "s": 27226, "text": "Stack Class in Java" }, { "code": null, "e": 27261, "s": 27246, "text": "Stream In Java" } ]
Electron - Audio and Video Capturing
Audio and video capturing are important characteristics if you are building apps for screen sharing, voice memos, etc. They are also useful if you require an application to capture the profile picture. We will be using the getUserMedia HTML5 API for capturing audio and video streams with Electron. Let us first set up our main process in the main.js file as follows − const {app, BrowserWindow} = require('electron') const url = require('url') const path = require('path') let win // Set the path where recordings will be saved app.setPath("userData", __dirname + "/saved_recordings") function createWindow() { win = new BrowserWindow({width: 800, height: 600}) win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) } app.on('ready', createWindow) Now that we have set up our main process, let us create the HTML file that will be capturing this content. Create a file called index.html with the following content − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>Audio and Video</title> </head> <body> <video autoplay></video> <script type = "text/javascript"> function errorCallback(e) { console.log('Error', e) } navigator.getUserMedia({video: true, audio: true}, (localMediaStream) => { var video = document.querySelector('video') video.src = window.URL.createObjectURL(localMediaStream) video.onloadedmetadata = (e) => { // Ready to go. Do some stuff. }; }, errorCallback) </script> </body> </html> The above program will generate the following output − You now have the stream from both your webcam and your microphone. You can send this stream over the network or save this in a format you like. Have a look at the MDN Documentation for capturing images to get the images from your webcam and store them. This was done using the HTML5 getUserMedia API. You can also capture the user desktop using the desktopCapturer module that comes with Electron. Let us now see an example of how to get the screen stream. Use the same main.js file as above and edit the index.html file to have the following content − desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => { if (error) throw error for (let i = 0; i < sources.length; ++i) { if (sources[i].name === 'Your Window Name here!') { navigator.webkitGetUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: sources[i].id, minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }, handleStream, handleError) return } } }) function handleStream (stream) { document.querySelector('video').src = URL.createObjectURL(stream) } function handleError (e) { console.log(e) } We have used the desktopCapturer module to get the information about each open window. Now you can capture the events of a specific application or of the entire screen depending on the name you pass to the above if statement. This will stream only that which is happening on that screen to your app. You can refer to this StackOverflow question to understand the usage in detail. 251 Lectures 35.5 hours Gowthami Swarna 9 Lectures 41 mins Ashraf Said 8 Lectures 32 mins Ashraf Said 25 Lectures 1 hours Ashraf Said 17 Lectures 1 hours Ashraf Said 8 Lectures 25 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2267, "s": 2065, "text": "Audio and video capturing are important characteristics if you are building apps for screen sharing, voice memos, etc. They are also useful if you require an application to capture the profile picture." }, { "code": null, "e": 2434, "s": 2267, "text": "We will be using the getUserMedia HTML5 API for capturing audio and video streams with Electron. Let us first set up our main process in the main.js file as follows −" }, { "code": null, "e": 2899, "s": 2434, "text": "const {app, BrowserWindow} = require('electron')\nconst url = require('url')\nconst path = require('path')\n\nlet win\n\n// Set the path where recordings will be saved\napp.setPath(\"userData\", __dirname + \"/saved_recordings\")\n\nfunction createWindow() {\n win = new BrowserWindow({width: 800, height: 600})\n win.loadURL(url.format({\n pathname: path.join(__dirname, 'index.html'),\n protocol: 'file:',\n slashes: true\n }))\n}\n\napp.on('ready', createWindow)" }, { "code": null, "e": 3067, "s": 2899, "text": "Now that we have set up our main process, let us create the HTML file that will be capturing this content. Create a file called index.html with the following content −" }, { "code": null, "e": 3727, "s": 3067, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"UTF-8\">\n <title>Audio and Video</title>\n </head>\n \n <body>\n <video autoplay></video>\n <script type = \"text/javascript\">\n function errorCallback(e) {\n console.log('Error', e)\n }\n\n navigator.getUserMedia({video: true, audio: true}, (localMediaStream) => {\n var video = document.querySelector('video')\n video.src = window.URL.createObjectURL(localMediaStream)\n video.onloadedmetadata = (e) => {\n // Ready to go. Do some stuff.\n };\n }, errorCallback)\n </script>\n </body>\n</html>" }, { "code": null, "e": 3782, "s": 3727, "text": "The above program will generate the following output −" }, { "code": null, "e": 3926, "s": 3782, "text": "You now have the stream from both your webcam and your microphone. You can send this stream over the network or save this in a format you like." }, { "code": null, "e": 4239, "s": 3926, "text": "Have a look at the MDN Documentation for capturing images to get the images from your webcam and store them. This was done using the HTML5 getUserMedia API. You can also capture the user desktop using the desktopCapturer module that comes with Electron. Let us now see an example of how to get the screen stream." }, { "code": null, "e": 4335, "s": 4239, "text": "Use the same main.js file as above and edit the index.html file to have the following content −" }, { "code": null, "e": 5152, "s": 4335, "text": "desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {\n if (error) throw error\n for (let i = 0; i < sources.length; ++i) {\n if (sources[i].name === 'Your Window Name here!') {\n navigator.webkitGetUserMedia({\n audio: false,\n video: {\n mandatory: {\n chromeMediaSource: 'desktop',\n chromeMediaSourceId: sources[i].id,\n minWidth: 1280,\n maxWidth: 1280,\n minHeight: 720,\n maxHeight: 720\n }\n }\n }, handleStream, handleError)\n return\n }\n }\n})\n\nfunction handleStream (stream) {\n document.querySelector('video').src = URL.createObjectURL(stream)\n}\n\nfunction handleError (e) {\n console.log(e)\n}" }, { "code": null, "e": 5452, "s": 5152, "text": "We have used the desktopCapturer module to get the information about each open window. Now you can capture the events of a specific application or of the entire screen depending on the name you pass to the above if statement. This will stream only that which is happening on that screen to your app." }, { "code": null, "e": 5532, "s": 5452, "text": "You can refer to this StackOverflow question to understand the usage in detail." }, { "code": null, "e": 5569, "s": 5532, "text": "\n 251 Lectures \n 35.5 hours \n" }, { "code": null, "e": 5586, "s": 5569, "text": " Gowthami Swarna" }, { "code": null, "e": 5617, "s": 5586, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 5630, "s": 5617, "text": " Ashraf Said" }, { "code": null, "e": 5661, "s": 5630, "text": "\n 8 Lectures \n 32 mins\n" }, { "code": null, "e": 5674, "s": 5661, "text": " Ashraf Said" }, { "code": null, "e": 5707, "s": 5674, "text": "\n 25 Lectures \n 1 hours \n" }, { "code": null, "e": 5720, "s": 5707, "text": " Ashraf Said" }, { "code": null, "e": 5753, "s": 5720, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5766, "s": 5753, "text": " Ashraf Said" }, { "code": null, "e": 5797, "s": 5766, "text": "\n 8 Lectures \n 25 mins\n" }, { "code": null, "e": 5810, "s": 5797, "text": " Ashraf Said" }, { "code": null, "e": 5817, "s": 5810, "text": " Print" }, { "code": null, "e": 5828, "s": 5817, "text": " Add Notes" } ]
Largest number in K swaps | Practice | GeeksforGeeks
Given a number K and string str of digits denoting a positive integer, build the largest number possible by performing swap operations on the digits of str at most K times. Example 1: Input: K = 4 str = "1234567" Output: 7654321 Explanation: Three swaps can make the input 1234567 to 7654321, swapping 1 with 7, 2 with 6 and finally 3 with 5 Example 2: Input: K = 3 str = "3435335" Output: 5543333 Explanation: Three swaps can make the input 3435335 to 5543333, swapping 3 with 5, 4 with 5 and finally 3 with 4 Your task: You don't have to read input or print anything. Your task is to complete the function findMaximumNum() which takes the string and an integer as input and returns a string containing the largest number formed by perfoming the swap operation at most k times. Expected Time Complexity: O(n!/(n-k)!) , where n = length of input string Expected Auxiliary Space: O(n) Constraints: 1 ≤ |str| ≤ 30 1 ≤ K ≤ 10 +5 amitpurohit47471 week ago class Solution { public: void rec(string str, int k, int a, string &ans){ ans=max(ans,str); if(k==0) return; for(int i=a;i<str.length()-1;i++){ for(int j=i+1;j<str.length();j++){ if(str[j]>str[i]){ swap(str[i],str[j]); rec(str,k-1,i+1,ans); swap(str[i],str[j]); } } } } string findMaximumNum(string str, int k) { // code here. string ans=str; rec(str,k,0,ans); return ans; } }; 0 joyrockok2 weeks ago class Solution{static String strMax = "";public static String findMaximumNum(String str, int k) { strMax = ""; char [] arr = str.toCharArray(); findNum(arr, k); if(strMax.isEmpty()) return str; return strMax;}public static void findNum(char [] arr, int k) { if(k==0) return; int size = arr.length; for(int i=0; i<size-1; i++) { for(int j=i+1; j<size; j++) { char a = arr[i]; char b = arr[j]; if(a<b) { char tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; String toStr = String.valueOf(arr); if(toStr.compareTo(strMax) > 0){ strMax = toStr; } findNum(arr, k-1); } if(a<b) { char tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } }}} 0 vadapaav4 weeks ago Whats wrong with this code ?? help .. string findMaximumNum(string str, int k) { int n = str.length(); for(int i=0; i<n; i++) { if(k==0) break; int ind = i; for(int j=n-1; j>i; j--) { if(str[j]>str[ind]) ind = j; } if(i!=ind) { k--; swap(str[ind], str[i]); } } return str; } 0 shraddhakumari5151 month ago can someone tell me why my code is not working? please help class Solution{ //Function to find the largest number after k swaps. public static String findMaximumNum(String str, int k) { //code here. String[] a=new String[1]; a[0]="0"; int[] k1=new int[1]; k1[0]=k; if(str.length()==1) return str; sol(0,str,k,a); return a[0]; } static void sol(int st,String str, int k1,String[] a) { if(k1==0 || st==str.length()) { return ; } for(int i=st;i<str.length();i++) { if(Character.getNumericValue(str.charAt(i))<Character.getNumericValue(str.charAt(st)) && st!=i) continue; str=swap(str,i,st); if(Long.parseLong(str)>Long.parseLong(a[0])) { a[0]=copy(str); } if(i==st) sol(st+1,str,k1,a); sol(st+1,str,k1--,a); str=swap(str,i,st); } return; } static String swap(String str, int i, int j) { char ch[] = str.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.valueOf(ch); } static String copy(String str) { String z=str; return z; }} +6 vinamrajha1 month ago void helper(string str, string &maxi, int k, int idx){ if(k==0) return; char c = str[idx]; for(int i = idx+1; i<str.length(); ++i){ if(str[i]>c) c = str[i]; } if(c != str[idx]) k--; for(int i =0; i<str.length(); i++){ if(str[i]==c){ swap(str[idx], str[i]); if(maxi < str) maxi = str; helper(str, maxi, k, idx+1); swap(str[idx], str[i]); } } } string findMaximumNum(string str, int k) { // code here. string maxi = str; helper(str, maxi, k, 0); return maxi; } 0 blank551k2 months ago class Solution { public: string s; void answer(string curr,int k,int i){ if(k==0 || i==s.size()){ if(s<curr){ s=curr; } return; } for(int j=i;j<curr.size();++j){ if(curr[j]<=curr[i] && i!=j){ continue; } swap(curr[j],curr[i]); // saving the swap when i=j; if(i==j){ answer(curr,k,i+1); } answer(curr,k-1,i+1); swap(curr[j],curr[i]); } return ; } //Function to find the largest number after k swaps. string findMaximumNum(string str, int k) { s=str; answer(str,k,0); return s; } }; 0 naveenkushawaha20032 months ago //0.0 sec Very Simple Solution........ class Solution{ public: //Function to find the largest number after k swaps. string find(int i,string str,int k,int t){if(i>=str.size()||t==k) return str;string str1,str2=str;stack<pair<char,int>>s;char ch=str[i];for(int j=i+1;j<str.size();j++){ if(ch<=str[j]){ //cout<<ch<<" "<<str[j]<<endl; while(!s.empty()&&str[j]>s.top().first) s.pop(); s.push(make_pair(str[j],j)); ch=str[j]; }}if(s.empty()==true){ str1=find(i+1,str,k,t); if(str2<str1) str2=str1;}while(!s.empty()){ if(str[i]==s.top().first) str1=find(i+1,str,k,t); else{ swap(str[i],str[s.top().second]); str1=find(i+1,str,k,t+1); swap(str[i],str[s.top().second]);} if(str2<str1) str2=str1; s.pop();}return str2; } string findMaximumNum(string str, int k) { return find(0,str,k,0); } +1 thotakurapavan3 months ago java solution :: class Solution{ //Function to find the largest number after k swaps. public static String findMaximumNum(String str, int k) { char[] vals = str.toCharArray(); return findmax(vals, 0 , k); } public static String findmax(char[] vals, int start, int k) { if(0 == k) return String.valueOf(vals); if(start == vals.length) return String.valueOf(vals); char maxVal = vals[start]; for(int i = start+1; i<vals.length; i++) { if(maxVal < vals[i]) { maxVal = vals[i]; } } if(vals[start] == maxVal) { return findmax(vals, start+1, k); } String max = String.valueOf(vals); for(int i = start+1; i<vals.length; i++) { if(Integer.valueOf(maxVal) == Integer.valueOf(vals[i])) { char[] newVal = vals.clone(); char temp = newVal[start]; newVal[start] = newVal[i]; newVal[i] = temp; String newMax = findmax(newVal, start+1, k-1); if(max.compareTo(newMax) < 0) { max = newMax; } } } return max; }} -1 2019011223 months ago Why the solution does not get accepted in C++, and shows abort 3 (SIGABRT) error after test case 4 ? 0 araj2920183 months ago class Solution{ public: //Function to find the largest number after k swaps. void klp(string str,int k,string &maxm,int ctr){ if(k==0){ return ; } int n=str.size(); char maxi=str[ctr]; for(int i=ctr+1;i<n;i++){ if(str[i]>maxi){ maxi=str[i]; } } if(maxi!=str[ctr]){ k--; } for (int j=n-1;j>=ctr;j--){ if(str[j]==maxi){ swap(str[ctr],str[j]); if(str.compare(maxm)>0){ maxm=str; } klp(str,k,maxm,ctr+1); swap(str[ctr],str[j]); } } } string findMaximumNum(string str, int k) { string maxm=""; klp(str,k,maxm,0); return maxm; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 411, "s": 238, "text": "Given a number K and string str of digits denoting a positive integer, build the largest number possible by performing swap operations on the digits of str at most K times." }, { "code": null, "e": 423, "s": 411, "text": "\nExample 1:" }, { "code": null, "e": 582, "s": 423, "text": "Input:\nK = 4\nstr = \"1234567\"\nOutput:\n7654321\nExplanation:\nThree swaps can make the\ninput 1234567 to 7654321, swapping 1\nwith 7, 2 with 6 and finally 3 with 5\n" }, { "code": null, "e": 593, "s": 582, "text": "Example 2:" }, { "code": null, "e": 754, "s": 593, "text": "Input:\nK = 3\nstr = \"3435335\"\nOutput:\n5543333\nExplanation:\nThree swaps can make the input\n3435335 to 5543333, swapping 3 \nwith 5, 4 with 5 and finally 3 with 4 \n" }, { "code": null, "e": 1023, "s": 754, "text": "\nYour task:\nYou don't have to read input or print anything. Your task is to complete the function findMaximumNum() which takes the string and an integer as input and returns a string containing the largest number formed by perfoming the swap operation at most k times." }, { "code": null, "e": 1129, "s": 1023, "text": "\nExpected Time Complexity: O(n!/(n-k)!) , where n = length of input string\nExpected Auxiliary Space: O(n)" }, { "code": null, "e": 1169, "s": 1129, "text": "\nConstraints:\n1 ≤ |str| ≤ 30\n1 ≤ K ≤ 10" }, { "code": null, "e": 1172, "s": 1169, "text": "+5" }, { "code": null, "e": 1198, "s": 1172, "text": "amitpurohit47471 week ago" }, { "code": null, "e": 1781, "s": 1198, "text": "class Solution\n{\n public:\n void rec(string str, int k, int a, string &ans){\n ans=max(ans,str);\n if(k==0) return;\n for(int i=a;i<str.length()-1;i++){\n for(int j=i+1;j<str.length();j++){\n if(str[j]>str[i]){\n swap(str[i],str[j]);\n rec(str,k-1,i+1,ans);\n swap(str[i],str[j]);\n }\n }\n }\n }\n \n string findMaximumNum(string str, int k)\n {\n // code here.\n string ans=str;\n rec(str,k,0,ans);\n return ans;\n }\n};" }, { "code": null, "e": 1783, "s": 1781, "text": "0" }, { "code": null, "e": 1804, "s": 1783, "text": "joyrockok2 weeks ago" }, { "code": null, "e": 2620, "s": 1804, "text": "class Solution{static String strMax = \"\";public static String findMaximumNum(String str, int k) { strMax = \"\"; char [] arr = str.toCharArray(); findNum(arr, k); if(strMax.isEmpty()) return str; return strMax;}public static void findNum(char [] arr, int k) { if(k==0) return; int size = arr.length; for(int i=0; i<size-1; i++) { for(int j=i+1; j<size; j++) { char a = arr[i]; char b = arr[j]; if(a<b) { char tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; String toStr = String.valueOf(arr); if(toStr.compareTo(strMax) > 0){ strMax = toStr; } findNum(arr, k-1); } if(a<b) { char tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } }}}" }, { "code": null, "e": 2622, "s": 2620, "text": "0" }, { "code": null, "e": 2642, "s": 2622, "text": "vadapaav4 weeks ago" }, { "code": null, "e": 2680, "s": 2642, "text": "Whats wrong with this code ?? help .." }, { "code": null, "e": 3071, "s": 2680, "text": "string findMaximumNum(string str, int k)\n {\n int n = str.length();\n \tfor(int i=0; i<n; i++) {\n \t if(k==0)\n \t break;\n \t int ind = i;\n \t for(int j=n-1; j>i; j--) {\n \t if(str[j]>str[ind])\n \t ind = j;\n \t }\n \t if(i!=ind) {\n \t k--;\n \t swap(str[ind], str[i]);\n \t }\n \t}\n \treturn str;\n }" }, { "code": null, "e": 3073, "s": 3071, "text": "0" }, { "code": null, "e": 3102, "s": 3073, "text": "shraddhakumari5151 month ago" }, { "code": null, "e": 3150, "s": 3102, "text": "can someone tell me why my code is not working?" }, { "code": null, "e": 3162, "s": 3150, "text": "please help" }, { "code": null, "e": 4536, "s": 3164, "text": "class Solution{ //Function to find the largest number after k swaps. public static String findMaximumNum(String str, int k) { //code here. String[] a=new String[1]; a[0]=\"0\"; int[] k1=new int[1]; k1[0]=k; if(str.length()==1) return str; sol(0,str,k,a); return a[0]; } static void sol(int st,String str, int k1,String[] a) { if(k1==0 || st==str.length()) { return ; } for(int i=st;i<str.length();i++) { if(Character.getNumericValue(str.charAt(i))<Character.getNumericValue(str.charAt(st)) && st!=i) continue; str=swap(str,i,st); if(Long.parseLong(str)>Long.parseLong(a[0])) { a[0]=copy(str); } if(i==st) sol(st+1,str,k1,a); sol(st+1,str,k1--,a); str=swap(str,i,st); } return; } static String swap(String str, int i, int j) { char ch[] = str.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.valueOf(ch); } static String copy(String str) { String z=str; return z; }} " }, { "code": null, "e": 4539, "s": 4536, "text": "+6" }, { "code": null, "e": 4561, "s": 4539, "text": "vinamrajha1 month ago" }, { "code": null, "e": 5198, "s": 4561, "text": "void helper(string str, string &maxi, int k, int idx){\n if(k==0) return;\n char c = str[idx];\n for(int i = idx+1; i<str.length(); ++i){\n if(str[i]>c) c = str[i];\n }\n if(c != str[idx]) k--;\n for(int i =0; i<str.length(); i++){\n if(str[i]==c){\n swap(str[idx], str[i]);\n if(maxi < str) maxi = str;\n helper(str, maxi, k, idx+1);\n swap(str[idx], str[i]);\n }\n }\n }\n string findMaximumNum(string str, int k)\n {\n // code here.\n string maxi = str;\n helper(str, maxi, k, 0);\n return maxi;\n }" }, { "code": null, "e": 5200, "s": 5198, "text": "0" }, { "code": null, "e": 5222, "s": 5200, "text": "blank551k2 months ago" }, { "code": null, "e": 5975, "s": 5222, "text": "class Solution\n{\n public:\n string s;\n void answer(string curr,int k,int i){\n if(k==0 || i==s.size()){\n if(s<curr){\n s=curr;\n }\n return;\n }\n \n for(int j=i;j<curr.size();++j){\n if(curr[j]<=curr[i] && i!=j){\n continue;\n }\n \n swap(curr[j],curr[i]);\n // saving the swap when i=j;\n if(i==j){\n answer(curr,k,i+1);\n }\n answer(curr,k-1,i+1);\n swap(curr[j],curr[i]);\n }\n return ;\n \n }\n //Function to find the largest number after k swaps.\n string findMaximumNum(string str, int k)\n {\n s=str;\n answer(str,k,0);\n return s;\n }\n};\n" }, { "code": null, "e": 5977, "s": 5975, "text": "0" }, { "code": null, "e": 6009, "s": 5977, "text": "naveenkushawaha20032 months ago" }, { "code": null, "e": 6048, "s": 6009, "text": "//0.0 sec Very Simple Solution........" }, { "code": null, "e": 6907, "s": 6048, "text": "class Solution{ public: //Function to find the largest number after k swaps. string find(int i,string str,int k,int t){if(i>=str.size()||t==k) return str;string str1,str2=str;stack<pair<char,int>>s;char ch=str[i];for(int j=i+1;j<str.size();j++){ if(ch<=str[j]){ //cout<<ch<<\" \"<<str[j]<<endl; while(!s.empty()&&str[j]>s.top().first) s.pop(); s.push(make_pair(str[j],j)); ch=str[j]; }}if(s.empty()==true){ str1=find(i+1,str,k,t); if(str2<str1) str2=str1;}while(!s.empty()){ if(str[i]==s.top().first) str1=find(i+1,str,k,t); else{ swap(str[i],str[s.top().second]); str1=find(i+1,str,k,t+1); swap(str[i],str[s.top().second]);} if(str2<str1) str2=str1; s.pop();}return str2; } string findMaximumNum(string str, int k) { return find(0,str,k,0); }" }, { "code": null, "e": 6910, "s": 6907, "text": "+1" }, { "code": null, "e": 6937, "s": 6910, "text": "thotakurapavan3 months ago" }, { "code": null, "e": 6955, "s": 6937, "text": "java solution ::" }, { "code": null, "e": 7167, "s": 6957, "text": "class Solution{ //Function to find the largest number after k swaps. public static String findMaximumNum(String str, int k) { char[] vals = str.toCharArray(); return findmax(vals, 0 , k); }" }, { "code": null, "e": 7338, "s": 7167, "text": " public static String findmax(char[] vals, int start, int k) { if(0 == k) return String.valueOf(vals); if(start == vals.length) return String.valueOf(vals);" }, { "code": null, "e": 8140, "s": 7338, "text": " char maxVal = vals[start]; for(int i = start+1; i<vals.length; i++) { if(maxVal < vals[i]) { maxVal = vals[i]; } } if(vals[start] == maxVal) { return findmax(vals, start+1, k); } String max = String.valueOf(vals); for(int i = start+1; i<vals.length; i++) { if(Integer.valueOf(maxVal) == Integer.valueOf(vals[i])) { char[] newVal = vals.clone(); char temp = newVal[start]; newVal[start] = newVal[i]; newVal[i] = temp; String newMax = findmax(newVal, start+1, k-1); if(max.compareTo(newMax) < 0) { max = newMax; } } } return max; }}" }, { "code": null, "e": 8143, "s": 8140, "text": "-1" }, { "code": null, "e": 8165, "s": 8143, "text": "2019011223 months ago" }, { "code": null, "e": 8266, "s": 8165, "text": "Why the solution does not get accepted in C++, and shows abort 3 (SIGABRT) error after test case 4 ?" }, { "code": null, "e": 8268, "s": 8266, "text": "0" }, { "code": null, "e": 8291, "s": 8268, "text": "araj2920183 months ago" }, { "code": null, "e": 9067, "s": 8291, "text": "class Solution{ public: //Function to find the largest number after k swaps. void klp(string str,int k,string &maxm,int ctr){ if(k==0){ return ; } int n=str.size(); char maxi=str[ctr]; for(int i=ctr+1;i<n;i++){ if(str[i]>maxi){ maxi=str[i]; } } if(maxi!=str[ctr]){ k--; } for (int j=n-1;j>=ctr;j--){ if(str[j]==maxi){ swap(str[ctr],str[j]); if(str.compare(maxm)>0){ maxm=str; } klp(str,k,maxm,ctr+1); swap(str[ctr],str[j]); } } } string findMaximumNum(string str, int k) { string maxm=\"\"; klp(str,k,maxm,0); return maxm; }};" }, { "code": null, "e": 9213, "s": 9067, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 9249, "s": 9213, "text": " Login to access your submissions. " }, { "code": null, "e": 9259, "s": 9249, "text": "\nProblem\n" }, { "code": null, "e": 9269, "s": 9259, "text": "\nContest\n" }, { "code": null, "e": 9332, "s": 9269, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9480, "s": 9332, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 9688, "s": 9480, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 9794, "s": 9688, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Tutorial on displaying SHAP force plots in Python HTML | by Liam I. | Towards Data Science
Here’s the source code for this tutorial so that you can follow along, and you can just run app.py to see the results. SHAP plots can be very useful for model explainability (see here for a great talk on them). As part of a recent project on displaying a logistic regression of League of Legends data using SHAP (you can see the project web app here and a screenshot below), I struggled to find a way to display SHAP plots on page load without having to save the image first. I was so used to just using SHAP plots in a Jupyter notebook or something like that, but I really wanted to display it on a web app. Since this was a large pain point for me, I wanted to consolidate what I learned and write about it here. I’ll cover some of the pit-falls for me in trying outbase64, plt.savefig(), the issues with these approaches, and I’ll end with the solution using HTML iFrames. To give a visual of the result of this, an example end result is displaying SHAP force plots in a Flask web app: Base64 is a binary-to-text encoding method. Using this, we can define our force_plot and use plt.savefig() to store it in a variable buf which we can later decode to ASCII. It’s not very important in my opinion to understand the functionality, but the result is that your computer will save each individual image and then display it in HTML. This means your img tag’s src variable will have to locate each saved image locally. """Example implementation of XGBoost algorithm and base64 approach to save the SHAP force plot and later display in HTML.If you're doing this in Flask, the ML is in app.py and you pass the SHAP force plot as a *variable* which you can index in your HTML page."""#Train test split#Let's assume you have some X_, y_...Xt, Xv, yt, yv = train_test_split(X_,y_, test_size=0.2, random_state=10)dt = xgb.DMatrix(Xt, label=yt.values, enable_categorical=True)dv = xgb.DMatrix(Xv, label=yv.values)#Tuned hyperparameters via hyperopt Bayesian optimizationparams = { "eta": 0.5, "max_depth": 8, "min_child_weight": 1, "objective": "binary:logistic", "verbosity": 0, "base_score": np.mean(yt), "eval_metric": "logloss", "colsample_bytree": 0.7434869381604485, 'gamma': 1.1053886968419446, 'reg_alpha': 49.0, 'reg_lambda': 0.9997899615065826}#Run modelmodel = xgb.train(params, dt, 35, [(dt, "train"), (dv, "valid")], early_stopping_rounds=5, verbose_eval=35)#SHAP explainer values (NumPy array)explainer = shap.TreeExplainer(model)shap_values = explainer.shap_values(Xv)#The SHAP *force* plot itself (using this method, I think you can #also do Beeswarm plots but I have not tried it)shap_plot = shap.force_plot(explainer.expected_value, shap_values[-1:], features=Xv.iloc[-1:], feature_names=Xv.columns[0:20], matplotlib=True, show=False, plot_cmap=['#77dd77', '#f99191'])#Encode into base64,#Answer inspiration: https://stackoverflow.com/questions/60621103/is-there-a-way-to-render-shap-or-lime-output-from-flask-to-react/60669449#60669449buf = BytesIO()plt.savefig(buf, format = "png", dpi = 150, bbox_inches = 'tight')dataToTake = base64.b64encode(buf.getbuffer()).decode("ascii")return dataToTake#Example HTML integration<img class="xgboost_image" src="data:image/png;base64"> While handy for single-plot generation, this is not workable in a production context as it means you will save each plot. Using plt.savefig() we shorten our effort (Base64 is not entirely necessary), but it’s the same result of having to save each force plot and indexing it as a file in our <img src="wherever_the_plot_is_locally"> tag. #Just using the same XGBoost model from above def shap_plot(ind): explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(Xv) p = shap.force_plot(explainer.expected_value, shap_values[ind], Xv.iloc[[ind]]) plt.savefig('temp.svg') plt.close() return pshap_plot(3) Easier to understand, yes, but again not available in a production context: you are still saving each image. With this approach, we take advantage of HTML iFrames, which can embed our SHAP force_plot into our main HTML. #works in Dash#taken from here: https://stackoverflow.com/questions/54292226/putting-html-output-from-shap-into-the-dash-output-layout-callbackdef _force_plot_html(*args): force_plot = shap.force_plot(*args, matplotlib=False) shap_html = f"<head>{shap.getjs()}</head><body>{force_plot.html()}</body>" return html.Iframe(srcDoc=shap_html, style={"width": "100%", "height": "200px", "border": 0}) This does not exactly translate to what I’m using though, which is Flask. I took the above idea and appropriated it to a Flask context: Let’s assume you have a logistic regression model like this: Xt, Xv, yt, yv = train_test_split(X_, y_, test_size=0.2, random_state=10)model = LogisticRegression(penalty='l2', solver='liblinear', max_iter=900, C=0.1).fit(Xt, yt)explainer = shap.Explainer(model, Xt, feature_names=Xt.columns)shap_values = explainer(Xv) The basic idea is in app.py to create a _force_plot_html function that uses explainer, shap_values, andind input to return a shap_html srcdoc. We will pass that shap_html variable to our HTML using render_template, and in the HTML file itself we will display shap_html in an embedded iFrame. This is an example where we loop through ind, creating various SHAP plots, and displaying them in our HTML as iFrames. #in app.pyfrom flask import *import shapfrom shap.plots._force_matplotlib import draw_additive_plotfrom model import give_shap_plotapp = Flask(__name__)@app.route('/')def displayshap(): explainer, shap_values = give_shap_plot() def _force_plot_html(explainer, shap_values, ind): force_plot = shap.plots.force(shap_values[ind], matplotlib=False) shap_html = f"<head>{shap.getjs()}</head><body>{force_plot.html()}</body>" return shap_html shap_plots = {} for i in range(10): #how many plots you want ind = i shap_plots[i] = _force_plot_html(explainer, shap_values, ind) return render_template('displayshap.html', shap_plots = shap_plots)if __name__ == '__main__': app.run()#EXIT app.py###<!-- HTML --><!-- in displayshap.html -->{% for i in shap_plots: %} <iframe srcdoc="{{shap_plots[i]}}" style={"width": "2000px"; "height": "200px"; border: none;} ></iframe>{% endfor %} The shap.getjs() is really important because without it you will get in your HTML a “Visualization omitted, Javascript library not loaded!’ issue. Some drawbacks of this solution is that it only works for force plots. I was not able to get beeswarm/bar plots like this to work: #TYPES OF PLOTS THAT WORK: force_plot = shap.plots.force(shap_values[ind], matplotlib=False)#TYPES OF PLOTS THAT DO NOT WORK:force_plot = shap.plots.beeswarm(shap_values)force_plot = shap.plots.bar(shap_values[ind])#I think no .html() method is written for these? I'm not quite sure Thank you for reading! I hope this is helpful to anyone wanting to incorporate SHAP into their web application. You can find the source code for this tutorial here. You can find me on my website, LinkedIn, or github. You can read more of my stuff here.
[ { "code": null, "e": 291, "s": 172, "text": "Here’s the source code for this tutorial so that you can follow along, and you can just run app.py to see the results." }, { "code": null, "e": 383, "s": 291, "text": "SHAP plots can be very useful for model explainability (see here for a great talk on them)." }, { "code": null, "e": 781, "s": 383, "text": "As part of a recent project on displaying a logistic regression of League of Legends data using SHAP (you can see the project web app here and a screenshot below), I struggled to find a way to display SHAP plots on page load without having to save the image first. I was so used to just using SHAP plots in a Jupyter notebook or something like that, but I really wanted to display it on a web app." }, { "code": null, "e": 1048, "s": 781, "text": "Since this was a large pain point for me, I wanted to consolidate what I learned and write about it here. I’ll cover some of the pit-falls for me in trying outbase64, plt.savefig(), the issues with these approaches, and I’ll end with the solution using HTML iFrames." }, { "code": null, "e": 1161, "s": 1048, "text": "To give a visual of the result of this, an example end result is displaying SHAP force plots in a Flask web app:" }, { "code": null, "e": 1588, "s": 1161, "text": "Base64 is a binary-to-text encoding method. Using this, we can define our force_plot and use plt.savefig() to store it in a variable buf which we can later decode to ASCII. It’s not very important in my opinion to understand the functionality, but the result is that your computer will save each individual image and then display it in HTML. This means your img tag’s src variable will have to locate each saved image locally." }, { "code": null, "e": 3423, "s": 1588, "text": "\"\"\"Example implementation of XGBoost algorithm and base64 approach to save the SHAP force plot and later display in HTML.If you're doing this in Flask, the ML is in app.py and you pass the SHAP force plot as a *variable* which you can index in your HTML page.\"\"\"#Train test split#Let's assume you have some X_, y_...Xt, Xv, yt, yv = train_test_split(X_,y_, test_size=0.2, random_state=10)dt = xgb.DMatrix(Xt, label=yt.values, enable_categorical=True)dv = xgb.DMatrix(Xv, label=yv.values)#Tuned hyperparameters via hyperopt Bayesian optimizationparams = { \"eta\": 0.5, \"max_depth\": 8, \"min_child_weight\": 1, \"objective\": \"binary:logistic\", \"verbosity\": 0, \"base_score\": np.mean(yt), \"eval_metric\": \"logloss\", \"colsample_bytree\": 0.7434869381604485, 'gamma': 1.1053886968419446, 'reg_alpha': 49.0, 'reg_lambda': 0.9997899615065826}#Run modelmodel = xgb.train(params, dt, 35, [(dt, \"train\"), (dv, \"valid\")], early_stopping_rounds=5, verbose_eval=35)#SHAP explainer values (NumPy array)explainer = shap.TreeExplainer(model)shap_values = explainer.shap_values(Xv)#The SHAP *force* plot itself (using this method, I think you can #also do Beeswarm plots but I have not tried it)shap_plot = shap.force_plot(explainer.expected_value, shap_values[-1:], features=Xv.iloc[-1:], feature_names=Xv.columns[0:20], matplotlib=True, show=False, plot_cmap=['#77dd77', '#f99191'])#Encode into base64,#Answer inspiration: https://stackoverflow.com/questions/60621103/is-there-a-way-to-render-shap-or-lime-output-from-flask-to-react/60669449#60669449buf = BytesIO()plt.savefig(buf, format = \"png\", dpi = 150, bbox_inches = 'tight')dataToTake = base64.b64encode(buf.getbuffer()).decode(\"ascii\")return dataToTake#Example HTML integration<img class=\"xgboost_image\" src=\"data:image/png;base64\">" }, { "code": null, "e": 3545, "s": 3423, "text": "While handy for single-plot generation, this is not workable in a production context as it means you will save each plot." }, { "code": null, "e": 3761, "s": 3545, "text": "Using plt.savefig() we shorten our effort (Base64 is not entirely necessary), but it’s the same result of having to save each force plot and indexing it as a file in our <img src=\"wherever_the_plot_is_locally\"> tag." }, { "code": null, "e": 4061, "s": 3761, "text": "#Just using the same XGBoost model from above def shap_plot(ind): explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(Xv) p = shap.force_plot(explainer.expected_value, shap_values[ind], Xv.iloc[[ind]]) plt.savefig('temp.svg') plt.close() return pshap_plot(3)" }, { "code": null, "e": 4170, "s": 4061, "text": "Easier to understand, yes, but again not available in a production context: you are still saving each image." }, { "code": null, "e": 4281, "s": 4170, "text": "With this approach, we take advantage of HTML iFrames, which can embed our SHAP force_plot into our main HTML." }, { "code": null, "e": 4730, "s": 4281, "text": "#works in Dash#taken from here: https://stackoverflow.com/questions/54292226/putting-html-output-from-shap-into-the-dash-output-layout-callbackdef _force_plot_html(*args): force_plot = shap.force_plot(*args, matplotlib=False) shap_html = f\"<head>{shap.getjs()}</head><body>{force_plot.html()}</body>\" return html.Iframe(srcDoc=shap_html, style={\"width\": \"100%\", \"height\": \"200px\", \"border\": 0})" }, { "code": null, "e": 4866, "s": 4730, "text": "This does not exactly translate to what I’m using though, which is Flask. I took the above idea and appropriated it to a Flask context:" }, { "code": null, "e": 4927, "s": 4866, "text": "Let’s assume you have a logistic regression model like this:" }, { "code": null, "e": 5184, "s": 4927, "text": "Xt, Xv, yt, yv = train_test_split(X_, y_, test_size=0.2, random_state=10)model = LogisticRegression(penalty='l2', solver='liblinear', max_iter=900, C=0.1).fit(Xt, yt)explainer = shap.Explainer(model, Xt, feature_names=Xt.columns)shap_values = explainer(Xv)" }, { "code": null, "e": 5476, "s": 5184, "text": "The basic idea is in app.py to create a _force_plot_html function that uses explainer, shap_values, andind input to return a shap_html srcdoc. We will pass that shap_html variable to our HTML using render_template, and in the HTML file itself we will display shap_html in an embedded iFrame." }, { "code": null, "e": 5595, "s": 5476, "text": "This is an example where we loop through ind, creating various SHAP plots, and displaying them in our HTML as iFrames." }, { "code": null, "e": 6547, "s": 5595, "text": "#in app.pyfrom flask import *import shapfrom shap.plots._force_matplotlib import draw_additive_plotfrom model import give_shap_plotapp = Flask(__name__)@app.route('/')def displayshap(): explainer, shap_values = give_shap_plot() def _force_plot_html(explainer, shap_values, ind): force_plot = shap.plots.force(shap_values[ind], matplotlib=False) shap_html = f\"<head>{shap.getjs()}</head><body>{force_plot.html()}</body>\" return shap_html shap_plots = {} for i in range(10): #how many plots you want ind = i shap_plots[i] = _force_plot_html(explainer, shap_values, ind) return render_template('displayshap.html', shap_plots = shap_plots)if __name__ == '__main__': app.run()#EXIT app.py###<!-- HTML --><!-- in displayshap.html -->{% for i in shap_plots: %} <iframe srcdoc=\"{{shap_plots[i]}}\" style={\"width\": \"2000px\"; \"height\": \"200px\"; border: none;} ></iframe>{% endfor %}" }, { "code": null, "e": 6694, "s": 6547, "text": "The shap.getjs() is really important because without it you will get in your HTML a “Visualization omitted, Javascript library not loaded!’ issue." }, { "code": null, "e": 6765, "s": 6694, "text": "Some drawbacks of this solution is that it only works for force plots." }, { "code": null, "e": 6825, "s": 6765, "text": "I was not able to get beeswarm/bar plots like this to work:" }, { "code": null, "e": 7108, "s": 6825, "text": "#TYPES OF PLOTS THAT WORK: force_plot = shap.plots.force(shap_values[ind], matplotlib=False)#TYPES OF PLOTS THAT DO NOT WORK:force_plot = shap.plots.beeswarm(shap_values)force_plot = shap.plots.bar(shap_values[ind])#I think no .html() method is written for these? I'm not quite sure" }, { "code": null, "e": 7273, "s": 7108, "text": "Thank you for reading! I hope this is helpful to anyone wanting to incorporate SHAP into their web application. You can find the source code for this tutorial here." } ]
How can I check if a string is all uppercase in JavaScript?
You can compare the string against itself in upper case to check if it is in the upper case. function isUpperCase(str) { return str === str.toUpperCase(); } console.log(isUpperCase('a')) console.log(isUpperCase('A')) console.log(isUpperCase('ASDF 123 asd')) console.log(isUpperCase('TEST 123 TEST')) This will give the output − false true false true
[ { "code": null, "e": 1155, "s": 1062, "text": "You can compare the string against itself in upper case to check if it is\nin the upper case." }, { "code": null, "e": 1365, "s": 1155, "text": "function isUpperCase(str) {\n return str === str.toUpperCase();\n}\nconsole.log(isUpperCase('a'))\nconsole.log(isUpperCase('A'))\nconsole.log(isUpperCase('ASDF 123 asd'))\nconsole.log(isUpperCase('TEST 123 TEST'))" }, { "code": null, "e": 1393, "s": 1365, "text": "This will give the output −" }, { "code": null, "e": 1415, "s": 1393, "text": "false\ntrue\nfalse\ntrue" } ]
Divide large number represented as string in C++ Program
In this tutorial, we are going to learn how to divide a large number that is represented as a string. We have given a large number in string format and a divisor. Our program should find a reminder. First, we will find a part of the given number that is greater than the dividend. And then we will add the remaining digits one by one to the divisor. Let's see the steps to solve the problem. Initialize the large number along with a divisor. Initialize the large number along with a divisor. Iterate over the given number until we extract the part that is greater than the divisor. Iterate over the given number until we extract the part that is greater than the divisor. Now, iterate from where we left in the previous step until the end of the number.Divide the extracted part with a divisor and add it to the result.Update the number with the next digit. Now, iterate from where we left in the previous step until the end of the number. Divide the extracted part with a divisor and add it to the result. Divide the extracted part with a divisor and add it to the result. Update the number with the next digit. Update the number with the next digit. Check whether the result is zero or not. Check whether the result is zero or not. And print the result. And print the result. Let's see the code. Live Demo #include <bits/stdc++.h> using namespace std; string divideLargeNumber(string number, int divisor) { // to store the result string result; int index = 0; // extracting the part that is greater than the given divisor int dividend = number[index] - '0'; while (dividend < divisor) { dividend = dividend * 10 + (number[++index] - '0'); } // iterating until all digits participate in the division while (number.size() > index) { result += (dividend / divisor) + '0'; // adding the next digit to the dividend dividend = (dividend % divisor) * 10 + number[++index] - '0'; } if (result.length() == 0) { return "0"; } return result; } int main() { string large_number = "12345678901234567890"; int divisor = 75; cout << divideLargeNumber(large_number, divisor) << endl; return 0; } If you execute the above program, then you will get the following result. 164609052016460905 If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1164, "s": 1062, "text": "In this tutorial, we are going to learn how to divide a large number that is represented as a string." }, { "code": null, "e": 1261, "s": 1164, "text": "We have given a large number in string format and a divisor. Our program should find a reminder." }, { "code": null, "e": 1412, "s": 1261, "text": "First, we will find a part of the given number that is greater than the dividend. And then we will add the remaining digits one by one to the divisor." }, { "code": null, "e": 1454, "s": 1412, "text": "Let's see the steps to solve the problem." }, { "code": null, "e": 1504, "s": 1454, "text": "Initialize the large number along with a divisor." }, { "code": null, "e": 1554, "s": 1504, "text": "Initialize the large number along with a divisor." }, { "code": null, "e": 1644, "s": 1554, "text": "Iterate over the given number until we extract the part that is greater than the divisor." }, { "code": null, "e": 1734, "s": 1644, "text": "Iterate over the given number until we extract the part that is greater than the divisor." }, { "code": null, "e": 1920, "s": 1734, "text": "Now, iterate from where we left in the previous step until the end of the number.Divide the extracted part with a divisor and add it to the result.Update the number with the next digit." }, { "code": null, "e": 2002, "s": 1920, "text": "Now, iterate from where we left in the previous step until the end of the number." }, { "code": null, "e": 2069, "s": 2002, "text": "Divide the extracted part with a divisor and add it to the result." }, { "code": null, "e": 2136, "s": 2069, "text": "Divide the extracted part with a divisor and add it to the result." }, { "code": null, "e": 2175, "s": 2136, "text": "Update the number with the next digit." }, { "code": null, "e": 2214, "s": 2175, "text": "Update the number with the next digit." }, { "code": null, "e": 2255, "s": 2214, "text": "Check whether the result is zero or not." }, { "code": null, "e": 2296, "s": 2255, "text": "Check whether the result is zero or not." }, { "code": null, "e": 2318, "s": 2296, "text": "And print the result." }, { "code": null, "e": 2340, "s": 2318, "text": "And print the result." }, { "code": null, "e": 2360, "s": 2340, "text": "Let's see the code." }, { "code": null, "e": 2371, "s": 2360, "text": " Live Demo" }, { "code": null, "e": 3226, "s": 2371, "text": "#include <bits/stdc++.h>\nusing namespace std;\nstring divideLargeNumber(string number, int divisor) {\n // to store the result\n string result;\n int index = 0;\n // extracting the part that is greater than the given divisor\n int dividend = number[index] - '0';\n while (dividend < divisor) {\n dividend = dividend * 10 + (number[++index] - '0');\n }\n // iterating until all digits participate in the division\n while (number.size() > index) {\n result += (dividend / divisor) + '0';\n // adding the next digit to the dividend\n dividend = (dividend % divisor) * 10 + number[++index] - '0';\n }\n if (result.length() == 0) {\n return \"0\";\n }\n return result;\n}\nint main() {\n string large_number = \"12345678901234567890\";\n int divisor = 75;\n cout << divideLargeNumber(large_number, divisor) << endl;\n return 0;\n}" }, { "code": null, "e": 3300, "s": 3226, "text": "If you execute the above program, then you will get the following result." }, { "code": null, "e": 3319, "s": 3300, "text": "164609052016460905" }, { "code": null, "e": 3397, "s": 3319, "text": "If you have any queries in the tutorial, mention them in the comment section." } ]
Serious Software Development Using Jupyter Notebooks | by Dipam Vasani | Towards Data Science
The image below comes from the documentation page of a library called fastcore. It has the source code hyperlinked so you can easily check the implementation, it has a small pargraph explaning what the function does and, it has tests so you can verify the behavior of the function. Compare this to your regular Github repository with partial or no documentation, no hyperlinks to jump around and tests that exist in a separate folder and you can already see which approach is better. Yes you can have workarounds but nothing will compare to what I am about to show you. Back in 1983, Donald Knuth envisioned a style of programming called literate programming. In this style of programming, you move away from writing computer programs in the manner and order imposed by the computer, and instead enable programmers to develop programs in the order demanded by the logic and flow of their thoughts. source: https://en.wikipedia.org/wiki/Literate_programming The best environment to capture this style of programming is Jupyter notebooks. You can work on bits of code, spell out your thoughts and when you are satisfied, put it all together. They’re great for iterative, experimental style of programming. However, until recently, Jupyter notebooks lacked a lot of additional functionality to build software. It lacked components around it, that when put together, make Jupyter a true literate programming environment. Introducing, nbdev. nbdev is a library developed by fastai to enable development of Python packages using nothing but notebooks. I’m not going to give you a summary of the features because I want you to read along and find out everything in detail. I’m also not doing a code walkthru since fastai already has a really good tutorial on their website so it wouldn’t make sense to repeat the same steps. The goal of this article will be to introduce you to this world, one that you didn’t know existed, get you to love it and get you to use it in your next project. Let’s start by looking at how nbdev works. Since I’m not doing a code-walthru, we will be browsing the source code of a library already built using nbdev known as fastcore. If you go to the Github page of fastcore, you will see that it has a folder called nbs which, as the name suggests, includes a bunch of notebooks. Each notebook represents a module of the package we are building. For example 00_test.ipynb will be converted to a module called test.py. Users of our package can then use it as follows: from fastcore.test import * The conversion from notebook to a .py file is done with the help of a function called notebook2script() which is executed at the end of each notebook. If you open one of the notebooks, you’ll notice that it looks like any regular Jupyter notebook except for a few things. The first thing you’ll notice is a bunch of #export (s) at the start of certain cells. #export is how nbdev determines which cells will become part of the module. From the above code, cell [1] will go into test.py but cell [2] won’t. Cell [2] however, will become part of the documentation for this module. This is my favorite part. Whatever code and explanation you write in your notebook is automatically converted to docs. You don’t need to spend any extra time on it. Also, the fact that we’re able to write tests just below the source code and that they become part of the documentation as well is a hugeeeee bonus. What happens with traditional Python testing modules is that, the tests exist in a different folder. This makes it difficult to identify which tests are related to which functionality. And when you make changes to the source code, it’s difficult to make changes to the relevant tests since they’re not right in front of your eyes. Nbdev solves both these problems for you. Plus anyone reading your code also sees the how the tests are designed and gets a richer learning experience. Finally, notice that the keywords that were in backticks in our markdown, were searched in the code base and if found, hyperlinked as well (see test_eq_type in the above image). This is just incredible. Automating mundane tasks just puts so much more creative power in your hands when developing software. Let’s now look at the feature list of nbdev and I can give you a brief explanation for each feature Automatically generate docs This one I’ve already explained. Utilities to automate publishing to PyPI and conda packages Whenever you do pip install bla , bla has to exist on Python Package Index (PyPI). Similarly for Conda. Publishing to PyPI requires you to package your project in a certain way and create a bunch of files. Nbdev makes this process really simple by automating tasks and providing utilities to help you publish without any hassle. Two-way sync between notebooks and source code IDEs are useful for a lot of tasks, for example, they provide better tools for debugging. With nbdev, you can edit the source code (.py file) as well and the changes will reflect in your notebook. This allows you to use the best features of both mediums. Fine-grained control on hiding/showing cells Complete Jupyter notebooks are converted to documentation, but you can hide certain cells if you want. Just like #export , nbdev includes a #hide keyword. Put it on top of any cell and it won’t occur in the generated documentation. Write tests directly in notebooks I mentioned you can do this, but did I mention that you can run these tests via CLI just like you do with pytest. You can also group them if you don’t want to run the long running ones everytime. Merge/conflict resolution One of the problems with Jupyter notebooks is that version control does not work well with it. Git often gives merge conflicts and Github’s visual diff shows changes to the underlying json of a Jupyter notebook instead of the actual cell changes. This is annoying. Well, let nbdev handle it for you. It cleans up notebooks to avoid these conflicts and if they do occur, gives you a human readable format of the error. Continuous integration (CI) comes setup for you with GitHub Actions Github Actions allows you to automate workflows like what happens when you push a new change or a new issue is created or a PR is raised. nbdev sets this up for you without any manual intervention required. All the features of Markdown Now that we’re using Markdown for documentation, we can easily include images, formatted text and even math equations very easily. ...and much more At this point I would suggest you to go through the tutorial and learn more about the parts that excite you. There is a very famous talk by Joel Grus called “I don’t like notebooks”. Joel is an excellent presenter and his talk is really funny, but it discourages people from using notebooks for serious development. Now, the talk is really old, some of the stuff that exists now, didn’t exist back then. But still, there is a general consensus among professionals that Jupyter notebooks are just for experimentation and if you want to write serious software that will be deployed, you have to use IDEs. That’s no longer the case. With this article, I hope to change that. I hope you give this other side a try, I hope that more people do serious software development using Jupyter notebooks.
[ { "code": null, "e": 127, "s": 47, "text": "The image below comes from the documentation page of a library called fastcore." }, { "code": null, "e": 329, "s": 127, "text": "It has the source code hyperlinked so you can easily check the implementation, it has a small pargraph explaning what the function does and, it has tests so you can verify the behavior of the function." }, { "code": null, "e": 531, "s": 329, "text": "Compare this to your regular Github repository with partial or no documentation, no hyperlinks to jump around and tests that exist in a separate folder and you can already see which approach is better." }, { "code": null, "e": 617, "s": 531, "text": "Yes you can have workarounds but nothing will compare to what I am about to show you." }, { "code": null, "e": 945, "s": 617, "text": "Back in 1983, Donald Knuth envisioned a style of programming called literate programming. In this style of programming, you move away from writing computer programs in the manner and order imposed by the computer, and instead enable programmers to develop programs in the order demanded by the logic and flow of their thoughts." }, { "code": null, "e": 1004, "s": 945, "text": "source: https://en.wikipedia.org/wiki/Literate_programming" }, { "code": null, "e": 1251, "s": 1004, "text": "The best environment to capture this style of programming is Jupyter notebooks. You can work on bits of code, spell out your thoughts and when you are satisfied, put it all together. They’re great for iterative, experimental style of programming." }, { "code": null, "e": 1464, "s": 1251, "text": "However, until recently, Jupyter notebooks lacked a lot of additional functionality to build software. It lacked components around it, that when put together, make Jupyter a true literate programming environment." }, { "code": null, "e": 1484, "s": 1464, "text": "Introducing, nbdev." }, { "code": null, "e": 1865, "s": 1484, "text": "nbdev is a library developed by fastai to enable development of Python packages using nothing but notebooks. I’m not going to give you a summary of the features because I want you to read along and find out everything in detail. I’m also not doing a code walkthru since fastai already has a really good tutorial on their website so it wouldn’t make sense to repeat the same steps." }, { "code": null, "e": 2027, "s": 1865, "text": "The goal of this article will be to introduce you to this world, one that you didn’t know existed, get you to love it and get you to use it in your next project." }, { "code": null, "e": 2200, "s": 2027, "text": "Let’s start by looking at how nbdev works. Since I’m not doing a code-walthru, we will be browsing the source code of a library already built using nbdev known as fastcore." }, { "code": null, "e": 2347, "s": 2200, "text": "If you go to the Github page of fastcore, you will see that it has a folder called nbs which, as the name suggests, includes a bunch of notebooks." }, { "code": null, "e": 2485, "s": 2347, "text": "Each notebook represents a module of the package we are building. For example 00_test.ipynb will be converted to a module called test.py." }, { "code": null, "e": 2534, "s": 2485, "text": "Users of our package can then use it as follows:" }, { "code": null, "e": 2562, "s": 2534, "text": "from fastcore.test import *" }, { "code": null, "e": 2713, "s": 2562, "text": "The conversion from notebook to a .py file is done with the help of a function called notebook2script() which is executed at the end of each notebook." }, { "code": null, "e": 2834, "s": 2713, "text": "If you open one of the notebooks, you’ll notice that it looks like any regular Jupyter notebook except for a few things." }, { "code": null, "e": 2921, "s": 2834, "text": "The first thing you’ll notice is a bunch of #export (s) at the start of certain cells." }, { "code": null, "e": 3068, "s": 2921, "text": "#export is how nbdev determines which cells will become part of the module. From the above code, cell [1] will go into test.py but cell [2] won’t." }, { "code": null, "e": 3141, "s": 3068, "text": "Cell [2] however, will become part of the documentation for this module." }, { "code": null, "e": 3455, "s": 3141, "text": "This is my favorite part. Whatever code and explanation you write in your notebook is automatically converted to docs. You don’t need to spend any extra time on it. Also, the fact that we’re able to write tests just below the source code and that they become part of the documentation as well is a hugeeeee bonus." }, { "code": null, "e": 3786, "s": 3455, "text": "What happens with traditional Python testing modules is that, the tests exist in a different folder. This makes it difficult to identify which tests are related to which functionality. And when you make changes to the source code, it’s difficult to make changes to the relevant tests since they’re not right in front of your eyes." }, { "code": null, "e": 3938, "s": 3786, "text": "Nbdev solves both these problems for you. Plus anyone reading your code also sees the how the tests are designed and gets a richer learning experience." }, { "code": null, "e": 4244, "s": 3938, "text": "Finally, notice that the keywords that were in backticks in our markdown, were searched in the code base and if found, hyperlinked as well (see test_eq_type in the above image). This is just incredible. Automating mundane tasks just puts so much more creative power in your hands when developing software." }, { "code": null, "e": 4344, "s": 4244, "text": "Let’s now look at the feature list of nbdev and I can give you a brief explanation for each feature" }, { "code": null, "e": 4372, "s": 4344, "text": "Automatically generate docs" }, { "code": null, "e": 4405, "s": 4372, "text": "This one I’ve already explained." }, { "code": null, "e": 4465, "s": 4405, "text": "Utilities to automate publishing to PyPI and conda packages" }, { "code": null, "e": 4794, "s": 4465, "text": "Whenever you do pip install bla , bla has to exist on Python Package Index (PyPI). Similarly for Conda. Publishing to PyPI requires you to package your project in a certain way and create a bunch of files. Nbdev makes this process really simple by automating tasks and providing utilities to help you publish without any hassle." }, { "code": null, "e": 4841, "s": 4794, "text": "Two-way sync between notebooks and source code" }, { "code": null, "e": 5096, "s": 4841, "text": "IDEs are useful for a lot of tasks, for example, they provide better tools for debugging. With nbdev, you can edit the source code (.py file) as well and the changes will reflect in your notebook. This allows you to use the best features of both mediums." }, { "code": null, "e": 5141, "s": 5096, "text": "Fine-grained control on hiding/showing cells" }, { "code": null, "e": 5373, "s": 5141, "text": "Complete Jupyter notebooks are converted to documentation, but you can hide certain cells if you want. Just like #export , nbdev includes a #hide keyword. Put it on top of any cell and it won’t occur in the generated documentation." }, { "code": null, "e": 5407, "s": 5373, "text": "Write tests directly in notebooks" }, { "code": null, "e": 5603, "s": 5407, "text": "I mentioned you can do this, but did I mention that you can run these tests via CLI just like you do with pytest. You can also group them if you don’t want to run the long running ones everytime." }, { "code": null, "e": 5629, "s": 5603, "text": "Merge/conflict resolution" }, { "code": null, "e": 6047, "s": 5629, "text": "One of the problems with Jupyter notebooks is that version control does not work well with it. Git often gives merge conflicts and Github’s visual diff shows changes to the underlying json of a Jupyter notebook instead of the actual cell changes. This is annoying. Well, let nbdev handle it for you. It cleans up notebooks to avoid these conflicts and if they do occur, gives you a human readable format of the error." }, { "code": null, "e": 6115, "s": 6047, "text": "Continuous integration (CI) comes setup for you with GitHub Actions" }, { "code": null, "e": 6322, "s": 6115, "text": "Github Actions allows you to automate workflows like what happens when you push a new change or a new issue is created or a PR is raised. nbdev sets this up for you without any manual intervention required." }, { "code": null, "e": 6351, "s": 6322, "text": "All the features of Markdown" }, { "code": null, "e": 6482, "s": 6351, "text": "Now that we’re using Markdown for documentation, we can easily include images, formatted text and even math equations very easily." }, { "code": null, "e": 6499, "s": 6482, "text": "...and much more" }, { "code": null, "e": 6608, "s": 6499, "text": "At this point I would suggest you to go through the tutorial and learn more about the parts that excite you." }, { "code": null, "e": 6815, "s": 6608, "text": "There is a very famous talk by Joel Grus called “I don’t like notebooks”. Joel is an excellent presenter and his talk is really funny, but it discourages people from using notebooks for serious development." }, { "code": null, "e": 7129, "s": 6815, "text": "Now, the talk is really old, some of the stuff that exists now, didn’t exist back then. But still, there is a general consensus among professionals that Jupyter notebooks are just for experimentation and if you want to write serious software that will be deployed, you have to use IDEs. That’s no longer the case." } ]
Perl | split() Function
23 Jun, 2020 split() is a string function in Perl which is used to split or you can say to cut a string into smaller sections or pieces. There are different criteria to split a string, like on a single character, a regular expression(pattern), a group of characters or on undefined value etc.. The best thing about this function that user can specify how many sections to split the string into. Syntax: split /Pattern/, Expression, Limit or split /Pattern/, Expression or split /Pattern/ or Split In the above syntax, Pattern is specified a regular expression which provides the criteria to split the string. The Expression is the string which is to be split. The Limit is kind of restriction which stops the splitting at (n-1)th pattern found in the string. Return Value: This method returns the value in two context as follows: In Array Context: Here it returns a list of the fields which found in Expression. If no Expression is specified then it returns $_. In Scalar Context: Here it returns the number of fields which found in Expression and then stored the fields in the @_ array. There are different ways to use split() Function as follows: Splitting on a Character Splitting among a String without Limit Splitting among a String with Limit Splitting on a Undefined value Splitting on a Regex(Pattern) Splitting on Hash Splitting on Space User can break or split the string on different characters like comma(,) backslash(\) etc. This type of splitting is generally used when you have to parse the data from another program or a file. Don’t use split() to parse the CSV(comma separated value) files. If there are commas in your data then use Text::CSV instead. Example: # Perl program to demonstrate the splitting on character #!/usr/bin/perluse strict;use warnings; # Here character is comma(, )my $str = 'Geeks, for, Geeks'; # using split() functionmy @spl = split(', ', $str); # displaying result using foreach loopforeach my $i (@spl) { print "$i";} GeeksforGeeks This also works same as the splitting on the character. Here string’s data is separated by two !!. Example: # Perl program to demonstrate the# splitting among string without Limit #!/usr/bin/perluse strict;use warnings; # string which is separated by !! signmy $str = 'GFG!!Geeks!!55!!GeeksforGeeks'; # using split function without Limitmy @spl = split('!!', $str); # displaying string after splittingforeach my $i (@spl) { print "$i\n";} GFG Geeks 55 GeeksforGeeks This also works same as the splitting on the character. Here string’s data is separated by two !!. Here the user can restrict the number of sections the string will split into by passing the third argument in split function which will be a positive integer value. In below example user pass the Limit as 3 so it will restrict the splitting of the string into 3, even there are the 4 occurrences of !! in the string. Example: # Perl program to demonstrate the # splitting on string with Limit #!/usr/bin/perluse strict;use warnings; # string which is separated by !! signmy $str = 'GFG!!Geeks!!55!!GeeksforGeeks'; # using split function with Limitmy @spl = split('!!', $str, 3); # displaying string after splittingforeach my $i (@spl) { print "$i\n";} GFG Geeks 55!!GeeksforGeeks If the user will try to split on an undefined value, then the string will split on every character. Example: # Perl program to demonstrate the # splitting on undefined value #!/usr/bin/perluse strict;use warnings; # string to be splitmy $str = 'GeeksforGeeks GFG'; # using split functionmy @spl = split(undef, $str); # displaying string after splittingforeach my $i (@spl) { print "$i\n";} Output: G e e k s f o r G e e k s G F G Runtime Error: Use of uninitialized value in regexp compilation at /home/38ececda726bcb7e68fb7b41eee5b8d9.pl line 12. Sometimes user may want to split the string on a pattern(regex) or a particular type of character. Here we will use the special character classes to make pattern of digits(integer) as follows: Example: # Perl program to demonstrate the # splitting on a pattern(regex) #!/usr/bin/perluse strict;use warnings; # string to be splitmy $str = 'Geeks1for2Geeks'; # using split function# \d+ will match one or more# integer numbers & placed # between two //my @spl = split(/\d+/, $str); # displaying string after splittingforeach my $i (@spl) { print "$i\n";} Geeks for Geeks A user can split the data or string into the hash instead of an array. Basically, a hash is a key/value pair. Before splitting user must have knowledge about the hashes. Example: # Perl program to demonstrate the # splitting into the hash #!/usr/bin/perluse strict;use warnings; # hash to be splitmy $has = 'GFG=1;GEEKS=2;PROGEEK=3'; # using split functionmy %spl = split(/[=;]/, $has); # after splitting displaying the valuesforeach my $i (keys %spl) { print "$i:$spl{$i}\n";} GFG:1 GEEKS:2 PROGEEK:3 Here space doesn’t mean only ‘ ‘ this space but it also includes the newline, tabs etc. Example: # Perl program to demonstrate the # splitting on space #!/usr/bin/perluse strict;use warnings; # string to be splittedmy $str = "ProGeek\n\nSudo\nPlacements"; # using split functionmy @spl = split(' ', $str); # Displaying result by printing# 'GFG' either side of the # value, so that user can see # where it splitforeach my $i (@spl){ print "GFG${i}GFG\n";} GFGProGeekGFG GFGSudoGFG GFGPlacementsGFG As split() function also returns the value in scalar context. So for storing the return values user have to define some scalar values according to the number of sections of splitting. In below example there will be 4 values after splitting so here user will define the 4 scalars values and store the return values.Example:# Perl program to demonstrate the # splitting on string and storing # values in scalars #!/usr/bin/perluse strict;use warnings; # string which is separated by !! signmy $str = 'GFG!Sudo!GeeksforGeeks!ProGeek'; # using split function and # storing values in scalarsmy ($sc1, $sc2, $sc3, $sc4) = split('!', $str); # displaying string after splittingprint "$sc1\n$sc2\n$sc3\n$sc4";Output:GFG Sudo GeeksforGeeks ProGeek Example: # Perl program to demonstrate the # splitting on string and storing # values in scalars #!/usr/bin/perluse strict;use warnings; # string which is separated by !! signmy $str = 'GFG!Sudo!GeeksforGeeks!ProGeek'; # using split function and # storing values in scalarsmy ($sc1, $sc2, $sc3, $sc4) = split('!', $str); # displaying string after splittingprint "$sc1\n$sc2\n$sc3\n$sc4"; GFG Sudo GeeksforGeeks ProGeek There may be a situation when user don’t pass in a string to split, then by default split() function will use the $_ and if user don’t pass a Expression i.e. the string to split on then it will use ‘ ‘(a space).Example:# Perl program to demonstrate the # split() function and context #!/usr/bin/perluse strict;use warnings; # using foreach loop containing string valuesforeach ('G F G', 'Geeks for Geeks'){ # using split() function my @spl = split; # displaying values to be split print "Split $_:\n"; foreach my $i (@spl) { print " $i\n"; }}Output:Split G F G: G F G Split Geeks for Geeks: Geeks for Geeks Example: # Perl program to demonstrate the # split() function and context #!/usr/bin/perluse strict;use warnings; # using foreach loop containing string valuesforeach ('G F G', 'Geeks for Geeks'){ # using split() function my @spl = split; # displaying values to be split print "Split $_:\n"; foreach my $i (@spl) { print " $i\n"; }} Split G F G: G F G Split Geeks for Geeks: Geeks for Geeks If the delimiter is present at the starting of the string which is to be split, then the first element of return values will be empty and that will store into the array. In below example we have this situation and we are printing the empty value of resulted array:Example:# Perl program to demonstrate the # split() function with the Delimiter# at the start of the string #!/usr/bin/perluse strict;use warnings; # string containing delimiter(, ) # at the starting my $str = ', GFG, Geeks'; # using split functionmy @spl = split(', ', $str); # printing "Array_Element: " with each # returned value so that you can see# the empty oneforeach my $i (@spl) { print "Array_Element: $i\n";}Output:Array_Element: Array_Element: GFG Array_Element: Geeks Example: # Perl program to demonstrate the # split() function with the Delimiter# at the start of the string #!/usr/bin/perluse strict;use warnings; # string containing delimiter(, ) # at the starting my $str = ', GFG, Geeks'; # using split functionmy @spl = split(', ', $str); # printing "Array_Element: " with each # returned value so that you can see# the empty oneforeach my $i (@spl) { print "Array_Element: $i\n";} Array_Element: Array_Element: GFG Array_Element: Geeks If you want to keep the delimiter in result also then simply put that delimiter inside the parentheses.Example:# Perl program to demonstrate the # split() function and keeping # the delimiter #!/usr/bin/perluse strict;use warnings; # string to be splitmy $str = 'Geeks1for2Geeks'; # using split function# \d+ will match one or more# integer numbers & placed # between two // and () to # keep the delimiter in resultmy @spl = split(/(\d+)/, $str); # displaying string after splittingforeach my $i (@spl) { print "$i\n";}Output:Geeks 1 for 2 Geeks Example: # Perl program to demonstrate the # split() function and keeping # the delimiter #!/usr/bin/perluse strict;use warnings; # string to be splitmy $str = 'Geeks1for2Geeks'; # using split function# \d+ will match one or more# integer numbers & placed # between two // and () to # keep the delimiter in resultmy @spl = split(/(\d+)/, $str); # displaying string after splittingforeach my $i (@spl) { print "$i\n";} Geeks 1 for 2 Geeks nidhi_biet Perl-function Perl-method Perl-String Perl-String-Functions Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays Perl Tutorial - Learn Perl With Examples Perl | Boolean Values Perl | length() Function Perl | Subroutines or Functions Perl | ne operator Use of print() and say() in Perl Hello World Program in Perl Perl | Basic Syntax of a Perl Program Perl | eq operator
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2020" }, { "code": null, "e": 410, "s": 28, "text": "split() is a string function in Perl which is used to split or you can say to cut a string into smaller sections or pieces. There are different criteria to split a string, like on a single character, a regular expression(pattern), a group of characters or on undefined value etc.. The best thing about this function that user can specify how many sections to split the string into." }, { "code": null, "e": 418, "s": 410, "text": "Syntax:" }, { "code": null, "e": 519, "s": 418, "text": "split /Pattern/, Expression, Limit\n\nor\n\nsplit /Pattern/, Expression\n\nor\n\nsplit /Pattern/\n\nor\n\nSplit\n" }, { "code": null, "e": 781, "s": 519, "text": "In the above syntax, Pattern is specified a regular expression which provides the criteria to split the string. The Expression is the string which is to be split. The Limit is kind of restriction which stops the splitting at (n-1)th pattern found in the string." }, { "code": null, "e": 852, "s": 781, "text": "Return Value: This method returns the value in two context as follows:" }, { "code": null, "e": 984, "s": 852, "text": "In Array Context: Here it returns a list of the fields which found in Expression. If no Expression is specified then it returns $_." }, { "code": null, "e": 1110, "s": 984, "text": "In Scalar Context: Here it returns the number of fields which found in Expression and then stored the fields in the @_ array." }, { "code": null, "e": 1171, "s": 1110, "text": "There are different ways to use split() Function as follows:" }, { "code": null, "e": 1196, "s": 1171, "text": "Splitting on a Character" }, { "code": null, "e": 1235, "s": 1196, "text": "Splitting among a String without Limit" }, { "code": null, "e": 1271, "s": 1235, "text": "Splitting among a String with Limit" }, { "code": null, "e": 1302, "s": 1271, "text": "Splitting on a Undefined value" }, { "code": null, "e": 1332, "s": 1302, "text": "Splitting on a Regex(Pattern)" }, { "code": null, "e": 1350, "s": 1332, "text": "Splitting on Hash" }, { "code": null, "e": 1369, "s": 1350, "text": "Splitting on Space" }, { "code": null, "e": 1691, "s": 1369, "text": "User can break or split the string on different characters like comma(,) backslash(\\) etc. This type of splitting is generally used when you have to parse the data from another program or a file. Don’t use split() to parse the CSV(comma separated value) files. If there are commas in your data then use Text::CSV instead." }, { "code": null, "e": 1700, "s": 1691, "text": "Example:" }, { "code": "# Perl program to demonstrate the splitting on character #!/usr/bin/perluse strict;use warnings; # Here character is comma(, )my $str = 'Geeks, for, Geeks'; # using split() functionmy @spl = split(', ', $str); # displaying result using foreach loopforeach my $i (@spl) { print \"$i\";}", "e": 1991, "s": 1700, "text": null }, { "code": null, "e": 2006, "s": 1991, "text": "GeeksforGeeks\n" }, { "code": null, "e": 2105, "s": 2006, "text": "This also works same as the splitting on the character. Here string’s data is separated by two !!." }, { "code": null, "e": 2114, "s": 2105, "text": "Example:" }, { "code": "# Perl program to demonstrate the# splitting among string without Limit #!/usr/bin/perluse strict;use warnings; # string which is separated by !! signmy $str = 'GFG!!Geeks!!55!!GeeksforGeeks'; # using split function without Limitmy @spl = split('!!', $str); # displaying string after splittingforeach my $i (@spl) { print \"$i\\n\";}", "e": 2452, "s": 2114, "text": null }, { "code": null, "e": 2480, "s": 2452, "text": "GFG\nGeeks\n55\nGeeksforGeeks\n" }, { "code": null, "e": 2896, "s": 2480, "text": "This also works same as the splitting on the character. Here string’s data is separated by two !!. Here the user can restrict the number of sections the string will split into by passing the third argument in split function which will be a positive integer value. In below example user pass the Limit as 3 so it will restrict the splitting of the string into 3, even there are the 4 occurrences of !! in the string." }, { "code": null, "e": 2905, "s": 2896, "text": "Example:" }, { "code": "# Perl program to demonstrate the # splitting on string with Limit #!/usr/bin/perluse strict;use warnings; # string which is separated by !! signmy $str = 'GFG!!Geeks!!55!!GeeksforGeeks'; # using split function with Limitmy @spl = split('!!', $str, 3); # displaying string after splittingforeach my $i (@spl) { print \"$i\\n\";}", "e": 3238, "s": 2905, "text": null }, { "code": null, "e": 3267, "s": 3238, "text": "GFG\nGeeks\n55!!GeeksforGeeks\n" }, { "code": null, "e": 3367, "s": 3267, "text": "If the user will try to split on an undefined value, then the string will split on every character." }, { "code": null, "e": 3376, "s": 3367, "text": "Example:" }, { "code": "# Perl program to demonstrate the # splitting on undefined value #!/usr/bin/perluse strict;use warnings; # string to be splitmy $str = 'GeeksforGeeks GFG'; # using split functionmy @spl = split(undef, $str); # displaying string after splittingforeach my $i (@spl) { print \"$i\\n\";}", "e": 3664, "s": 3376, "text": null }, { "code": null, "e": 3672, "s": 3664, "text": "Output:" }, { "code": null, "e": 3707, "s": 3672, "text": "G\ne\ne\nk\ns\nf\no\nr\nG\ne\ne\nk\ns\n \nG\nF\nG\n" }, { "code": null, "e": 3722, "s": 3707, "text": "Runtime Error:" }, { "code": null, "e": 3825, "s": 3722, "text": "Use of uninitialized value in regexp compilation at /home/38ececda726bcb7e68fb7b41eee5b8d9.pl line 12." }, { "code": null, "e": 4018, "s": 3825, "text": "Sometimes user may want to split the string on a pattern(regex) or a particular type of character. Here we will use the special character classes to make pattern of digits(integer) as follows:" }, { "code": null, "e": 4027, "s": 4018, "text": "Example:" }, { "code": "# Perl program to demonstrate the # splitting on a pattern(regex) #!/usr/bin/perluse strict;use warnings; # string to be splitmy $str = 'Geeks1for2Geeks'; # using split function# \\d+ will match one or more# integer numbers & placed # between two //my @spl = split(/\\d+/, $str); # displaying string after splittingforeach my $i (@spl) { print \"$i\\n\";}", "e": 4385, "s": 4027, "text": null }, { "code": null, "e": 4402, "s": 4385, "text": "Geeks\nfor\nGeeks\n" }, { "code": null, "e": 4572, "s": 4402, "text": "A user can split the data or string into the hash instead of an array. Basically, a hash is a key/value pair. Before splitting user must have knowledge about the hashes." }, { "code": null, "e": 4581, "s": 4572, "text": "Example:" }, { "code": "# Perl program to demonstrate the # splitting into the hash #!/usr/bin/perluse strict;use warnings; # hash to be splitmy $has = 'GFG=1;GEEKS=2;PROGEEK=3'; # using split functionmy %spl = split(/[=;]/, $has); # after splitting displaying the valuesforeach my $i (keys %spl) { print \"$i:$spl{$i}\\n\";}", "e": 4887, "s": 4581, "text": null }, { "code": null, "e": 4912, "s": 4887, "text": "GFG:1\nGEEKS:2\nPROGEEK:3\n" }, { "code": null, "e": 5000, "s": 4912, "text": "Here space doesn’t mean only ‘ ‘ this space but it also includes the newline, tabs etc." }, { "code": null, "e": 5009, "s": 5000, "text": "Example:" }, { "code": "# Perl program to demonstrate the # splitting on space #!/usr/bin/perluse strict;use warnings; # string to be splittedmy $str = \"ProGeek\\n\\nSudo\\nPlacements\"; # using split functionmy @spl = split(' ', $str); # Displaying result by printing# 'GFG' either side of the # value, so that user can see # where it splitforeach my $i (@spl){ print \"GFG${i}GFG\\n\";}", "e": 5374, "s": 5009, "text": null }, { "code": null, "e": 5417, "s": 5374, "text": "GFGProGeekGFG\nGFGSudoGFG\nGFGPlacementsGFG\n" }, { "code": null, "e": 6160, "s": 5417, "text": "As split() function also returns the value in scalar context. So for storing the return values user have to define some scalar values according to the number of sections of splitting. In below example there will be 4 values after splitting so here user will define the 4 scalars values and store the return values.Example:# Perl program to demonstrate the # splitting on string and storing # values in scalars #!/usr/bin/perluse strict;use warnings; # string which is separated by !! signmy $str = 'GFG!Sudo!GeeksforGeeks!ProGeek'; # using split function and # storing values in scalarsmy ($sc1, $sc2, $sc3, $sc4) = split('!', $str); # displaying string after splittingprint \"$sc1\\n$sc2\\n$sc3\\n$sc4\";Output:GFG\nSudo\nGeeksforGeeks\nProGeek\n" }, { "code": null, "e": 6169, "s": 6160, "text": "Example:" }, { "code": "# Perl program to demonstrate the # splitting on string and storing # values in scalars #!/usr/bin/perluse strict;use warnings; # string which is separated by !! signmy $str = 'GFG!Sudo!GeeksforGeeks!ProGeek'; # using split function and # storing values in scalarsmy ($sc1, $sc2, $sc3, $sc4) = split('!', $str); # displaying string after splittingprint \"$sc1\\n$sc2\\n$sc3\\n$sc4\";", "e": 6552, "s": 6169, "text": null }, { "code": null, "e": 6584, "s": 6552, "text": "GFG\nSudo\nGeeksforGeeks\nProGeek\n" }, { "code": null, "e": 7240, "s": 6584, "text": "There may be a situation when user don’t pass in a string to split, then by default split() function will use the $_ and if user don’t pass a Expression i.e. the string to split on then it will use ‘ ‘(a space).Example:# Perl program to demonstrate the # split() function and context #!/usr/bin/perluse strict;use warnings; # using foreach loop containing string valuesforeach ('G F G', 'Geeks for Geeks'){ # using split() function my @spl = split; # displaying values to be split print \"Split $_:\\n\"; foreach my $i (@spl) { print \" $i\\n\"; }}Output:Split G F G:\n G\n F\n G\nSplit Geeks for Geeks:\n Geeks\n for\n Geeks\n" }, { "code": null, "e": 7249, "s": 7240, "text": "Example:" }, { "code": "# Perl program to demonstrate the # split() function and context #!/usr/bin/perluse strict;use warnings; # using foreach loop containing string valuesforeach ('G F G', 'Geeks for Geeks'){ # using split() function my @spl = split; # displaying values to be split print \"Split $_:\\n\"; foreach my $i (@spl) { print \" $i\\n\"; }}", "e": 7615, "s": 7249, "text": null }, { "code": null, "e": 7680, "s": 7615, "text": "Split G F G:\n G\n F\n G\nSplit Geeks for Geeks:\n Geeks\n for\n Geeks\n" }, { "code": null, "e": 8434, "s": 7680, "text": "If the delimiter is present at the starting of the string which is to be split, then the first element of return values will be empty and that will store into the array. In below example we have this situation and we are printing the empty value of resulted array:Example:# Perl program to demonstrate the # split() function with the Delimiter# at the start of the string #!/usr/bin/perluse strict;use warnings; # string containing delimiter(, ) # at the starting my $str = ', GFG, Geeks'; # using split functionmy @spl = split(', ', $str); # printing \"Array_Element: \" with each # returned value so that you can see# the empty oneforeach my $i (@spl) { print \"Array_Element: $i\\n\";}Output:Array_Element: \nArray_Element: GFG\nArray_Element: Geeks\n" }, { "code": null, "e": 8443, "s": 8434, "text": "Example:" }, { "code": "# Perl program to demonstrate the # split() function with the Delimiter# at the start of the string #!/usr/bin/perluse strict;use warnings; # string containing delimiter(, ) # at the starting my $str = ', GFG, Geeks'; # using split functionmy @spl = split(', ', $str); # printing \"Array_Element: \" with each # returned value so that you can see# the empty oneforeach my $i (@spl) { print \"Array_Element: $i\\n\";}", "e": 8862, "s": 8443, "text": null }, { "code": null, "e": 8919, "s": 8862, "text": "Array_Element: \nArray_Element: GFG\nArray_Element: Geeks\n" }, { "code": null, "e": 9473, "s": 8919, "text": "If you want to keep the delimiter in result also then simply put that delimiter inside the parentheses.Example:# Perl program to demonstrate the # split() function and keeping # the delimiter #!/usr/bin/perluse strict;use warnings; # string to be splitmy $str = 'Geeks1for2Geeks'; # using split function# \\d+ will match one or more# integer numbers & placed # between two // and () to # keep the delimiter in resultmy @spl = split(/(\\d+)/, $str); # displaying string after splittingforeach my $i (@spl) { print \"$i\\n\";}Output:Geeks\n1\nfor\n2\nGeeks\n" }, { "code": null, "e": 9482, "s": 9473, "text": "Example:" }, { "code": "# Perl program to demonstrate the # split() function and keeping # the delimiter #!/usr/bin/perluse strict;use warnings; # string to be splitmy $str = 'Geeks1for2Geeks'; # using split function# \\d+ will match one or more# integer numbers & placed # between two // and () to # keep the delimiter in resultmy @spl = split(/(\\d+)/, $str); # displaying string after splittingforeach my $i (@spl) { print \"$i\\n\";}", "e": 9898, "s": 9482, "text": null }, { "code": null, "e": 9919, "s": 9898, "text": "Geeks\n1\nfor\n2\nGeeks\n" }, { "code": null, "e": 9930, "s": 9919, "text": "nidhi_biet" }, { "code": null, "e": 9944, "s": 9930, "text": "Perl-function" }, { "code": null, "e": 9956, "s": 9944, "text": "Perl-method" }, { "code": null, "e": 9968, "s": 9956, "text": "Perl-String" }, { "code": null, "e": 9990, "s": 9968, "text": "Perl-String-Functions" }, { "code": null, "e": 9995, "s": 9990, "text": "Perl" }, { "code": null, "e": 10000, "s": 9995, "text": "Perl" }, { "code": null, "e": 10098, "s": 10000, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10112, "s": 10098, "text": "Perl | Arrays" }, { "code": null, "e": 10153, "s": 10112, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 10175, "s": 10153, "text": "Perl | Boolean Values" }, { "code": null, "e": 10200, "s": 10175, "text": "Perl | length() Function" }, { "code": null, "e": 10232, "s": 10200, "text": "Perl | Subroutines or Functions" }, { "code": null, "e": 10251, "s": 10232, "text": "Perl | ne operator" }, { "code": null, "e": 10284, "s": 10251, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 10312, "s": 10284, "text": "Hello World Program in Perl" }, { "code": null, "e": 10350, "s": 10312, "text": "Perl | Basic Syntax of a Perl Program" } ]
Print the string after the specified character has occurred given no. of times
16 Jun, 2022 Given a string, a character, and a count, the task is to print the string after the specified character has occurred count number of times. Print “Empty string” in case of any unsatisfying conditions. (Given character is not present, or present but less than given count, or given count completes on last index). If given count is 0, then given character doesn’t matter, just print the whole string.Examples: Input : str = "This is demo string" char = i, count = 3 Output : ng Input : str = "geeksforgeeks" char = e, count = 2 Output : ksforgeeks Asked in: Oracle Implementation: 1- Start traversing the string. Increment occ_count if current char is equal to given char. Get out of the loop, if occ_count becomes equal to given count. 2- Print the string after the index till the string gets traversed in the loop. 3- If index has reached the last, then print “Empty string”. C++ Java Python3 C# Javascript // C++ program for above implementation#include <iostream>using namespace std; // Function to print the stringvoid printString(string str, char ch, int count){ int occ = 0, i; // If given count is 0 // print the given string and return if (count == 0) { cout << str; return; } // Start traversing the string for (i = 0; i < str.length(); i++) { // Increment occ if current char is equal // to given character if (str[i] == ch) occ++; // Break the loop if given character has // been occurred given no. of times if (occ == count) break; } // Print the string after the occurrence // of given character given no. of times if (i < str.length() - 1) cout << str.substr(i + 1, str.length() - (i + 1)); // Otherwise string is empty else cout << "Empty string";} // Drivers codeint main(){ string str = "geeks for geeks"; printString(str, 'e', 2); return 0;} // Java program for above implementation public class GFG{ // Method to print the string static void printString(String str, char ch, int count) { int occ = 0, i; // If given count is 0 // print the given string and return if (count == 0) { System.out.println(str); return; } // Start traversing the string for (i = 0; i < str.length(); i++) { // Increment occ if current char is equal // to given character if (str.charAt(i) == ch) occ++; // Break the loop if given character has // been occurred given no. of times if (occ == count) break; } // Print the string after the occurrence // of given character given no. of times if (i < str.length() - 1) System.out.println(str.substring(i + 1)); // Otherwise string is empty else System.out.println("Empty string"); } // Driver Method public static void main(String[] args) { String str = "geeks for geeks"; printString(str, 'e', 2); }} # Python3 program for above implementation # Function to print the stringdef printString(str, ch, count): occ, i = 0, 0 # If given count is 0 # print the given string and return if (count == 0): print(str) # Start traversing the string for i in range(len(str)): # Increment occ if current char # is equal to given character if (str[i] == ch): occ += 1 # Break the loop if given character has # been occurred given no. of times if (occ == count): break # Print the string after the occurrence # of given character given no. of times if (i < len(str)- 1): print(str[i + 1: len(str) - i + 2]) # Otherwise string is empty else: print("Empty string") # Driver codeif __name__ == '__main__': str = "geeks for geeks" printString(str, 'e', 2) # This code is contributed# by 29AjayKumar // C# program for above implementationusing System; public class GFG { // Method to print the string static public void printString(string str, char ch, int count) { int occ = 0, i; // If given count is 0 // print the given string // and return if (count == 0) { Console.WriteLine(str); return; } // Start traversing the string for (i = 0; i < str.Length; i++) { // Increment occ if current // char is equal to given // character if (str[i] == ch) occ++; // Break the loop if given // character has been occurred // given no. of times if (occ == count) break; } // Print the string after the // occurrence of given character // given no. of times if (i < str.Length - 1) Console.WriteLine(str.Substring(i + 1)); // Otherwise string is empty else Console.WriteLine("Empty string"); } // Driver Method static public void Main() { string str = "geeks for geeks"; printString(str, 'e', 2); }} // This code is contributed by vt_m. <script> // JavaScript program for above implementation // Method to print the stringfunction printString(str, ch , count){ var occ = 0, i; // If given count is 0 // print the given string and return if (count == 0) { document.write(str); return; } // Start traversing the string for (i = 0; i < str.length; i++) { // Increment occ if current char is equal // to given character if (str.charAt(i) == ch) occ++; // Break the loop if given character has // been occurred given no. of times if (occ == count) break; } // Print the string after the occurrence // of given character given no. of times if (i < str.length - 1) document.write(str.substring(i + 1)); // Otherwise string is empty else document.write("Empty string");} // Driver Methodvar str = "geeks for geeks";printString(str, 'e', 2); // This code is contributed by Amit Katiyar </script> Output: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. ks for geeks Time complexity : O(n) Auxiliary Space : O(1) Print the string after the specified character has occurred given no. of times | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPrint the string after the specified character has occurred given no. of times | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=v3vPtLKr9s4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySEmN22LjriVE8wTkkZA3tDB 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m 29AjayKumar amit143katiyar youmailmahibagi Oracle Zoho Strings Zoho Oracle Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 463, "s": 52, "text": "Given a string, a character, and a count, the task is to print the string after the specified character has occurred count number of times. Print “Empty string” in case of any unsatisfying conditions. (Given character is not present, or present but less than given count, or given count completes on last index). If given count is 0, then given character doesn’t matter, just print the whole string.Examples: " }, { "code": null, "e": 650, "s": 463, "text": "Input : str = \"This is demo string\" \n char = i, \n count = 3\nOutput : ng\n\nInput : str = \"geeksforgeeks\"\n char = e, \n count = 2\nOutput : ksforgeeks" }, { "code": null, "e": 668, "s": 650, "text": "Asked in: Oracle " }, { "code": null, "e": 716, "s": 668, "text": "Implementation: 1- Start traversing the string." }, { "code": null, "e": 776, "s": 716, "text": "Increment occ_count if current char is equal to given char." }, { "code": null, "e": 840, "s": 776, "text": "Get out of the loop, if occ_count becomes equal to given count." }, { "code": null, "e": 982, "s": 840, "text": "2- Print the string after the index till the string gets traversed in the loop. 3- If index has reached the last, then print “Empty string”. " }, { "code": null, "e": 986, "s": 982, "text": "C++" }, { "code": null, "e": 991, "s": 986, "text": "Java" }, { "code": null, "e": 999, "s": 991, "text": "Python3" }, { "code": null, "e": 1002, "s": 999, "text": "C#" }, { "code": null, "e": 1013, "s": 1002, "text": "Javascript" }, { "code": "// C++ program for above implementation#include <iostream>using namespace std; // Function to print the stringvoid printString(string str, char ch, int count){ int occ = 0, i; // If given count is 0 // print the given string and return if (count == 0) { cout << str; return; } // Start traversing the string for (i = 0; i < str.length(); i++) { // Increment occ if current char is equal // to given character if (str[i] == ch) occ++; // Break the loop if given character has // been occurred given no. of times if (occ == count) break; } // Print the string after the occurrence // of given character given no. of times if (i < str.length() - 1) cout << str.substr(i + 1, str.length() - (i + 1)); // Otherwise string is empty else cout << \"Empty string\";} // Drivers codeint main(){ string str = \"geeks for geeks\"; printString(str, 'e', 2); return 0;}", "e": 2011, "s": 1013, "text": null }, { "code": "// Java program for above implementation public class GFG{ // Method to print the string static void printString(String str, char ch, int count) { int occ = 0, i; // If given count is 0 // print the given string and return if (count == 0) { System.out.println(str); return; } // Start traversing the string for (i = 0; i < str.length(); i++) { // Increment occ if current char is equal // to given character if (str.charAt(i) == ch) occ++; // Break the loop if given character has // been occurred given no. of times if (occ == count) break; } // Print the string after the occurrence // of given character given no. of times if (i < str.length() - 1) System.out.println(str.substring(i + 1)); // Otherwise string is empty else System.out.println(\"Empty string\"); } // Driver Method public static void main(String[] args) { String str = \"geeks for geeks\"; printString(str, 'e', 2); }}", "e": 3206, "s": 2011, "text": null }, { "code": "# Python3 program for above implementation # Function to print the stringdef printString(str, ch, count): occ, i = 0, 0 # If given count is 0 # print the given string and return if (count == 0): print(str) # Start traversing the string for i in range(len(str)): # Increment occ if current char # is equal to given character if (str[i] == ch): occ += 1 # Break the loop if given character has # been occurred given no. of times if (occ == count): break # Print the string after the occurrence # of given character given no. of times if (i < len(str)- 1): print(str[i + 1: len(str) - i + 2]) # Otherwise string is empty else: print(\"Empty string\") # Driver codeif __name__ == '__main__': str = \"geeks for geeks\" printString(str, 'e', 2) # This code is contributed# by 29AjayKumar", "e": 4114, "s": 3206, "text": null }, { "code": "// C# program for above implementationusing System; public class GFG { // Method to print the string static public void printString(string str, char ch, int count) { int occ = 0, i; // If given count is 0 // print the given string // and return if (count == 0) { Console.WriteLine(str); return; } // Start traversing the string for (i = 0; i < str.Length; i++) { // Increment occ if current // char is equal to given // character if (str[i] == ch) occ++; // Break the loop if given // character has been occurred // given no. of times if (occ == count) break; } // Print the string after the // occurrence of given character // given no. of times if (i < str.Length - 1) Console.WriteLine(str.Substring(i + 1)); // Otherwise string is empty else Console.WriteLine(\"Empty string\"); } // Driver Method static public void Main() { string str = \"geeks for geeks\"; printString(str, 'e', 2); }} // This code is contributed by vt_m.", "e": 5418, "s": 4114, "text": null }, { "code": "<script> // JavaScript program for above implementation // Method to print the stringfunction printString(str, ch , count){ var occ = 0, i; // If given count is 0 // print the given string and return if (count == 0) { document.write(str); return; } // Start traversing the string for (i = 0; i < str.length; i++) { // Increment occ if current char is equal // to given character if (str.charAt(i) == ch) occ++; // Break the loop if given character has // been occurred given no. of times if (occ == count) break; } // Print the string after the occurrence // of given character given no. of times if (i < str.length - 1) document.write(str.substring(i + 1)); // Otherwise string is empty else document.write(\"Empty string\");} // Driver Methodvar str = \"geeks for geeks\";printString(str, 'e', 2); // This code is contributed by Amit Katiyar </script>", "e": 6411, "s": 5418, "text": null }, { "code": null, "e": 6421, "s": 6411, "text": "Output: " }, { "code": null, "e": 6430, "s": 6421, "text": "Chapters" }, { "code": null, "e": 6457, "s": 6430, "text": "descriptions off, selected" }, { "code": null, "e": 6507, "s": 6457, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 6530, "s": 6507, "text": "captions off, selected" }, { "code": null, "e": 6538, "s": 6530, "text": "English" }, { "code": null, "e": 6562, "s": 6538, "text": "This is a modal window." }, { "code": null, "e": 6631, "s": 6562, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 6653, "s": 6631, "text": "End of dialog window." }, { "code": null, "e": 6666, "s": 6653, "text": "ks for geeks" }, { "code": null, "e": 6713, "s": 6666, "text": "Time complexity : O(n) Auxiliary Space : O(1) " }, { "code": null, "e": 7687, "s": 6713, "text": "Print the string after the specified character has occurred given no. of times | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPrint the string after the specified character has occurred given no. of times | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:44•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=v3vPtLKr9s4\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 7728, "s": 7687, "text": "?list=PLqM7alHXFySEmN22LjriVE8wTkkZA3tDB" }, { "code": null, "e": 8150, "s": 7728, "text": "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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8155, "s": 8150, "text": "vt_m" }, { "code": null, "e": 8167, "s": 8155, "text": "29AjayKumar" }, { "code": null, "e": 8182, "s": 8167, "text": "amit143katiyar" }, { "code": null, "e": 8198, "s": 8182, "text": "youmailmahibagi" }, { "code": null, "e": 8205, "s": 8198, "text": "Oracle" }, { "code": null, "e": 8210, "s": 8205, "text": "Zoho" }, { "code": null, "e": 8218, "s": 8210, "text": "Strings" }, { "code": null, "e": 8223, "s": 8218, "text": "Zoho" }, { "code": null, "e": 8230, "s": 8223, "text": "Oracle" }, { "code": null, "e": 8238, "s": 8230, "text": "Strings" } ]
Closest Palindrome Number (absolute difference Is min)
14 Mar, 2022 Given a number N. our task is to find the closest Palindrome number whose absolute difference with given number is minimum and absolute difference must be greater than 0. Examples: Input : N = 121 Output : 131 or 111 Both having equal absolute difference with the given number. Input : N = 1234 Output : 1221 Asked In : Amazon Simple Solution is to find the largest palindrome number which is smaller to given number and also find the first palindrome number which is greater than Given number.we can find there Palindromic numbers by simply decreasing and increasing by one in given number until we find these palindromic numbers. Below is the implementation of above idea : C++ Java Python3 C# PHP Javascript // C++ Program to find the closest Palindrome// number#include <bits/stdc++.h>using namespace std; // function check Palindromebool isPalindrome(string n){ for (int i = 0; i < n.size() / 2; i++) if (n[i] != n[n.size() - 1 - i]) return false; return true;} // convert number into Stringstring convertNumIntoString(int num){ // base case: if (num == 0) return "0"; string Snum = ""; while (num > 0) { Snum += (num % 10 - '0'); num /= 10; } return Snum;} // function return closest Palindrome numberint closestPalindrome(int num){ // case1 : largest palindrome number // which is smaller to given number int RPNum = num - 1; while (!isPalindrome(convertNumIntoString(abs(RPNum)))) RPNum--; // Case 2 : smallest palindrome number // which is greater than given number int SPNum = num + 1; while (!isPalindrome(convertNumIntoString(SPNum))) SPNum++; // check absolute difference if (abs(num - RPNum) > abs(num - SPNum)) return SPNum; else return RPNum;} // Driver program to test above functionint main(){ int num = 121; cout << closestPalindrome(num) << endl; return 0;} // Java program to find the closest// Palindrome numberimport java.io.*; class GFG{ // Function to check Palindrome public static boolean isPalindrome(String s){ int left = 0; int right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true;} // Function return closest Palindrome numberpublic static void closestPalindrome(int num){ // Case1 : largest palindrome number // which is smaller to given number int RPNum = num - 1; while (isPalindrome(Integer.toString(RPNum)) == false) { RPNum--; } // Case 2 : smallest palindrome number // which is greater than given number int SPNum = num + 1; while (isPalindrome(Integer.toString(SPNum)) == false) { SPNum++; } // Check absolute difference if (Math.abs(num - SPNum) < Math.abs(num - RPNum)) { System.out.println(SPNum); } else System.out.println(RPNum);} // Driver code public static void main(String[] args){ int n = 121; closestPalindrome(n);}} // This code is contributed by kes333hav # Python3 program to find the# closest Palindrome number # Function to check Palindrome def isPalindrome(n): for i in range(len(n) // 2): if (n[i] != n[-1 - i]): return False return True # Convert number into String def convertNumIntoString(num): Snum = str(num) return Snum # Function return closest Palindrome number def closestPalindrome(num): # Case1 : largest palindrome number # which is smaller than given number RPNum = num - 1 while (not isPalindrome( convertNumIntoString(abs(RPNum)))): RPNum -= 1 # Case2 : smallest palindrome number # which is greater than given number SPNum = num + 1 while (not isPalindrome( convertNumIntoString(SPNum))): SPNum += 1 # Check absolute difference if (abs(num - RPNum) > abs(num - SPNum)): return SPNum else: return RPNum # Driver Codeif __name__ == '__main__': num = 121 print(closestPalindrome(num)) # This code is contributed by himanshu77 // C# program to find the closest// Palindrome numberusing System; class GFG{ // Function to check Palindromepublic static bool isPalindrome(string s){ int left = 0; int right = s.Length - 1; while (left < right) { if (s[left] != s[right]) { return false; } left++; right--; } return true;} // Function return closest Palindrome numberpublic static void closestPalindrome(int num){ // Case1 : largest palindrome number // which is smaller to given number int RPNum = num - 1; while (isPalindrome(RPNum.ToString()) == false) { RPNum--; } // Case 2 : smallest palindrome number // which is greater than given number int SPNum = num + 1; while (isPalindrome(SPNum.ToString()) == false) { SPNum++; } // Check absolute difference if (Math.Abs(num - SPNum) < Math.Abs(num - RPNum)) { Console.WriteLine(SPNum); } else Console.WriteLine(RPNum);} // Driver codepublic static void Main(string[] args){ int n = 121; closestPalindrome(n);}} // This code is contributed by ukasp <?php// PHP Program to find the// closest Palindrome number // function check Palindromefunction isPalindrome($n){ for ($i = 0; $i < floor(strlen($n) / 2); $i++) if ($n[$i] != $n[strlen($n) - 1 - $i]) return false;return true;} // convert number into Stringfunction convertNumIntoString($num){ // base case:if ($num == 0) return "0";$Snum = "";while ($num > 0){ $Snum .= ($num % 10 - '0'); $num =(int)($num / 10);}return $Snum;} // function return closest// Palindrome numberfunction closestPalindrome($num){ // case1 : largest palindrome number// which is smaller to given number$RPNum = $num - 1; while (!isPalindrome(convertNumIntoString(abs($RPNum)))) $RPNum--; // Case 2 : smallest palindrome number// which is greater than given number$SPNum = $num + 1; while (!isPalindrome(convertNumIntoString($SPNum))) $SPNum++; // check absolute differenceif (abs($num - $RPNum) > abs($num - $SPNum)) return $SPNum;else return $RPNum;} // Driver code $num = 121; echo closestPalindrome($num)."\n"; // This code is contributed by mits?> <script> // JavaScript Program to find the closest Palindrome// number // function check Palindromefunction isPalindrome(n){ for (let i = 0; i < Math.floor(n.length / 2); i++) if (n[i] != n[n.length - 1 - i]) return false; return true;} // convert number into Stringfunction convertNumIntoString(num){ // base case: if (num == 0) return "0"; let Snum = num + ''; return Snum;} // function return closest Palindrome numberfunction closestPalindrome(num){ // case1 : largest palindrome number // which is smaller to given number let RPNum = num - 1; while (!isPalindrome(convertNumIntoString(Math.abs(RPNum)))) RPNum--; // Case 2 : smallest palindrome number // which is greater than given number let SPNum = num + 1; while (!isPalindrome(convertNumIntoString(SPNum))) SPNum++; // check absolute difference if (Math.abs(num - RPNum) > Math.abs(num - SPNum)) return SPNum; else return RPNum;} // Driver program to test above functionlet num = 121;document.write(closestPalindrome(num),"</br>"); // This code is contributed by shinjanpatra.</script> Output: 111 An efficient solution is to consider following cases. Case 1: If a number contains all 9’s then we get next closest Palindrome by simply adding 2 in it. num = 999 : output : num + 2 = 1001.Case 2: Case 2 a :One possible way to getting closest palindromic by Copy first half and add mirror image at the end if it. Left half : For example, left side of “123 456” is “123” and left half of “12345” is “1 2”. To convert to palindrome, we can either take the mirror of its left half or take mirror of its right half. However, if we take the mirror of the right half, then the palindrome so formed is not guaranteed to be the closest palindrome. So, we must take the mirror of left side and copy it to right side. Let's number : 123456 After copy and append reverse of it at the end number looks like: we get palindrome 123321 case 2 b and 2c: Two more possible ways of getting the closest palindromic number by decrementing and incrementing middle digit by one on palindrome. Below is the implementation of the above idea : C++ // C++ program to find the closest Palindrome number#include <bits/stdc++.h>using namespace std; #define CToI(x) (x - '0')#define IToC(x) (x + '0') // function check Palindromebool isPalindrome(string n){ for (int i = 0; i < n.size() / 2; i++) if (n[i] != n[n.size() - 1 - i]) return false; return true;} // check all 9'sbool checkAll9(string num){ for (int i = 0; i < num.size(); i++) if (num[i] != '9') return false; return true;} // Add carry to the number of given sizestring carryOperation(string num, int carry, int size){ if (carry == -1) { int i = size - 1; while (i >= 0 && num[i] == '0') num[i--] = '9'; if (i >= 0) num[i] = IToC(CToI(num[i]) - 1); } else { for (int i = size - 1; i >= 0; i--) { int digit = CToI(num[i]); num[i] = IToC((digit + carry) % 10); carry = (digit + carry) / 10; } } return num;} // function return the closest number// to given numberstring MIN(long long int num, long long int num1, long long int num2, long long int num3){ long long int Diff1 = abs(num - num1); long long int Diff2 = abs(num - num2); long long int Diff3 = abs(num3 - num); if (Diff1 < Diff2 && Diff1 < Diff3 && num1 != num) return to_string(num1); else if (Diff3 < Diff2 && (Diff1 == 0 || Diff3 < Diff1)) return to_string(num3); else return to_string(num2);} // function return closest Palindrome numberstring closestPlandrome(string num){ // base case if (num.size() == 1) return (to_string(stoi(num) - 1)); // case 2: // If a number contains all 9's if (checkAll9(num)) { string str = "1"; return str.append(num.size() - 1, '0') + "1"; } int size_ = num.size(); // case 1 a: // copy first half and reverse it and append it // at the end of first half string FH = num.substr(0, size_ / 2); string odd; // odd length if (size_ % 2 != 0) odd = num[size_ / 2]; // reverse string SH = FH; reverse(SH.begin(), SH.end()); // store three nearest Palindrome numbers string RPNUM = "", EPNUM = "", LPNUM = ""; string tempFH = ""; string tempSH = ""; if (size_ % 2 != 0) { EPNUM = FH + odd + SH; if (odd == "0") { tempFH = carryOperation(FH, -1, FH.size()); tempSH = tempFH; reverse(tempSH.begin(), tempSH.end()); RPNUM = tempFH + "9" + tempSH; } else RPNUM = FH + to_string(stoi(odd) - 1) + SH; // To handle carry if (odd == "9") { tempFH = carryOperation(FH, 1, FH.size()); tempSH = tempFH; reverse(tempSH.begin(), tempSH.end()); LPNUM = tempFH + "0" + tempSH; } else LPNUM = FH + to_string(stoi(odd) + 1) + SH; } // for even case else { int n = FH.size(); tempFH = FH; EPNUM = FH + SH; if (FH[n - 1] == '0') tempFH = carryOperation(FH, -1, n); else tempFH[n - 1] = IToC(CToI(FH[n - 1]) - 1); tempSH = tempFH; reverse(tempSH.begin(), tempSH.end()); RPNUM = tempFH + tempSH; tempFH = FH; if (FH[n - 1] == '9') tempFH = carryOperation(FH, 1, n); else tempFH[n - 1] = IToC(CToI(tempFH[n - 1]) + 1); tempSH = tempFH; reverse(tempSH.begin(), tempSH.end()); LPNUM = tempFH + tempSH; } // return the closest palindrome numbers return MIN(stoll(num), stoll(EPNUM), stoll(RPNUM), stoll(LPNUM));} // Driver program to test above functionint main(){ string num = "123456"; cout << closestPlandrome(num) << endl; return 0;} Output: 123321 Time complexity: O(d) ( d is the number of digit in given number ) Mithun Kumar mahendera himanshu77 kes333hav ukasp shinjanpatra varshagumber28 number-digits palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters What is Data Structure: Types, Classifications and Applications Convert string to char array in C++ Check whether two strings are anagram of each other
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Mar, 2022" }, { "code": null, "e": 224, "s": 52, "text": "Given a number N. our task is to find the closest Palindrome number whose absolute difference with given number is minimum and absolute difference must be greater than 0. " }, { "code": null, "e": 235, "s": 224, "text": "Examples: " }, { "code": null, "e": 369, "s": 235, "text": "Input : N = 121 \nOutput : 131 or 111 \nBoth having equal absolute difference\nwith the given number.\n\nInput : N = 1234\nOutput : 1221" }, { "code": null, "e": 388, "s": 369, "text": "Asked In : Amazon " }, { "code": null, "e": 693, "s": 388, "text": "Simple Solution is to find the largest palindrome number which is smaller to given number and also find the first palindrome number which is greater than Given number.we can find there Palindromic numbers by simply decreasing and increasing by one in given number until we find these palindromic numbers." }, { "code": null, "e": 737, "s": 693, "text": "Below is the implementation of above idea :" }, { "code": null, "e": 741, "s": 737, "text": "C++" }, { "code": null, "e": 746, "s": 741, "text": "Java" }, { "code": null, "e": 754, "s": 746, "text": "Python3" }, { "code": null, "e": 757, "s": 754, "text": "C#" }, { "code": null, "e": 761, "s": 757, "text": "PHP" }, { "code": null, "e": 772, "s": 761, "text": "Javascript" }, { "code": "// C++ Program to find the closest Palindrome// number#include <bits/stdc++.h>using namespace std; // function check Palindromebool isPalindrome(string n){ for (int i = 0; i < n.size() / 2; i++) if (n[i] != n[n.size() - 1 - i]) return false; return true;} // convert number into Stringstring convertNumIntoString(int num){ // base case: if (num == 0) return \"0\"; string Snum = \"\"; while (num > 0) { Snum += (num % 10 - '0'); num /= 10; } return Snum;} // function return closest Palindrome numberint closestPalindrome(int num){ // case1 : largest palindrome number // which is smaller to given number int RPNum = num - 1; while (!isPalindrome(convertNumIntoString(abs(RPNum)))) RPNum--; // Case 2 : smallest palindrome number // which is greater than given number int SPNum = num + 1; while (!isPalindrome(convertNumIntoString(SPNum))) SPNum++; // check absolute difference if (abs(num - RPNum) > abs(num - SPNum)) return SPNum; else return RPNum;} // Driver program to test above functionint main(){ int num = 121; cout << closestPalindrome(num) << endl; return 0;}", "e": 1979, "s": 772, "text": null }, { "code": "// Java program to find the closest// Palindrome numberimport java.io.*; class GFG{ // Function to check Palindrome public static boolean isPalindrome(String s){ int left = 0; int right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true;} // Function return closest Palindrome numberpublic static void closestPalindrome(int num){ // Case1 : largest palindrome number // which is smaller to given number int RPNum = num - 1; while (isPalindrome(Integer.toString(RPNum)) == false) { RPNum--; } // Case 2 : smallest palindrome number // which is greater than given number int SPNum = num + 1; while (isPalindrome(Integer.toString(SPNum)) == false) { SPNum++; } // Check absolute difference if (Math.abs(num - SPNum) < Math.abs(num - RPNum)) { System.out.println(SPNum); } else System.out.println(RPNum);} // Driver code public static void main(String[] args){ int n = 121; closestPalindrome(n);}} // This code is contributed by kes333hav", "e": 3191, "s": 1979, "text": null }, { "code": "# Python3 program to find the# closest Palindrome number # Function to check Palindrome def isPalindrome(n): for i in range(len(n) // 2): if (n[i] != n[-1 - i]): return False return True # Convert number into String def convertNumIntoString(num): Snum = str(num) return Snum # Function return closest Palindrome number def closestPalindrome(num): # Case1 : largest palindrome number # which is smaller than given number RPNum = num - 1 while (not isPalindrome( convertNumIntoString(abs(RPNum)))): RPNum -= 1 # Case2 : smallest palindrome number # which is greater than given number SPNum = num + 1 while (not isPalindrome( convertNumIntoString(SPNum))): SPNum += 1 # Check absolute difference if (abs(num - RPNum) > abs(num - SPNum)): return SPNum else: return RPNum # Driver Codeif __name__ == '__main__': num = 121 print(closestPalindrome(num)) # This code is contributed by himanshu77", "e": 4208, "s": 3191, "text": null }, { "code": "// C# program to find the closest// Palindrome numberusing System; class GFG{ // Function to check Palindromepublic static bool isPalindrome(string s){ int left = 0; int right = s.Length - 1; while (left < right) { if (s[left] != s[right]) { return false; } left++; right--; } return true;} // Function return closest Palindrome numberpublic static void closestPalindrome(int num){ // Case1 : largest palindrome number // which is smaller to given number int RPNum = num - 1; while (isPalindrome(RPNum.ToString()) == false) { RPNum--; } // Case 2 : smallest palindrome number // which is greater than given number int SPNum = num + 1; while (isPalindrome(SPNum.ToString()) == false) { SPNum++; } // Check absolute difference if (Math.Abs(num - SPNum) < Math.Abs(num - RPNum)) { Console.WriteLine(SPNum); } else Console.WriteLine(RPNum);} // Driver codepublic static void Main(string[] args){ int n = 121; closestPalindrome(n);}} // This code is contributed by ukasp", "e": 5341, "s": 4208, "text": null }, { "code": "<?php// PHP Program to find the// closest Palindrome number // function check Palindromefunction isPalindrome($n){ for ($i = 0; $i < floor(strlen($n) / 2); $i++) if ($n[$i] != $n[strlen($n) - 1 - $i]) return false;return true;} // convert number into Stringfunction convertNumIntoString($num){ // base case:if ($num == 0) return \"0\";$Snum = \"\";while ($num > 0){ $Snum .= ($num % 10 - '0'); $num =(int)($num / 10);}return $Snum;} // function return closest// Palindrome numberfunction closestPalindrome($num){ // case1 : largest palindrome number// which is smaller to given number$RPNum = $num - 1; while (!isPalindrome(convertNumIntoString(abs($RPNum)))) $RPNum--; // Case 2 : smallest palindrome number// which is greater than given number$SPNum = $num + 1; while (!isPalindrome(convertNumIntoString($SPNum))) $SPNum++; // check absolute differenceif (abs($num - $RPNum) > abs($num - $SPNum)) return $SPNum;else return $RPNum;} // Driver code $num = 121; echo closestPalindrome($num).\"\\n\"; // This code is contributed by mits?>", "e": 6409, "s": 5341, "text": null }, { "code": "<script> // JavaScript Program to find the closest Palindrome// number // function check Palindromefunction isPalindrome(n){ for (let i = 0; i < Math.floor(n.length / 2); i++) if (n[i] != n[n.length - 1 - i]) return false; return true;} // convert number into Stringfunction convertNumIntoString(num){ // base case: if (num == 0) return \"0\"; let Snum = num + ''; return Snum;} // function return closest Palindrome numberfunction closestPalindrome(num){ // case1 : largest palindrome number // which is smaller to given number let RPNum = num - 1; while (!isPalindrome(convertNumIntoString(Math.abs(RPNum)))) RPNum--; // Case 2 : smallest palindrome number // which is greater than given number let SPNum = num + 1; while (!isPalindrome(convertNumIntoString(SPNum))) SPNum++; // check absolute difference if (Math.abs(num - RPNum) > Math.abs(num - SPNum)) return SPNum; else return RPNum;} // Driver program to test above functionlet num = 121;document.write(closestPalindrome(num),\"</br>\"); // This code is contributed by shinjanpatra.</script>", "e": 7570, "s": 6409, "text": null }, { "code": null, "e": 7579, "s": 7570, "text": "Output: " }, { "code": null, "e": 7583, "s": 7579, "text": "111" }, { "code": null, "e": 8292, "s": 7583, "text": "An efficient solution is to consider following cases. Case 1: If a number contains all 9’s then we get next closest Palindrome by simply adding 2 in it. num = 999 : output : num + 2 = 1001.Case 2: Case 2 a :One possible way to getting closest palindromic by Copy first half and add mirror image at the end if it. Left half : For example, left side of “123 456” is “123” and left half of “12345” is “1 2”. To convert to palindrome, we can either take the mirror of its left half or take mirror of its right half. However, if we take the mirror of the right half, then the palindrome so formed is not guaranteed to be the closest palindrome. So, we must take the mirror of left side and copy it to right side. " }, { "code": null, "e": 8406, "s": 8292, "text": "Let's number : 123456 \nAfter copy and append reverse of it at the end number looks like:\nwe get palindrome 123321" }, { "code": null, "e": 8557, "s": 8406, "text": "case 2 b and 2c: Two more possible ways of getting the closest palindromic number by decrementing and incrementing middle digit by one on palindrome. " }, { "code": null, "e": 8607, "s": 8557, "text": "Below is the implementation of the above idea : " }, { "code": null, "e": 8611, "s": 8607, "text": "C++" }, { "code": "// C++ program to find the closest Palindrome number#include <bits/stdc++.h>using namespace std; #define CToI(x) (x - '0')#define IToC(x) (x + '0') // function check Palindromebool isPalindrome(string n){ for (int i = 0; i < n.size() / 2; i++) if (n[i] != n[n.size() - 1 - i]) return false; return true;} // check all 9'sbool checkAll9(string num){ for (int i = 0; i < num.size(); i++) if (num[i] != '9') return false; return true;} // Add carry to the number of given sizestring carryOperation(string num, int carry, int size){ if (carry == -1) { int i = size - 1; while (i >= 0 && num[i] == '0') num[i--] = '9'; if (i >= 0) num[i] = IToC(CToI(num[i]) - 1); } else { for (int i = size - 1; i >= 0; i--) { int digit = CToI(num[i]); num[i] = IToC((digit + carry) % 10); carry = (digit + carry) / 10; } } return num;} // function return the closest number// to given numberstring MIN(long long int num, long long int num1, long long int num2, long long int num3){ long long int Diff1 = abs(num - num1); long long int Diff2 = abs(num - num2); long long int Diff3 = abs(num3 - num); if (Diff1 < Diff2 && Diff1 < Diff3 && num1 != num) return to_string(num1); else if (Diff3 < Diff2 && (Diff1 == 0 || Diff3 < Diff1)) return to_string(num3); else return to_string(num2);} // function return closest Palindrome numberstring closestPlandrome(string num){ // base case if (num.size() == 1) return (to_string(stoi(num) - 1)); // case 2: // If a number contains all 9's if (checkAll9(num)) { string str = \"1\"; return str.append(num.size() - 1, '0') + \"1\"; } int size_ = num.size(); // case 1 a: // copy first half and reverse it and append it // at the end of first half string FH = num.substr(0, size_ / 2); string odd; // odd length if (size_ % 2 != 0) odd = num[size_ / 2]; // reverse string SH = FH; reverse(SH.begin(), SH.end()); // store three nearest Palindrome numbers string RPNUM = \"\", EPNUM = \"\", LPNUM = \"\"; string tempFH = \"\"; string tempSH = \"\"; if (size_ % 2 != 0) { EPNUM = FH + odd + SH; if (odd == \"0\") { tempFH = carryOperation(FH, -1, FH.size()); tempSH = tempFH; reverse(tempSH.begin(), tempSH.end()); RPNUM = tempFH + \"9\" + tempSH; } else RPNUM = FH + to_string(stoi(odd) - 1) + SH; // To handle carry if (odd == \"9\") { tempFH = carryOperation(FH, 1, FH.size()); tempSH = tempFH; reverse(tempSH.begin(), tempSH.end()); LPNUM = tempFH + \"0\" + tempSH; } else LPNUM = FH + to_string(stoi(odd) + 1) + SH; } // for even case else { int n = FH.size(); tempFH = FH; EPNUM = FH + SH; if (FH[n - 1] == '0') tempFH = carryOperation(FH, -1, n); else tempFH[n - 1] = IToC(CToI(FH[n - 1]) - 1); tempSH = tempFH; reverse(tempSH.begin(), tempSH.end()); RPNUM = tempFH + tempSH; tempFH = FH; if (FH[n - 1] == '9') tempFH = carryOperation(FH, 1, n); else tempFH[n - 1] = IToC(CToI(tempFH[n - 1]) + 1); tempSH = tempFH; reverse(tempSH.begin(), tempSH.end()); LPNUM = tempFH + tempSH; } // return the closest palindrome numbers return MIN(stoll(num), stoll(EPNUM), stoll(RPNUM), stoll(LPNUM));} // Driver program to test above functionint main(){ string num = \"123456\"; cout << closestPlandrome(num) << endl; return 0;}", "e": 12484, "s": 8611, "text": null }, { "code": null, "e": 12493, "s": 12484, "text": "Output: " }, { "code": null, "e": 12500, "s": 12493, "text": "123321" }, { "code": null, "e": 12568, "s": 12500, "text": "Time complexity: O(d) ( d is the number of digit in given number ) " }, { "code": null, "e": 12581, "s": 12568, "text": "Mithun Kumar" }, { "code": null, "e": 12591, "s": 12581, "text": "mahendera" }, { "code": null, "e": 12602, "s": 12591, "text": "himanshu77" }, { "code": null, "e": 12612, "s": 12602, "text": "kes333hav" }, { "code": null, "e": 12618, "s": 12612, "text": "ukasp" }, { "code": null, "e": 12631, "s": 12618, "text": "shinjanpatra" }, { "code": null, "e": 12646, "s": 12631, "text": "varshagumber28" }, { "code": null, "e": 12660, "s": 12646, "text": "number-digits" }, { "code": null, "e": 12671, "s": 12660, "text": "palindrome" }, { "code": null, "e": 12679, "s": 12671, "text": "Strings" }, { "code": null, "e": 12687, "s": 12679, "text": "Strings" }, { "code": null, "e": 12698, "s": 12687, "text": "palindrome" }, { "code": null, "e": 12796, "s": 12698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12871, "s": 12796, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 12916, "s": 12871, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 12973, "s": 12916, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 13009, "s": 12973, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 13047, "s": 13009, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 13092, "s": 13047, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 13153, "s": 13092, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 13217, "s": 13153, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 13253, "s": 13217, "text": "Convert string to char array in C++" } ]
Tabulation vs Memoization
30 Dec, 2021 Prerequisite – Dynamic Programming, How to solve Dynamic Programming problems? There are two different ways to store the values so that the values of a sub-problem can be reused. Here, will discuss two patterns of solving dynamic programming (DP) problems: Tabulation: Bottom UpMemoization: Top Down Tabulation: Bottom Up Memoization: Top Down Before getting to the definitions of the above two terms consider the following statements: Version 1: I will study the theory of DP from GeeksforGeeks, then I will practice some problems on classic DP and hence I will master DP. Version 2: To Master DP, I would have to practice Dynamic problems and practice problems – Firstly, I would have to study some theories of DP from GeeksforGeeks Both versions say the same thing, the difference simply lies in the way of conveying the message and that’s exactly what Bottom-Up and Top-Down DP do. Version 1 can be related to Bottom-Up DP and Version-2 can be related as Top-Down DP. Tabulation Method – Bottom Up Dynamic Programming As the name itself suggests starting from the bottom and accumulating answers to the top. Let’s discuss in terms of state transition. Let’s describe a state for our DP problem to be dp[x] with dp[0] as base state and dp[n] as our destination state. So, we need to find the value of destination state i.e dp[n]. If we start our transition from our base state i.e dp[0] and follow our state transition relation to reach our destination state dp[n], we call it the Bottom-Up approach as it is quite clear that we started our transition from the bottom base state and reached the topmost desired state. Now, Why do we call it the tabulation method? To know this let’s first write some code to calculate the factorial of a number using a bottom-up approach. Once, again as our general procedure to solve a DP we first define a state. In this case, we define a state as dp[x], where dp[x] is to find the factorial of x. Now, it is quite obvious that dp[x+1] = dp[x] * (x+1) // Tabulated version to find factorial x. int dp[MAXN]; // base case int dp[0] = 1; for (int i = 1; i< =n; i++) { dp[i] = dp[i-1] * i; } The above code clearly follows the bottom-up approach as it starts its transition from the bottom-most base case dp[0] and reaches its destination state dp[n]. Here, we may notice that the DP table is being populated sequentially and we are directly accessing the calculated states from the table itself and hence, we call it the tabulation method. Memoization Method – Top-Down Dynamic Programming Once, again let’s describe it in terms of state transition. If we need to find the value for some state say dp[n] and instead of starting from the base state that i.e dp[0] we ask our answer from the states that can reach the destination state dp[n] following the state transition relation, then it is the top-down fashion of DP. Here, we start our journey from the top most destination state and compute its answer by taking in count the values of states that can reach the destination state, till we reach the bottom-most base state. Once again, let’s write the code for the factorial problem in the top-down fashion // Memoized version to find factorial x. // To speed up we store the values // of calculated states // initialized to -1 int dp[MAXN] // return fact x! int solve(int x) { if (x==0) return 1; if (dp[x]!=-1) return dp[x]; return (dp[x] = x * solve(x-1)); } As we can see we are storing the most recent cache up to a limit so that if next time we got a call from the same state we simply return it from the memory. So, this is why we call it memoization as we are storing the most recent state values. In this case, the memory layout is linear that’s why it may seem that the memory is being filled in a sequential manner like the tabulation method, but you may consider any other top-down DP having 2D memory layout like Min Cost Path, here the memory is not filled in a sequential manner. This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Deepak Sharma 4 draco_malf0y tim-hinnerkheuer leoburgy sulikdan techno96 mohan kumar Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Largest Sum Contiguous Subarray Program for Fibonacci numbers Find if there is a path between two vertices in an undirected graph Longest Palindromic Substring | Set 1 Longest Increasing Subsequence | DP-3 Bellman–Ford Algorithm | DP-23 Sieve of Eratosthenes Find minimum number of coins that make a given value Minimum number of jumps to reach end Count number of binary strings without consecutive 1's
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Dec, 2021" }, { "code": null, "e": 311, "s": 52, "text": "Prerequisite – Dynamic Programming, How to solve Dynamic Programming problems? There are two different ways to store the values so that the values of a sub-problem can be reused. Here, will discuss two patterns of solving dynamic programming (DP) problems: " }, { "code": null, "e": 354, "s": 311, "text": "Tabulation: Bottom UpMemoization: Top Down" }, { "code": null, "e": 376, "s": 354, "text": "Tabulation: Bottom Up" }, { "code": null, "e": 398, "s": 376, "text": "Memoization: Top Down" }, { "code": null, "e": 492, "s": 398, "text": "Before getting to the definitions of the above two terms consider the following statements: " }, { "code": null, "e": 630, "s": 492, "text": "Version 1: I will study the theory of DP from GeeksforGeeks, then I will practice some problems on classic DP and hence I will master DP." }, { "code": null, "e": 791, "s": 630, "text": "Version 2: To Master DP, I would have to practice Dynamic problems and practice problems – Firstly, I would have to study some theories of DP from GeeksforGeeks" }, { "code": null, "e": 1030, "s": 791, "text": "Both versions say the same thing, the difference simply lies in the way of conveying the message and that’s exactly what Bottom-Up and Top-Down DP do. Version 1 can be related to Bottom-Up DP and Version-2 can be related as Top-Down DP. " }, { "code": null, "e": 1081, "s": 1030, "text": "Tabulation Method – Bottom Up Dynamic Programming " }, { "code": null, "e": 1216, "s": 1081, "text": "As the name itself suggests starting from the bottom and accumulating answers to the top. Let’s discuss in terms of state transition. " }, { "code": null, "e": 1683, "s": 1216, "text": "Let’s describe a state for our DP problem to be dp[x] with dp[0] as base state and dp[n] as our destination state. So, we need to find the value of destination state i.e dp[n]. If we start our transition from our base state i.e dp[0] and follow our state transition relation to reach our destination state dp[n], we call it the Bottom-Up approach as it is quite clear that we started our transition from the bottom base state and reached the topmost desired state. " }, { "code": null, "e": 1730, "s": 1683, "text": "Now, Why do we call it the tabulation method? " }, { "code": null, "e": 2000, "s": 1730, "text": "To know this let’s first write some code to calculate the factorial of a number using a bottom-up approach. Once, again as our general procedure to solve a DP we first define a state. In this case, we define a state as dp[x], where dp[x] is to find the factorial of x. " }, { "code": null, "e": 2056, "s": 2000, "text": "Now, it is quite obvious that dp[x+1] = dp[x] * (x+1) " }, { "code": null, "e": 2198, "s": 2056, "text": "// Tabulated version to find factorial x.\nint dp[MAXN];\n\n// base case\nint dp[0] = 1;\nfor (int i = 1; i< =n; i++)\n{\n dp[i] = dp[i-1] * i;\n}" }, { "code": null, "e": 2548, "s": 2198, "text": "The above code clearly follows the bottom-up approach as it starts its transition from the bottom-most base case dp[0] and reaches its destination state dp[n]. Here, we may notice that the DP table is being populated sequentially and we are directly accessing the calculated states from the table itself and hence, we call it the tabulation method. " }, { "code": null, "e": 2601, "s": 2550, "text": "Memoization Method – Top-Down Dynamic Programming " }, { "code": null, "e": 2932, "s": 2601, "text": "Once, again let’s describe it in terms of state transition. If we need to find the value for some state say dp[n] and instead of starting from the base state that i.e dp[0] we ask our answer from the states that can reach the destination state dp[n] following the state transition relation, then it is the top-down fashion of DP. " }, { "code": null, "e": 3139, "s": 2932, "text": "Here, we start our journey from the top most destination state and compute its answer by taking in count the values of states that can reach the destination state, till we reach the bottom-most base state. " }, { "code": null, "e": 3224, "s": 3139, "text": "Once again, let’s write the code for the factorial problem in the top-down fashion " }, { "code": null, "e": 3509, "s": 3224, "text": "// Memoized version to find factorial x.\n// To speed up we store the values\n// of calculated states\n\n// initialized to -1\nint dp[MAXN]\n\n// return fact x!\nint solve(int x)\n{\n if (x==0)\n return 1;\n if (dp[x]!=-1)\n return dp[x];\n return (dp[x] = x * solve(x-1));\n}" }, { "code": null, "e": 3754, "s": 3509, "text": "As we can see we are storing the most recent cache up to a limit so that if next time we got a call from the same state we simply return it from the memory. So, this is why we call it memoization as we are storing the most recent state values. " }, { "code": null, "e": 4045, "s": 3754, "text": "In this case, the memory layout is linear that’s why it may seem that the memory is being filled in a sequential manner like the tabulation method, but you may consider any other top-down DP having 2D memory layout like Min Cost Path, here the memory is not filled in a sequential manner. " }, { "code": null, "e": 4318, "s": 4045, "text": "This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 4444, "s": 4318, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 4460, "s": 4444, "text": "Deepak Sharma 4" }, { "code": null, "e": 4473, "s": 4460, "text": "draco_malf0y" }, { "code": null, "e": 4490, "s": 4473, "text": "tim-hinnerkheuer" }, { "code": null, "e": 4499, "s": 4490, "text": "leoburgy" }, { "code": null, "e": 4508, "s": 4499, "text": "sulikdan" }, { "code": null, "e": 4517, "s": 4508, "text": "techno96" }, { "code": null, "e": 4529, "s": 4517, "text": "mohan kumar" }, { "code": null, "e": 4549, "s": 4529, "text": "Dynamic Programming" }, { "code": null, "e": 4569, "s": 4549, "text": "Dynamic Programming" }, { "code": null, "e": 4667, "s": 4569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4699, "s": 4667, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 4729, "s": 4699, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 4797, "s": 4729, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 4835, "s": 4797, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 4873, "s": 4835, "text": "Longest Increasing Subsequence | DP-3" }, { "code": null, "e": 4904, "s": 4873, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 4926, "s": 4904, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 4979, "s": 4926, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 5016, "s": 4979, "text": "Minimum number of jumps to reach end" } ]
Python Program to Efficiently compute sums of diagonals of a matrix
31 May, 2022 Given a 2D square matrix, find the sum of elements in Principal and Secondary diagonals. For example, consider the following 4 X 4 input matrix. A00 A01 A02 A03 A10 A11 A12 A13 A20 A21 A22 A23 A30 A31 A32 A33 The primary diagonal is formed by the elements A00, A11, A22, A33. Condition for Principal Diagonal: The row-column condition is row = column. The secondary diagonal is formed by the elements A03, A12, A21, A30.Condition for Secondary Diagonal: The row-column condition is row = numberOfRows – column -1. Condition for Principal Diagonal: The row-column condition is row = column. The secondary diagonal is formed by the elements A03, A12, A21, A30. Condition for Secondary Diagonal: The row-column condition is row = numberOfRows – column -1. Examples : Input : 4 1 2 3 4 4 3 2 1 7 8 9 6 6 5 4 3 Output : Principal Diagonal: 16 Secondary Diagonal: 20 Input : 3 1 1 1 1 1 1 1 1 1 Output : Principal Diagonal: 3 Secondary Diagonal: 3 Method 1 (O(n ^ 2) : In this method, we use two loops i.e. a loop for columns and a loop for rows and in the inner loop we check for the condition stated above: Python3 # A simple Python program to# find sum of diagonalsMAX = 100 def printDiagonalSums(mat, n): principal = 0 secondary = 0; for i in range(0, n): for j in range(0, n): # Condition for principal diagonal if (i == j): principal += mat[i][j] # Condition for secondary diagonal if ((i + j) == (n - 1)): secondary += mat[i][j] print("Principal Diagonal:", principal) print("Secondary Diagonal:", secondary) # Driver codea = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]]printDiagonalSums(a, 4) # This code is contributed# by ihritik Output: Principal Diagonal:18 Secondary Diagonal:18 Time Complexity: O(N*N), as we are using nested loops to traverse N*N times. Auxiliary Space: O(1), as we are not using any extra space. Method 2 (O(n) : In this method we use one loop i.e. a loop for calculating sum of both the principal and secondary diagonals: Python3 # A simple Python3 program to find# sum of diagonalsMAX = 100 def printDiagonalSums(mat, n): principal = 0 secondary = 0 for i in range(0, n): principal += mat[i][i] secondary += mat[i][n - i - 1] print("Principal Diagonal:", principal) print("Secondary Diagonal:", secondary) # Driver codea = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]]printDiagonalSums(a, 4) # This code is contributed# by ihritik Output : Principal Diagonal:18 Secondary Diagonal:18 Time Complexity: O(N), as we are using a loop to traverse N times. Auxiliary Space: O(1), as we are not using any extra space.Please refer complete article on Efficiently compute sums of diagonals of a matrix for more details! rohitsingh57 CBSE - Class 11 school-programming Matrix Python Python Programs Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unique paths in a Grid with Obstacles Traverse a given Matrix using Recursion Find median in row wise sorted matrix Zigzag (or diagonal) traversal of Matrix A Boolean Matrix Question Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2022" }, { "code": null, "e": 174, "s": 28, "text": "Given a 2D square matrix, find the sum of elements in Principal and Secondary diagonals. For example, consider the following 4 X 4 input matrix. " }, { "code": null, "e": 238, "s": 174, "text": "A00 A01 A02 A03\nA10 A11 A12 A13\nA20 A21 A22 A23\nA30 A31 A32 A33" }, { "code": null, "e": 307, "s": 238, "text": "The primary diagonal is formed by the elements A00, A11, A22, A33. " }, { "code": null, "e": 545, "s": 307, "text": "Condition for Principal Diagonal: The row-column condition is row = column. The secondary diagonal is formed by the elements A03, A12, A21, A30.Condition for Secondary Diagonal: The row-column condition is row = numberOfRows – column -1." }, { "code": null, "e": 690, "s": 545, "text": "Condition for Principal Diagonal: The row-column condition is row = column. The secondary diagonal is formed by the elements A03, A12, A21, A30." }, { "code": null, "e": 784, "s": 690, "text": "Condition for Secondary Diagonal: The row-column condition is row = numberOfRows – column -1." }, { "code": null, "e": 797, "s": 784, "text": "Examples : " }, { "code": null, "e": 977, "s": 797, "text": "Input : \n4\n1 2 3 4\n4 3 2 1\n7 8 9 6\n6 5 4 3\nOutput :\nPrincipal Diagonal: 16\nSecondary Diagonal: 20\n\nInput :\n3\n1 1 1\n1 1 1\n1 1 1\nOutput :\nPrincipal Diagonal: 3\nSecondary Diagonal: 3" }, { "code": null, "e": 1002, "s": 981, "text": "Method 1 (O(n ^ 2) :" }, { "code": null, "e": 1143, "s": 1002, "text": "In this method, we use two loops i.e. a loop for columns and a loop for rows and in the inner loop we check for the condition stated above: " }, { "code": null, "e": 1151, "s": 1143, "text": "Python3" }, { "code": "# A simple Python program to# find sum of diagonalsMAX = 100 def printDiagonalSums(mat, n): principal = 0 secondary = 0; for i in range(0, n): for j in range(0, n): # Condition for principal diagonal if (i == j): principal += mat[i][j] # Condition for secondary diagonal if ((i + j) == (n - 1)): secondary += mat[i][j] print(\"Principal Diagonal:\", principal) print(\"Secondary Diagonal:\", secondary) # Driver codea = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]]printDiagonalSums(a, 4) # This code is contributed# by ihritik", "e": 1815, "s": 1151, "text": null }, { "code": null, "e": 1825, "s": 1815, "text": "Output: " }, { "code": null, "e": 1869, "s": 1825, "text": "Principal Diagonal:18\nSecondary Diagonal:18" }, { "code": null, "e": 1946, "s": 1869, "text": "Time Complexity: O(N*N), as we are using nested loops to traverse N*N times." }, { "code": null, "e": 2006, "s": 1946, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 2023, "s": 2006, "text": "Method 2 (O(n) :" }, { "code": null, "e": 2135, "s": 2023, "text": "In this method we use one loop i.e. a loop for calculating sum of both the principal and secondary diagonals: " }, { "code": null, "e": 2143, "s": 2135, "text": "Python3" }, { "code": "# A simple Python3 program to find# sum of diagonalsMAX = 100 def printDiagonalSums(mat, n): principal = 0 secondary = 0 for i in range(0, n): principal += mat[i][i] secondary += mat[i][n - i - 1] print(\"Principal Diagonal:\", principal) print(\"Secondary Diagonal:\", secondary) # Driver codea = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]]printDiagonalSums(a, 4) # This code is contributed# by ihritik", "e": 2615, "s": 2143, "text": null }, { "code": null, "e": 2626, "s": 2615, "text": "Output : " }, { "code": null, "e": 2670, "s": 2626, "text": "Principal Diagonal:18\nSecondary Diagonal:18" }, { "code": null, "e": 2737, "s": 2670, "text": "Time Complexity: O(N), as we are using a loop to traverse N times." }, { "code": null, "e": 2897, "s": 2737, "text": "Auxiliary Space: O(1), as we are not using any extra space.Please refer complete article on Efficiently compute sums of diagonals of a matrix for more details!" }, { "code": null, "e": 2910, "s": 2897, "text": "rohitsingh57" }, { "code": null, "e": 2926, "s": 2910, "text": "CBSE - Class 11" }, { "code": null, "e": 2945, "s": 2926, "text": "school-programming" }, { "code": null, "e": 2952, "s": 2945, "text": "Matrix" }, { "code": null, "e": 2959, "s": 2952, "text": "Python" }, { "code": null, "e": 2975, "s": 2959, "text": "Python Programs" }, { "code": null, "e": 2982, "s": 2975, "text": "Matrix" }, { "code": null, "e": 3080, "s": 2982, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3118, "s": 3080, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 3158, "s": 3118, "text": "Traverse a given Matrix using Recursion" }, { "code": null, "e": 3196, "s": 3158, "text": "Find median in row wise sorted matrix" }, { "code": null, "e": 3237, "s": 3196, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 3263, "s": 3237, "text": "A Boolean Matrix Question" }, { "code": null, "e": 3291, "s": 3263, "text": "Read JSON file using Python" }, { "code": null, "e": 3341, "s": 3291, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3363, "s": 3341, "text": "Python map() function" } ]
How to Build Age Calculator in Android Studio?
22 Dec, 2021 Hello geeks, today we are going to make an application to calculate Age or time period between two dates. By making this application one can calculate his/her exact age, also one can calculate the exact difference between two dates. Prerequisites: Before making this application, you can go through the article Program to calculate age to have a better understanding of the concepts used in this application. In this application, we will be using two DatePickers, where user can select the date no. 1 and 2 respectively. A Button is used to perform the calculation part and show the result in a TextView named as result. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article. Step 1: Creating a new project Open a new project. We will be working on Empty Activity with language as Java. Leave all other options unchanged. You can change the name of the project at your convenience. There will be two default files named activity_main.xml and MainActivity.java. If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? Step 2: Navigate to Build scripts > build.gradle(module) file and add the following dependency to it implementation 'joda-time:joda-time:2.9.1' Step 3: Working with the activity_main.xml file Here we will design the user interface of our application. We will be using the following components for their respective works: Button 1: to pick the first date user wants to enter. Button 2: to pick the second date user wants to enter. Button 3: to perform the calculation TextView: to show the final output(age). Navigate to the app > res > layout > activity_main.xml and add the below code to that file. XML <?xml version="1.0" encoding="utf-8"?><!-- Parent layout as linear layout--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="10dp" tools:context=".MainActivity"> <!-- linear layout to show datepickers--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- to select the first date--> <Button android:id="@+id/bt_birth" android:layout_width="150dp" android:layout_height="50dp" android:background="@android:color/transparent" android:drawableRight="@drawable/ic_baseline" android:text="01/01/2021" android:textColor="@color/black" android:textSize="13sp" /> <!-- displaying message as "to"--> <TextView android:layout_width="100dp" android:layout_height="50dp" android:gravity="center_horizontal" android:text="To" android:textColor="@color/black" android:textSize="20sp" android:textStyle="bold" /> <!-- to display date number 2--> <Button android:id="@+id/bt_today" android:layout_width="145dp" android:layout_height="50dp" android:background="@android:color/transparent" android:drawableRight="@drawable/ic_baseline" android:textColor="@color/black" android:textSize="13sp" /> </LinearLayout> <!-- to perform the calculation--> <Button android:id="@+id/btn_calculate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="calculate" /> <!-- to display the message "Result"--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="Result" android:textColor="@android:color/holo_blue_bright" android:textSize="30sp" android:textStyle="bold" /> <!-- To show the final output(age)--> <TextView android:id="@+id/tv_result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="0 Years | 0 Months | 0 Days" android:textSize="25sp" android:textStyle="bold" /> </LinearLayout> After implementing the above code, the design of the activity_main.xml file looks like this. Step 4: Working with MainActivity.java file In MainActivity.java file onClickListerner is used on buttons to pick the date and to perform the calculation. Use the following code in the MainActivity.java file. Java import android.app.DatePickerDialog;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.DatePicker;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.joda.time.Period;import org.joda.time.PeriodType; import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date; public class MainActivity extends AppCompatActivity { // initializing variables Button btn_birth, btn_today, btn_calculate; TextView tvResult; DatePickerDialog.OnDateSetListener dateSetListener1, dateSetListener2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assign variables btn_birth = findViewById(R.id.bt_birth); btn_today = findViewById(R.id.bt_today); btn_calculate = findViewById(R.id.btn_calculate); tvResult = findViewById(R.id.tv_result); // calendar format is imported to pick date Calendar calendar = Calendar.getInstance(); // for year int year = calendar.get(Calendar.YEAR); // for month int month = calendar.get(Calendar.MONTH); // for date int day = calendar.get(Calendar.DAY_OF_MONTH); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); // to set the current date as by default String date = simpleDateFormat.format(Calendar.getInstance().getTime()); btn_today.setText(date); // action to be performed when button 1 is clicked btn_birth.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // date picker dialog is used // and its style and color are also passed DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, dateSetListener1, year, month, day ); // to set background for datepicker datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); datePickerDialog.show(); } }); // it is used to set the date which user selects dateSetListener1 = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int day) { // here month+1 is used so that // actual month number can be displayed // otherwise it starts from 0 and it shows // 1 number less for every month // example- for january month=0 month = month + 1; String date = day + "/" + month + "/" + year; btn_birth.setText(date); } }; // action to be performed when button 2 is clicked btn_today.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // date picker dialog is used // and its style and color are also passed DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, dateSetListener2, year, month, day ); // to set background for datepicker datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); datePickerDialog.show(); } }); // it is used to set the date which user selects dateSetListener2 = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int day) { // here month+1 is used so that // actual month number can be displayed // otherwise it starts from 0 and it shows // 1 number less for every month // example- for january month=0 month = month + 1; String date = day + "/" + month + "/" + year; btn_today.setText(date); } }; // action to be performed when calculate button is clicked btn_calculate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // converting the inputted date to string String sDate = btn_birth.getText().toString(); String eDate = btn_today.getText().toString(); SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("dd/MM/yyyy"); try { // converting it to date format Date date1 = simpleDateFormat1.parse(sDate); Date date2 = simpleDateFormat1.parse(eDate); long startdate = date1.getTime(); long endDate = date2.getTime(); // condition if (startdate <= endDate) { org.joda.time.Period period = new Period(startdate, endDate, PeriodType.yearMonthDay()); int years = period.getYears(); int months = period.getMonths(); int days = period.getDays(); // show the final output tvResult.setText(years + " Years |" + months + "Months |" + days + "Days"); } else { // show message Toast.makeText(MainActivity.this, "BirthDate should not be larger then today's date!", Toast.LENGTH_SHORT).show(); } } catch (ParseException e) { e.printStackTrace(); } } }); }} Congratulations! we have successfully the application to calculate the age or difference between two dates. Here is the final output of our application. Output: simmytarika5 Android-Studio Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Android SDK and it's Components Broadcast Receiver in Android With Example How to Communicate Between Fragments in Android? Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Dec, 2021" }, { "code": null, "e": 261, "s": 28, "text": "Hello geeks, today we are going to make an application to calculate Age or time period between two dates. By making this application one can calculate his/her exact age, also one can calculate the exact difference between two dates." }, { "code": null, "e": 276, "s": 261, "text": "Prerequisites:" }, { "code": null, "e": 437, "s": 276, "text": "Before making this application, you can go through the article Program to calculate age to have a better understanding of the concepts used in this application." }, { "code": null, "e": 815, "s": 437, "text": "In this application, we will be using two DatePickers, where user can select the date no. 1 and 2 respectively. A Button is used to perform the calculation part and show the result in a TextView named as result. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 846, "s": 815, "text": "Step 1: Creating a new project" }, { "code": null, "e": 866, "s": 846, "text": "Open a new project." }, { "code": null, "e": 961, "s": 866, "text": "We will be working on Empty Activity with language as Java. Leave all other options unchanged." }, { "code": null, "e": 1021, "s": 961, "text": "You can change the name of the project at your convenience." }, { "code": null, "e": 1100, "s": 1021, "text": "There will be two default files named activity_main.xml and MainActivity.java." }, { "code": null, "e": 1240, "s": 1100, "text": "If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? " }, { "code": null, "e": 1341, "s": 1240, "text": "Step 2: Navigate to Build scripts > build.gradle(module) file and add the following dependency to it" }, { "code": null, "e": 1384, "s": 1341, "text": "implementation 'joda-time:joda-time:2.9.1'" }, { "code": null, "e": 1432, "s": 1384, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 1561, "s": 1432, "text": "Here we will design the user interface of our application. We will be using the following components for their respective works:" }, { "code": null, "e": 1615, "s": 1561, "text": "Button 1: to pick the first date user wants to enter." }, { "code": null, "e": 1670, "s": 1615, "text": "Button 2: to pick the second date user wants to enter." }, { "code": null, "e": 1707, "s": 1670, "text": "Button 3: to perform the calculation" }, { "code": null, "e": 1748, "s": 1707, "text": "TextView: to show the final output(age)." }, { "code": null, "e": 1840, "s": 1748, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file." }, { "code": null, "e": 1844, "s": 1840, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!-- Parent layout as linear layout--><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\" android:padding=\"10dp\" tools:context=\".MainActivity\"> <!-- linear layout to show datepickers--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <!-- to select the first date--> <Button android:id=\"@+id/bt_birth\" android:layout_width=\"150dp\" android:layout_height=\"50dp\" android:background=\"@android:color/transparent\" android:drawableRight=\"@drawable/ic_baseline\" android:text=\"01/01/2021\" android:textColor=\"@color/black\" android:textSize=\"13sp\" /> <!-- displaying message as \"to\"--> <TextView android:layout_width=\"100dp\" android:layout_height=\"50dp\" android:gravity=\"center_horizontal\" android:text=\"To\" android:textColor=\"@color/black\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <!-- to display date number 2--> <Button android:id=\"@+id/bt_today\" android:layout_width=\"145dp\" android:layout_height=\"50dp\" android:background=\"@android:color/transparent\" android:drawableRight=\"@drawable/ic_baseline\" android:textColor=\"@color/black\" android:textSize=\"13sp\" /> </LinearLayout> <!-- to perform the calculation--> <Button android:id=\"@+id/btn_calculate\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:text=\"calculate\" /> <!-- to display the message \"Result\"--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"50dp\" android:text=\"Result\" android:textColor=\"@android:color/holo_blue_bright\" android:textSize=\"30sp\" android:textStyle=\"bold\" /> <!-- To show the final output(age)--> <TextView android:id=\"@+id/tv_result\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:text=\"0 Years | 0 Months | 0 Days\" android:textSize=\"25sp\" android:textStyle=\"bold\" /> </LinearLayout>", "e": 4484, "s": 1844, "text": null }, { "code": null, "e": 4577, "s": 4484, "text": "After implementing the above code, the design of the activity_main.xml file looks like this." }, { "code": null, "e": 4621, "s": 4577, "text": "Step 4: Working with MainActivity.java file" }, { "code": null, "e": 4786, "s": 4621, "text": "In MainActivity.java file onClickListerner is used on buttons to pick the date and to perform the calculation. Use the following code in the MainActivity.java file." }, { "code": null, "e": 4791, "s": 4786, "text": "Java" }, { "code": "import android.app.DatePickerDialog;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.DatePicker;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.joda.time.Period;import org.joda.time.PeriodType; import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date; public class MainActivity extends AppCompatActivity { // initializing variables Button btn_birth, btn_today, btn_calculate; TextView tvResult; DatePickerDialog.OnDateSetListener dateSetListener1, dateSetListener2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assign variables btn_birth = findViewById(R.id.bt_birth); btn_today = findViewById(R.id.bt_today); btn_calculate = findViewById(R.id.btn_calculate); tvResult = findViewById(R.id.tv_result); // calendar format is imported to pick date Calendar calendar = Calendar.getInstance(); // for year int year = calendar.get(Calendar.YEAR); // for month int month = calendar.get(Calendar.MONTH); // for date int day = calendar.get(Calendar.DAY_OF_MONTH); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"dd/MM/yyyy\"); // to set the current date as by default String date = simpleDateFormat.format(Calendar.getInstance().getTime()); btn_today.setText(date); // action to be performed when button 1 is clicked btn_birth.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // date picker dialog is used // and its style and color are also passed DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, dateSetListener1, year, month, day ); // to set background for datepicker datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); datePickerDialog.show(); } }); // it is used to set the date which user selects dateSetListener1 = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int day) { // here month+1 is used so that // actual month number can be displayed // otherwise it starts from 0 and it shows // 1 number less for every month // example- for january month=0 month = month + 1; String date = day + \"/\" + month + \"/\" + year; btn_birth.setText(date); } }; // action to be performed when button 2 is clicked btn_today.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // date picker dialog is used // and its style and color are also passed DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, dateSetListener2, year, month, day ); // to set background for datepicker datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); datePickerDialog.show(); } }); // it is used to set the date which user selects dateSetListener2 = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int day) { // here month+1 is used so that // actual month number can be displayed // otherwise it starts from 0 and it shows // 1 number less for every month // example- for january month=0 month = month + 1; String date = day + \"/\" + month + \"/\" + year; btn_today.setText(date); } }; // action to be performed when calculate button is clicked btn_calculate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // converting the inputted date to string String sDate = btn_birth.getText().toString(); String eDate = btn_today.getText().toString(); SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat(\"dd/MM/yyyy\"); try { // converting it to date format Date date1 = simpleDateFormat1.parse(sDate); Date date2 = simpleDateFormat1.parse(eDate); long startdate = date1.getTime(); long endDate = date2.getTime(); // condition if (startdate <= endDate) { org.joda.time.Period period = new Period(startdate, endDate, PeriodType.yearMonthDay()); int years = period.getYears(); int months = period.getMonths(); int days = period.getDays(); // show the final output tvResult.setText(years + \" Years |\" + months + \"Months |\" + days + \"Days\"); } else { // show message Toast.makeText(MainActivity.this, \"BirthDate should not be larger then today's date!\", Toast.LENGTH_SHORT).show(); } } catch (ParseException e) { e.printStackTrace(); } } }); }}", "e": 10847, "s": 4791, "text": null }, { "code": null, "e": 11000, "s": 10847, "text": "Congratulations! we have successfully the application to calculate the age or difference between two dates. Here is the final output of our application." }, { "code": null, "e": 11008, "s": 11000, "text": "Output:" }, { "code": null, "e": 11021, "s": 11008, "text": "simmytarika5" }, { "code": null, "e": 11036, "s": 11021, "text": "Android-Studio" }, { "code": null, "e": 11044, "s": 11036, "text": "Android" }, { "code": null, "e": 11049, "s": 11044, "text": "Java" }, { "code": null, "e": 11054, "s": 11049, "text": "Java" }, { "code": null, "e": 11062, "s": 11054, "text": "Android" }, { "code": null, "e": 11160, "s": 11062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11229, "s": 11160, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 11260, "s": 11229, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 11292, "s": 11260, "text": "Android SDK and it's Components" }, { "code": null, "e": 11335, "s": 11292, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 11384, "s": 11335, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 11399, "s": 11384, "text": "Arrays in Java" }, { "code": null, "e": 11443, "s": 11399, "text": "Split() String method in Java with examples" }, { "code": null, "e": 11479, "s": 11443, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 11504, "s": 11479, "text": "Reverse a string in Java" } ]
Explain Encapsulation in PHP.
Object Oriented Programming is a software approach added to PHP5, which helps in building the composite application in an easy way. Some of the OOP concepts added into the PHP5 are an abstraction, interface, static method, and static class, etc... In this article, we will learn Encapsulation and it's implementation through a few examples. The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Encapsulation is a protection mechanism for the data members and methods present inside the class. In the encapsulation technique, we are restricting the data members from access to outside world end-user. In PHP, encapsulation utilized to make the code more secure and robust. Using encapsulation, we are hiding the real implementation of data from the user and also does not allow anyone to manipulate data members except by calling the desired operation. Let' understand this through an example. <?php class ATM { private $custid; private $atmpin; public function PinChange($custid,$atmpin) { ---------perform tasks----- } public function CheckBalance($custid,$atmpin){ ---------perform tasks----- } public function miniStatement($custid) { ---------perform tasks----- } } $obj = new ATM(); $obj ->CheckBalance(10005285637,1**3); ?> In this example, all the ATM class data members (variable) are marked with the private modifier. It implies that we can not directly access ATM class data members (property). So, we can't change the class property directly. The only approach to change the class property (data members) is calling a method (function). That’s the reason we have stated all the ATM class methods with a public access modifier. The user can pass the expected arguments to a class method to perform a particular task. Suppose anyone wants to check balance then he needs to access the CheckBalance() method with the required arguments custid="10005285637"andatmpin="1**3". This is called Data hiding through Encapsulation. We can achieve Encapsulation in PHP through by implementing Access specifiers.
[ { "code": null, "e": 1435, "s": 1187, "text": "Object Oriented Programming is a software approach added to PHP5, which helps in building the composite application in an easy way. Some of the OOP concepts added into the PHP5 are an abstraction, interface, static method, and static class, etc..." }, { "code": null, "e": 1528, "s": 1435, "text": "In this article, we will learn Encapsulation and it's implementation through a few examples." }, { "code": null, "e": 1831, "s": 1528, "text": "The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Encapsulation is a protection mechanism for the data members and methods present inside the class. In the encapsulation technique, we are restricting the data members from access to outside world end-user." }, { "code": null, "e": 2083, "s": 1831, "text": "In PHP, encapsulation utilized to make the code more secure and robust. Using encapsulation, we are hiding the real implementation of data from the user and also does not allow anyone to manipulate data members except by calling the desired operation." }, { "code": null, "e": 2124, "s": 2083, "text": "Let' understand this through an example." }, { "code": null, "e": 2596, "s": 2124, "text": "<?php\n class ATM {\n private $custid;\n private $atmpin;\n public function PinChange($custid,$atmpin) {\n ---------perform tasks-----\n }\n public function CheckBalance($custid,$atmpin){\n ---------perform tasks-----\n }\n public function miniStatement($custid) {\n ---------perform tasks-----\n }\n }\n $obj = new ATM();\n $obj ->CheckBalance(10005285637,1**3);\n?>" }, { "code": null, "e": 3094, "s": 2596, "text": "In this example, all the ATM class data members (variable) are marked with the private modifier. It implies that we can not directly access ATM class data members (property). So, we can't change the class property directly. The only approach to change the class property (data members) is calling a method (function). That’s the reason we have stated all the ATM class methods with a public access modifier. The user can pass the expected arguments to a class method to perform a particular task. " }, { "code": null, "e": 3298, "s": 3094, "text": "Suppose anyone wants to check balance then he needs to access the CheckBalance() method with the required arguments custid=\"10005285637\"andatmpin=\"1**3\". This is called Data hiding through Encapsulation." }, { "code": null, "e": 3377, "s": 3298, "text": "We can achieve Encapsulation in PHP through by implementing Access specifiers." } ]
Symfony - Working Example
In this chapter, we will learn how to create a complete MVC based BookStore Application in Symfony Framework. Following are the steps. Let’s create a new project named “BookStore” in Symfony using the following command. symfony new BookStore Create a BooksController in “src/AppBundle/Controller” directory. It is defined as follows. <?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class BooksController { /** * @Route("/books/author") */ public function authorAction() { return new Response('Book store application!'); } } Now, we have created a BooksController, next create a view to render the action. Let’s create a new folder named “Books” in “app/Resources/views/” directory. Inside the folder, create a file “author.html.twig” and add the following changes. <h3> Simple book store application</h3> Now, render the view in BooksController class. It is defined as follows. <?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class BooksController extends Controller { /** * @Route("/books/author") */ public function authorAction() { return $this->render('books/author.html.twig'); } } As of now, we have created a basic BooksController and the result is rendered. You can check the result in the browser using the URL “http://localhost:8000/books/author”. Configure the database in “app/config/parameters.yml” file. Open the file and add the following changes. # This file is auto-generated during the composer install parameters: database_driver: pdo_mysql database_host: localhost database_port: 3306 database_name: booksdb database_user: <database_username> database_password: <database_password> mailer_transport: smtp mailer_host: 127.0.0.1 mailer_user: null mailer_password: null secret: 0ad4b6d0676f446900a4cb11d96cf0502029620d doctrine: dbal: driver: pdo_mysql host: '%database_host%' dbname: '%database_name%' user: '%database_user%' password: '%database_password%' charset: utf8mb4 Now, Doctrine can connect to your database “booksdb”. Issue the following command to generate “booksdb” database. This step is used to bind the database in Doctrine. php bin/console doctrine:database:create After executing the command, it automatically generates an empty “booksdb” database. You can see the following response on your screen. It will produce the following result − Created database `booksdb` for connection named default Create a Book entity class inside the Entity directory which is located at “src/AppBundle/Entity”. You can directly pass Book class using annotations. It is defined as follows. Add the following code in the file. <?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name = "Books") */ class Book { /** * @ORM\Column(type = "integer") * @ORM\Id * @ORM\GeneratedValue(strategy = "AUTO") */ private $id; /** * @ORM\Column(type = "string", length = 50) */ private $name; /** * @ORM\Column(type = "string", length = 50) */ private $author; /** * @ORM\Column(type = "decimal", scale = 2) */ private $price; } Here, the table name is optional. If the table name is not specified, then it will be determined automatically based on the name of the entity class. Doctrine creates simple entity classes for you. It helps you build any entity. Issue the following command to generate an entity. php bin/console doctrine:generate:entities AppBundle/Entity/Book Then you will see the following result and the entity will be updated. Generating entity "AppBundle\Entity\Book” > backing up Book.php to Book.php~ > generating AppBundle\Entity\Book <?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name = "Books") */ class Book { /** * @ORM\Column(type = "integer") * @ORM\Id * @ORM\GeneratedValue(strategy = "AUTO") */ private $id; /** * @ORM\Column(type = "string", length = 50) */ private $name; /** * @ORM\Column(type = "string", length = 50) */ private $author; /** * @ORM\Column(type = "decimal", scale = 2) */ private $price; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Book */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set author * * @param string $author * * @return Book */ public function setAuthor($author) { $this->author = $author; return $this; } /** * Get author * * @return string */ public function getAuthor() { return $this->author; } /** * Set price * * @param string $price * * @return Book */ public function setPrice($price) { $this->price = $price; return $this; } /** * Get price * * @return string */ public function getPrice() { return $this->price; } } After creating entities, you should validate the mappings using the following command. php bin/console doctrine:schema:validate It will produce the following result − [Mapping] OK - The mapping files are correct [Database] FAIL - The database schema is not in sync with the current mapping file. Since we have not created the Books table, the entity is out of sync. Let us create the Books table using Symfony command in the next step. Doctrine can automatically create all the database tables needed for Book entity. This can be done using the following command. php bin/console doctrine:schema:update --force After executing the command, you will see the following response. Updating database schema... Database schema updated successfully! "1" query was executed Now, again validate the schema using the following command. php bin/console doctrine:schema:validate It will produce the following result − [Mapping] OK - The mapping files are correct. [Database] OK - The database schema is in sync with the mapping files. As seen in the Bind an Entity section, the following command generates all the getters and setters for the Book class. $ php bin/console doctrine:generate:entities AppBundle/Entity/Book Create a method in BooksController that will display the books’ details. /** * @Route("/books/display", name="app_book_display") */ public function displayAction() { $bk = $this->getDoctrine() ->getRepository('AppBundle:Book') ->findAll(); return $this->render('books/display.html.twig', array('data' => $bk)); } Let’s create a view that points to display action. Move to the views directory and create file “display.html.twig”. Add the following changes in the file. {% extends 'base.html.twig' %} {% block stylesheets %} <style> .table { border-collapse: collapse; } .table th, td { border-bottom: 1px solid #ddd; width: 250px; text-align: left; align: left; } </style> {% endblock %} {% block body %} <h2>Books database application!</h2> <table class = "table"> <tr> <th>Name</th> <th>Author</th> <th>Price</th> </tr> {% for x in data %} <tr> <td>{{ x.Name }}</td> <td>{{ x.Author }}</td> <td>{{ x.Price }}</td> </tr> {% endfor %} </table> {% endblock %} You can obtain the result by requesting the URL “http://localhost:8000/books/display” in the browser. Let's create a functionality to add a book into the system. Create a new page, newAction method in the BooksController as follows. // use section use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; // methods section /** * @Route("/books/new") */ public function newAction(Request $request) { $stud = new StudentForm(); $form = $this->createFormBuilder($stud) ->add('name', TextType::class) ->add('author', TextType::class) ->add('price', TextType::class) ->add('save', SubmitType::class, array('label' => 'Submit')) ->getForm(); return $this->render('books/new.html.twig', array('form' => $form->createView(),)); } Let’s create a view that points to a new action. Move to the views directory and create a file “new.html.twig”. Add the following changes in the file. {% extends 'base.html.twig' %} {% block stylesheets %} <style> #simpleform { width:600px; border:2px solid grey; padding:14px; } #simpleform label { font-size:14px; float:left; width:300px; text-align:right; display:block; } #simpleform span { font-size:11px; color:grey; width:100px; text-align:right; display:block; } #simpleform input { border:1px solid grey; font-family:verdana; font-size:14px; color:light blue; height:24px; width:250px; margin: 0 0 10px 10px; } #simpleform textarea { border:1px solid grey; font-family:verdana; font-size:14px; color:light blue; height:120px; width:250px; margin: 0 0 20px 10px; } #simpleform select { margin: 0 0 20px 10px; } #simpleform button { clear:both; margin-left:250px; background: grey; color:#FFFFFF; border:solid 1px #666666; font-size:16px; } </style> {% endblock %} {% block body %} <h3>Book details:</h3> <div id = "simpleform"> {{ form_start(form) }} {{ form_widget(form) }} {{ form_end(form) }} </div> {% endblock %} It will produce the following screen as output − Let's change the newAction method and include the code to handle form submission. Also, store the book information into the database. /** * @Route("/books/new", name="app_book_new") */ public function newAction(Request $request) { $book = new Book(); $form = $this->createFormBuilder($book) ->add('name', TextType::class) ->add('author', TextType::class) ->add('price', TextType::class) ->add('save', SubmitType::class, array('label' => 'Submit')) ->getForm(); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $book = $form->getData(); $doct = $this->getDoctrine()->getManager(); // tells Doctrine you want to save the Product $doct->persist($book); //executes the queries (i.e. the INSERT query) $doct->flush(); return $this->redirectToRoute('app_book_display'); } else { return $this->render('books/new.html.twig', array( 'form' => $form->createView(), )); } } Once the book is stored into the database, redirect to the book display page. To update the book, create an action, updateAction, and add the following changes. /** * @Route("/books/update/{id}", name = "app_book_update" ) */ public function updateAction($id, Request $request) { $doct = $this->getDoctrine()->getManager(); $bk = $doct->getRepository('AppBundle:Book')->find($id); if (!$bk) { throw $this->createNotFoundException( 'No book found for id '.$id ); } $form = $this->createFormBuilder($bk) ->add('name', TextType::class) ->add('author', TextType::class) ->add('price', TextType::class) ->add('save', SubmitType::class, array('label' => 'Submit')) ->getForm(); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $book = $form->getData(); $doct = $this->getDoctrine()->getManager(); // tells Doctrine you want to save the Product $doct->persist($book); //executes the queries (i.e. the INSERT query) $doct->flush(); return $this->redirectToRoute('app_book_display'); } else { return $this->render('books/new.html.twig', array( 'form' => $form->createView(), )); } } Here, we are processing two functionalities. If the request only contains id, then we fetch it from the database and show it in the book form. And, if the request contains full book information, then we update the details in the database and redirect to the book display page. Deleting an object requires a call to the remove() method of the entity (doctrine) manager. This can be done using the following code. /** * @Route("/books/delete/{id}", name="app_book_delete") */ public function deleteAction($id) { $doct = $this->getDoctrine()->getManager(); $bk = $doct->getRepository('AppBundle:Book')->find($id); if (!$bk) { throw $this->createNotFoundException('No book found for id '.$id); } $doct->remove($bk); $doct->flush(); return $this->redirectToRoute('app_book_display'); } Here, we deleted the book and redirected to book display page. Now, update the body block in display view and include include add / edit / delete links as follows. {% block body %} <h2>Books database application!</h2> <div> <a href = "{{ path('app_book_new') }}">Add</a> </div> <table class = "table"> <tr> <th>Name</th> <th>Author</th> <th>Price</th> <th></th> <th></th> </tr> {% for x in data %} <tr> <td>{{ x.Name }}</td> <td>{{ x.Author }}</td> <td>{{ x.Price }}</td> <td><a href = "{{ path('app_book_update', { 'id' : x.Id }) }}">Edit</a></td> <td><a href = "{{ path('app_book_delete', { 'id' : x.Id }) }}">Delete</a></td> </tr> {% endfor %} </table> {% endblock %} It will produce the following screen as output − Symfony comprises of a set of PHP components, an application framework, a community and a philosophy. Symfony is extremely flexible and capable of meeting all the requirements of advanced users, professionals, and an ideal choice for all the beginners with PHP.
[ { "code": null, "e": 2472, "s": 2337, "text": "In this chapter, we will learn how to create a complete MVC based BookStore Application in Symfony Framework. Following are the steps." }, { "code": null, "e": 2557, "s": 2472, "text": "Let’s create a new project named “BookStore” in Symfony using the following command." }, { "code": null, "e": 2580, "s": 2557, "text": "symfony new BookStore\n" }, { "code": null, "e": 2672, "s": 2580, "text": "Create a BooksController in “src/AppBundle/Controller” directory. It is defined as follows." }, { "code": null, "e": 3058, "s": 2672, "text": "<?php \nnamespace AppBundle\\Controller; \n\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Route; \nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller; \nuse Symfony\\Component\\HttpFoundation\\Response; \n\nclass BooksController { \n /** \n * @Route(\"/books/author\") \n */ \n public function authorAction() { \n return new Response('Book store application!'); \n } \n}" }, { "code": null, "e": 3139, "s": 3058, "text": "Now, we have created a BooksController, next create a view to render the action." }, { "code": null, "e": 3299, "s": 3139, "text": "Let’s create a new folder named “Books” in “app/Resources/views/” directory. Inside the folder, create a file “author.html.twig” and add the following changes." }, { "code": null, "e": 3341, "s": 3299, "text": "<h3> Simple book store application</h3> \n" }, { "code": null, "e": 3414, "s": 3341, "text": "Now, render the view in BooksController class. It is defined as follows." }, { "code": null, "e": 3819, "s": 3414, "text": "<?php \nnamespace AppBundle\\Controller; \n\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Route; \nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller; \nuse Symfony\\Component\\HttpFoundation\\Response; \n\nclass BooksController extends Controller { \n /** \n * @Route(\"/books/author\") \n */ \n public function authorAction() { \n return $this->render('books/author.html.twig'); \n } \n}" }, { "code": null, "e": 3990, "s": 3819, "text": "As of now, we have created a basic BooksController and the result is rendered. You can check the result in the browser using the URL “http://localhost:8000/books/author”." }, { "code": null, "e": 4050, "s": 3990, "text": "Configure the database in “app/config/parameters.yml” file." }, { "code": null, "e": 4095, "s": 4050, "text": "Open the file and add the following changes." }, { "code": null, "e": 4743, "s": 4095, "text": "# This file is auto-generated during the composer install \nparameters: \n database_driver: pdo_mysql \n database_host: localhost \n database_port: 3306 \n database_name: booksdb \n database_user: <database_username> \n database_password: <database_password> \n mailer_transport: smtp \n mailer_host: 127.0.0.1 \n mailer_user: null \n mailer_password: null \n secret: 0ad4b6d0676f446900a4cb11d96cf0502029620d \n \n doctrine: \n dbal: \n driver: pdo_mysql \n host: '%database_host%' \n dbname: '%database_name%' \n user: '%database_user%' \n password: '%database_password%' \n charset: utf8mb4 \n" }, { "code": null, "e": 4797, "s": 4743, "text": "Now, Doctrine can connect to your database “booksdb”." }, { "code": null, "e": 4909, "s": 4797, "text": "Issue the following command to generate “booksdb” database. This step is used to bind the database in Doctrine." }, { "code": null, "e": 4951, "s": 4909, "text": "php bin/console doctrine:database:create\n" }, { "code": null, "e": 5087, "s": 4951, "text": "After executing the command, it automatically generates an empty “booksdb” database. You can see the following response on your screen." }, { "code": null, "e": 5126, "s": 5087, "text": "It will produce the following result −" }, { "code": null, "e": 5184, "s": 5126, "text": "Created database `booksdb` for connection named default \n" }, { "code": null, "e": 5283, "s": 5184, "text": "Create a Book entity class inside the Entity directory which is located at “src/AppBundle/Entity”." }, { "code": null, "e": 5361, "s": 5283, "text": "You can directly pass Book class using annotations. It is defined as follows." }, { "code": null, "e": 5397, "s": 5361, "text": "Add the following code in the file." }, { "code": null, "e": 5958, "s": 5397, "text": "<?php \nnamespace AppBundle\\Entity; \nuse Doctrine\\ORM\\Mapping as ORM; \n\n/** \n * @ORM\\Entity \n * @ORM\\Table(name = \"Books\") \n*/ \nclass Book { \n /** \n * @ORM\\Column(type = \"integer\") \n * @ORM\\Id \n * @ORM\\GeneratedValue(strategy = \"AUTO\") \n */ \n private $id; \n \n /** \n * @ORM\\Column(type = \"string\", length = 50) \n */ \n private $name; \n \n /** \n * @ORM\\Column(type = \"string\", length = 50) \n */ \n \n private $author;\n /** \n * @ORM\\Column(type = \"decimal\", scale = 2) \n */ \n private $price; \n} " }, { "code": null, "e": 5992, "s": 5958, "text": "Here, the table name is optional." }, { "code": null, "e": 6108, "s": 5992, "text": "If the table name is not specified, then it will be determined automatically based on the name of the entity class." }, { "code": null, "e": 6187, "s": 6108, "text": "Doctrine creates simple entity classes for you. It helps you build any entity." }, { "code": null, "e": 6238, "s": 6187, "text": "Issue the following command to generate an entity." }, { "code": null, "e": 6304, "s": 6238, "text": "php bin/console doctrine:generate:entities AppBundle/Entity/Book\n" }, { "code": null, "e": 6375, "s": 6304, "text": "Then you will see the following result and the entity will be updated." }, { "code": null, "e": 6497, "s": 6375, "text": "Generating entity \"AppBundle\\Entity\\Book” \n > backing up Book.php to Book.php~ \n > generating AppBundle\\Entity\\Book \n" }, { "code": null, "e": 8228, "s": 6497, "text": "<?php \nnamespace AppBundle\\Entity; \n\nuse Doctrine\\ORM\\Mapping as ORM; \n/** \n * @ORM\\Entity \n * @ORM\\Table(name = \"Books\") \n*/ \nclass Book { \n /** \n * @ORM\\Column(type = \"integer\") \n * @ORM\\Id\n * @ORM\\GeneratedValue(strategy = \"AUTO\") \n */ \n private $id; \n \n /** \n * @ORM\\Column(type = \"string\", length = 50) \n */ \n private $name; \n \n /** \n * @ORM\\Column(type = \"string\", length = 50) \n */ \n private $author; \n \n /** \n * @ORM\\Column(type = \"decimal\", scale = 2) \n */ \n private $price; \n \n /** \n * Get id \n * \n * @return integer \n */ \n public function getId() { \n return $this->id; \n } \n \n /** \n * Set name \n * \n * @param string $name \n * \n * @return Book \n */\n public function setName($name) { \n $this->name = $name; \n return $this; \n } \n \n /** \n * Get name \n * \n * @return string \n */ \n public function getName() { \n return $this->name; \n } \n \n /** \n * Set author \n * \n * @param string $author \n * \n * @return Book \n */ \n public function setAuthor($author) { \n $this->author = $author; \n return $this; \n } \n \n /** \n * Get author \n * \n * @return string \n */ \n public function getAuthor() {\n return $this->author; \n } \n \n /** \n * Set price \n * \n * @param string $price \n * \n * @return Book \n */ \n public function setPrice($price) { \n $this->price = $price; \n return $this; \n } \n \n /** \n * Get price \n * \n * @return string \n */ \n public function getPrice() { \n return $this->price; \n } \n} " }, { "code": null, "e": 8315, "s": 8228, "text": "After creating entities, you should validate the mappings using the following command." }, { "code": null, "e": 8357, "s": 8315, "text": "php bin/console doctrine:schema:validate " }, { "code": null, "e": 8396, "s": 8357, "text": "It will produce the following result −" }, { "code": null, "e": 8527, "s": 8396, "text": "[Mapping] OK - The mapping files are correct\n[Database] FAIL - The database schema is not in sync with the current mapping file.\n" }, { "code": null, "e": 8667, "s": 8527, "text": "Since we have not created the Books table, the entity is out of sync. Let us create the Books table using Symfony command in the next step." }, { "code": null, "e": 8795, "s": 8667, "text": "Doctrine can automatically create all the database tables needed for Book entity. This can be done using the following command." }, { "code": null, "e": 8843, "s": 8795, "text": "php bin/console doctrine:schema:update --force\n" }, { "code": null, "e": 8909, "s": 8843, "text": "After executing the command, you will see the following response." }, { "code": null, "e": 9001, "s": 8909, "text": "Updating database schema... \nDatabase schema updated successfully! \"1\" query was executed \n" }, { "code": null, "e": 9061, "s": 9001, "text": "Now, again validate the schema using the following command." }, { "code": null, "e": 9104, "s": 9061, "text": "php bin/console doctrine:schema:validate \n" }, { "code": null, "e": 9143, "s": 9104, "text": "It will produce the following result −" }, { "code": null, "e": 9264, "s": 9143, "text": "[Mapping] OK - The mapping files are correct. \n[Database] OK - The database schema is in sync with the mapping files. \n" }, { "code": null, "e": 9383, "s": 9264, "text": "As seen in the Bind an Entity section, the following command generates all the getters and setters for the Book class." }, { "code": null, "e": 9451, "s": 9383, "text": "$ php bin/console doctrine:generate:entities AppBundle/Entity/Book\n" }, { "code": null, "e": 9524, "s": 9451, "text": "Create a method in BooksController that will display the books’ details." }, { "code": null, "e": 9786, "s": 9524, "text": "/** \n * @Route(\"/books/display\", name=\"app_book_display\") \n*/ \npublic function displayAction() { \n $bk = $this->getDoctrine()\n ->getRepository('AppBundle:Book') \n ->findAll(); \n return $this->render('books/display.html.twig', array('data' => $bk)); \n}" }, { "code": null, "e": 9941, "s": 9786, "text": "Let’s create a view that points to display action. Move to the views directory and create file “display.html.twig”. Add the following changes in the file." }, { "code": null, "e": 10639, "s": 9941, "text": "{% extends 'base.html.twig' %} \n{% block stylesheets %} \n <style> \n .table { border-collapse: collapse; } \n .table th, td { \n border-bottom: 1px solid #ddd; \n width: 250px; \n text-align: left; \n align: left; \n } \n </style> \n{% endblock %} \n{% block body %} \n <h2>Books database application!</h2> \n <table class = \"table\"> \n <tr> \n <th>Name</th> \n <th>Author</th> \n <th>Price</th> \n </tr> \n {% for x in data %} \n <tr> \n <td>{{ x.Name }}</td> \n <td>{{ x.Author }}</td>\n <td>{{ x.Price }}</td> \n </tr> \n {% endfor %} \n </table> \n{% endblock %} " }, { "code": null, "e": 10741, "s": 10639, "text": "You can obtain the result by requesting the URL “http://localhost:8000/books/display” in the browser." }, { "code": null, "e": 10872, "s": 10741, "text": "Let's create a functionality to add a book into the system. Create a new page, newAction method in the BooksController as follows." }, { "code": null, "e": 11548, "s": 10872, "text": "// use section \nuse Symfony\\Component\\HttpFoundation\\Request; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\SubmitType; \n\n// methods section \n/** \n * @Route(\"/books/new\") \n*/ \n\npublic function newAction(Request $request) { \n $stud = new StudentForm();\n $form = $this->createFormBuilder($stud) \n ->add('name', TextType::class) \n ->add('author', TextType::class) \n ->add('price', TextType::class) \n ->add('save', SubmitType::class, array('label' => 'Submit')) \n ->getForm(); \n return $this->render('books/new.html.twig', array('form' => $form->createView(),)); \n} " }, { "code": null, "e": 11699, "s": 11548, "text": "Let’s create a view that points to a new action. Move to the views directory and create a file “new.html.twig”. Add the following changes in the file." }, { "code": null, "e": 13163, "s": 11699, "text": "{% extends 'base.html.twig' %} \n{% block stylesheets %} \n <style> \n #simpleform { \n width:600px; \n border:2px solid grey; \n padding:14px; \n } \n #simpleform label { \n font-size:14px; \n float:left; \n width:300px; \n text-align:right; \n display:block; \n } \n #simpleform span { \n font-size:11px; \n color:grey;\n width:100px; \n text-align:right; \n display:block; \n } \n #simpleform input { \n border:1px solid grey; \n font-family:verdana; \n font-size:14px; \n color:light blue; \n height:24px; \n width:250px; \n margin: 0 0 10px 10px; \n } \n #simpleform textarea { \n border:1px solid grey; \n font-family:verdana; \n font-size:14px; \n color:light blue; \n height:120px; \n width:250px; \n margin: 0 0 20px 10px; \n } \n #simpleform select { \n margin: 0 0 20px 10px; \n } \n #simpleform button { \n clear:both; \n margin-left:250px; \n background: grey;\n color:#FFFFFF; \n border:solid 1px #666666; \n font-size:16px; \n } \n </style> \n{% endblock %} \n{% block body %} \n <h3>Book details:</h3> \n <div id = \"simpleform\"> \n {{ form_start(form) }} \n {{ form_widget(form) }} \n {{ form_end(form) }} \n </div> \n{% endblock %} " }, { "code": null, "e": 13212, "s": 13163, "text": "It will produce the following screen as output −" }, { "code": null, "e": 13346, "s": 13212, "text": "Let's change the newAction method and include the code to handle form submission. Also, store the book information into the database." }, { "code": null, "e": 14286, "s": 13346, "text": "/**\n * @Route(\"/books/new\", name=\"app_book_new\") \n*/ \npublic function newAction(Request $request) { \n $book = new Book(); \n $form = $this->createFormBuilder($book) \n ->add('name', TextType::class) \n ->add('author', TextType::class) \n ->add('price', TextType::class) \n ->add('save', SubmitType::class, array('label' => 'Submit')) \n ->getForm(); \n \n $form->handleRequest($request); \n \n if ($form->isSubmitted() && $form->isValid()) { \n $book = $form->getData(); \n $doct = $this->getDoctrine()->getManager(); \n \n // tells Doctrine you want to save the Product \n $doct->persist($book); \n \n //executes the queries (i.e. the INSERT query) \n $doct->flush(); \n \n return $this->redirectToRoute('app_book_display'); \n } else { \n return $this->render('books/new.html.twig', array( \n 'form' => $form->createView(), \n )); \n } \n} " }, { "code": null, "e": 14364, "s": 14286, "text": "Once the book is stored into the database, redirect to the book display page." }, { "code": null, "e": 14447, "s": 14364, "text": "To update the book, create an action, updateAction, and add the following changes." }, { "code": null, "e": 15609, "s": 14447, "text": "/** \n * @Route(\"/books/update/{id}\", name = \"app_book_update\" ) \n*/ \npublic function updateAction($id, Request $request) { \n $doct = $this->getDoctrine()->getManager(); \n $bk = $doct->getRepository('AppBundle:Book')->find($id); \n \n if (!$bk) { \n throw $this->createNotFoundException( \n 'No book found for id '.$id \n ); \n } \n $form = $this->createFormBuilder($bk) \n ->add('name', TextType::class) \n ->add('author', TextType::class) \n ->add('price', TextType::class) \n ->add('save', SubmitType::class, array('label' => 'Submit')) \n ->getForm(); \n \n $form->handleRequest($request); \n \n if ($form->isSubmitted() && $form->isValid()) { \n $book = $form->getData(); \n $doct = $this->getDoctrine()->getManager(); \n \n // tells Doctrine you want to save the Product \n $doct->persist($book); \n \n //executes the queries (i.e. the INSERT query) \n $doct->flush(); \n return $this->redirectToRoute('app_book_display'); \n } else { \n return $this->render('books/new.html.twig', array(\n 'form' => $form->createView(), \n )); \n } \n} " }, { "code": null, "e": 15886, "s": 15609, "text": "Here, we are processing two functionalities. If the request only contains id, then we fetch it from the database and show it in the book form. And, if the request contains full book information, then we update the details in the database and redirect to the book display page." }, { "code": null, "e": 15978, "s": 15886, "text": "Deleting an object requires a call to the remove() method of the entity (doctrine) manager." }, { "code": null, "e": 16021, "s": 15978, "text": "This can be done using the following code." }, { "code": null, "e": 16437, "s": 16021, "text": "/** \n * @Route(\"/books/delete/{id}\", name=\"app_book_delete\") \n*/ \npublic function deleteAction($id) { \n $doct = $this->getDoctrine()->getManager(); \n $bk = $doct->getRepository('AppBundle:Book')->find($id); \n \n if (!$bk) { \n throw $this->createNotFoundException('No book found for id '.$id); \n } \n $doct->remove($bk); \n $doct->flush(); \n return $this->redirectToRoute('app_book_display'); \n} " }, { "code": null, "e": 16500, "s": 16437, "text": "Here, we deleted the book and redirected to book display page." }, { "code": null, "e": 16601, "s": 16500, "text": "Now, update the body block in display view and include include add / edit / delete links as follows." }, { "code": null, "e": 17291, "s": 16601, "text": "{% block body %} \n <h2>Books database application!</h2> \n <div> \n <a href = \"{{ path('app_book_new') }}\">Add</a> \n </div> \n <table class = \"table\"> \n <tr> \n <th>Name</th> \n <th>Author</th> \n <th>Price</th> \n <th></th> \n <th></th> \n </tr> \n {% for x in data %} \n <tr> \n <td>{{ x.Name }}</td> \n <td>{{ x.Author }}</td> \n <td>{{ x.Price }}</td> \n <td><a href = \"{{ path('app_book_update', { 'id' : x.Id }) }}\">Edit</a></td>\n <td><a href = \"{{ path('app_book_delete', { 'id' : x.Id }) }}\">Delete</a></td>\n </tr> \n {% endfor %} \n </table> \n{% endblock %} " }, { "code": null, "e": 17340, "s": 17291, "text": "It will produce the following screen as output −" } ]
Internal working of Set/HashSet in Java
11 Dec, 2018 As we know that a set is a well-defined collection of distinct objects. Each member of a set is called an element of the set. So in other words, we can say that a set will never contain duplicate elements. But how in java Set interface implemented classes like HashSet, LinkedHashSet, TreeSet etc. achieve this uniqueness. In this post, we will discuss the hidden truth behind this uniqueness. How HashSet works internally in Java? We will understand this with an example.Let us see the output of the following program which try to add duplicate elements in a HashSet. // Java program to demonstrate// internal working of HashSet import java.util.HashSet; class Test{ public static void main(String args[]) { // creating a HashSet HashSet hs = new HashSet(); // adding elements to hashset // using add() method boolean b1 = hs.add("Geeks"); boolean b2 = hs.add("GeeksforGeeks"); // adding duplicate element boolean b3 = hs.add("Geeks"); // printing b1, b2, b3 System.out.println("b1 = "+b1); System.out.println("b2 = "+b2); System.out.println("b3 = "+b3); // printing all elements of hashset System.out.println(hs); }} Output: b1 = true b2 = true b3 = false [GeeksforGeeks, Geeks] Now from the output, it is clear that when we try to add a duplicate element to a set using add() method, it returns false, and element is not added to hashset, as it is already present. Now the question comes, how add() method checks whether the set already contains the specified element or not. It will be more clear if we have a closer look on the add() method and default constructor in HashSet class. // predefined HashSet class public class HashSet { // A HashMap object private transient HashMap map; // A Dummy value(PRESENT) to associate with an Object in the Map private static final Object PRESENT = new Object(); // default constructor of HashSet class // It creates a HashMap by calling // default constructor of HashMap class public HashSet() { map = new HashMap<>(); } // add method // it calls put() method on map object // and then compares it's return value with null public boolean add(E e) { return map.put(e, PRESENT)==null; } // Other methods in Hash Set } Now as you can see that whenever we create a HashSet, it internally creates a HashMap and if we insert an element into this HashSet using add() method, it actually call put() method on internally created HashMap object with element you have specified as it’s key and constant Object called “PRESENT” as it’s value. So we can say that a Set achieves uniqueness internally through HashMap. Now the whole story comes around how a HashMap and put() method internally works. As we know in a HashMap each key is unique and when we call put(Key, Value) method, it returns the previous value associated with key, or null if there was no mapping for key. So in add() method we check the return value of map.put(key, value) method with null value. If map.put(key, value) returns null, then the statement “map.put(e, PRESENT) == null” will return true and element is added to the HashSet(internally HashMap).If map.put(key, value) returns old value of the key, then the statement “map.put(e, PRESENT) == null” will return false and element is not added to the HashSet(internally HashMap). If map.put(key, value) returns null, then the statement “map.put(e, PRESENT) == null” will return true and element is added to the HashSet(internally HashMap). If map.put(key, value) returns old value of the key, then the statement “map.put(e, PRESENT) == null” will return false and element is not added to the HashSet(internally HashMap). As LinkedHashSet extends HashSet, so it internally calls constructors of HashSet using super(). Similarly creating an object of TreeSet class internally creates object of Navigable Map as backing map. Related Article : How HashMap internally works in Java. 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-Collections java-hashset Java-Set-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Stack Class in Java Introduction to Java Constructors in Java Initializing a List in Java Multithreading in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Dec, 2018" }, { "code": null, "e": 446, "s": 52, "text": "As we know that a set is a well-defined collection of distinct objects. Each member of a set is called an element of the set. So in other words, we can say that a set will never contain duplicate elements. But how in java Set interface implemented classes like HashSet, LinkedHashSet, TreeSet etc. achieve this uniqueness. In this post, we will discuss the hidden truth behind this uniqueness." }, { "code": null, "e": 484, "s": 446, "text": "How HashSet works internally in Java?" }, { "code": null, "e": 621, "s": 484, "text": "We will understand this with an example.Let us see the output of the following program which try to add duplicate elements in a HashSet." }, { "code": "// Java program to demonstrate// internal working of HashSet import java.util.HashSet; class Test{ public static void main(String args[]) { // creating a HashSet HashSet hs = new HashSet(); // adding elements to hashset // using add() method boolean b1 = hs.add(\"Geeks\"); boolean b2 = hs.add(\"GeeksforGeeks\"); // adding duplicate element boolean b3 = hs.add(\"Geeks\"); // printing b1, b2, b3 System.out.println(\"b1 = \"+b1); System.out.println(\"b2 = \"+b2); System.out.println(\"b3 = \"+b3); // printing all elements of hashset System.out.println(hs); }}", "e": 1339, "s": 621, "text": null }, { "code": null, "e": 1347, "s": 1339, "text": "Output:" }, { "code": null, "e": 1402, "s": 1347, "text": "b1 = true\nb2 = true\nb3 = false\n[GeeksforGeeks, Geeks]\n" }, { "code": null, "e": 1809, "s": 1402, "text": "Now from the output, it is clear that when we try to add a duplicate element to a set using add() method, it returns false, and element is not added to hashset, as it is already present. Now the question comes, how add() method checks whether the set already contains the specified element or not. It will be more clear if we have a closer look on the add() method and default constructor in HashSet class." }, { "code": null, "e": 2471, "s": 1809, "text": "// predefined HashSet class\npublic class HashSet\n{\n // A HashMap object \n private transient HashMap map;\n\n // A Dummy value(PRESENT) to associate with an Object in the Map\n private static final Object PRESENT = new Object();\n \n // default constructor of HashSet class\n // It creates a HashMap by calling \n // default constructor of HashMap class\n public HashSet() {\n map = new HashMap<>();\n }\n\n // add method \n // it calls put() method on map object\n // and then compares it's return value with null\n public boolean add(E e) {\n return map.put(e, PRESENT)==null;\n }\n \n // Other methods in Hash Set\n}\n" }, { "code": null, "e": 2941, "s": 2471, "text": "Now as you can see that whenever we create a HashSet, it internally creates a HashMap and if we insert an element into this HashSet using add() method, it actually call put() method on internally created HashMap object with element you have specified as it’s key and constant Object called “PRESENT” as it’s value. So we can say that a Set achieves uniqueness internally through HashMap. Now the whole story comes around how a HashMap and put() method internally works." }, { "code": null, "e": 3209, "s": 2941, "text": "As we know in a HashMap each key is unique and when we call put(Key, Value) method, it returns the previous value associated with key, or null if there was no mapping for key. So in add() method we check the return value of map.put(key, value) method with null value." }, { "code": null, "e": 3549, "s": 3209, "text": "If map.put(key, value) returns null, then the statement “map.put(e, PRESENT) == null” will return true and element is added to the HashSet(internally HashMap).If map.put(key, value) returns old value of the key, then the statement “map.put(e, PRESENT) == null” will return false and element is not added to the HashSet(internally HashMap)." }, { "code": null, "e": 3709, "s": 3549, "text": "If map.put(key, value) returns null, then the statement “map.put(e, PRESENT) == null” will return true and element is added to the HashSet(internally HashMap)." }, { "code": null, "e": 3890, "s": 3709, "text": "If map.put(key, value) returns old value of the key, then the statement “map.put(e, PRESENT) == null” will return false and element is not added to the HashSet(internally HashMap)." }, { "code": null, "e": 4091, "s": 3890, "text": "As LinkedHashSet extends HashSet, so it internally calls constructors of HashSet using super(). Similarly creating an object of TreeSet class internally creates object of Navigable Map as backing map." }, { "code": null, "e": 4147, "s": 4091, "text": "Related Article : How HashMap internally works in Java." }, { "code": null, "e": 4449, "s": 4147, "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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4574, "s": 4449, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4591, "s": 4574, "text": "Java-Collections" }, { "code": null, "e": 4604, "s": 4591, "text": "java-hashset" }, { "code": null, "e": 4622, "s": 4604, "text": "Java-Set-Programs" }, { "code": null, "e": 4627, "s": 4622, "text": "Java" }, { "code": null, "e": 4632, "s": 4627, "text": "Java" }, { "code": null, "e": 4649, "s": 4632, "text": "Java-Collections" }, { "code": null, "e": 4747, "s": 4649, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4766, "s": 4747, "text": "Interfaces in Java" }, { "code": null, "e": 4781, "s": 4766, "text": "Stream In Java" }, { "code": null, "e": 4799, "s": 4781, "text": "ArrayList in Java" }, { "code": null, "e": 4819, "s": 4799, "text": "Collections in Java" }, { "code": null, "e": 4843, "s": 4819, "text": "Singleton Class in Java" }, { "code": null, "e": 4863, "s": 4843, "text": "Stack Class in Java" }, { "code": null, "e": 4884, "s": 4863, "text": "Introduction to Java" }, { "code": null, "e": 4905, "s": 4884, "text": "Constructors in Java" }, { "code": null, "e": 4933, "s": 4905, "text": "Initializing a List in Java" } ]
PHP | floatval() Function
25 Jun, 2018 The floatval() function is an inbuilt function in PHP which returns the float value of a variable. Syntax: float floatval ( $var ) Parameters: This function accepts one parameter which is mandatory and described below: $var: The variable whose corresponding float value will be returned. This variable should not be an object. Return Value: It returns float value of given variable. Empty array returns 0 and non-empty array returns 1. Note: If an object is passed to the function, it produce an E_NOTICE level error and return 1. Examples: Input : $var = '41.68127E3' Output : 41681.27 Input : $var = '47.129mln' Output : 47.129 Below programs illustrate the use of floatval() function in PHP:Program 1: <?php$var = '41.68127E3';$float_value = floatval($var);echo $float_value;?> 41681.27 Program 2: <?php$var = '47.129mln';$float_value = floatval($var);echo $float_value;?> 47.129 Reference: http://php.net/manual/en/function.floatval.php PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2018" }, { "code": null, "e": 127, "s": 28, "text": "The floatval() function is an inbuilt function in PHP which returns the float value of a variable." }, { "code": null, "e": 135, "s": 127, "text": "Syntax:" }, { "code": null, "e": 160, "s": 135, "text": "float floatval ( $var )\n" }, { "code": null, "e": 248, "s": 160, "text": "Parameters: This function accepts one parameter which is mandatory and described below:" }, { "code": null, "e": 356, "s": 248, "text": "$var: The variable whose corresponding float value will be returned. This variable should not be an object." }, { "code": null, "e": 465, "s": 356, "text": "Return Value: It returns float value of given variable. Empty array returns 0 and non-empty array returns 1." }, { "code": null, "e": 560, "s": 465, "text": "Note: If an object is passed to the function, it produce an E_NOTICE level error and return 1." }, { "code": null, "e": 570, "s": 560, "text": "Examples:" }, { "code": null, "e": 661, "s": 570, "text": "Input : $var = '41.68127E3'\nOutput : 41681.27\n\nInput : $var = '47.129mln'\nOutput : 47.129\n" }, { "code": null, "e": 736, "s": 661, "text": "Below programs illustrate the use of floatval() function in PHP:Program 1:" }, { "code": "<?php$var = '41.68127E3';$float_value = floatval($var);echo $float_value;?>", "e": 812, "s": 736, "text": null }, { "code": null, "e": 822, "s": 812, "text": "41681.27\n" }, { "code": null, "e": 833, "s": 822, "text": "Program 2:" }, { "code": "<?php$var = '47.129mln';$float_value = floatval($var);echo $float_value;?>", "e": 908, "s": 833, "text": null }, { "code": null, "e": 916, "s": 908, "text": "47.129\n" }, { "code": null, "e": 974, "s": 916, "text": "Reference: http://php.net/manual/en/function.floatval.php" }, { "code": null, "e": 987, "s": 974, "text": "PHP-function" }, { "code": null, "e": 991, "s": 987, "text": "PHP" }, { "code": null, "e": 1008, "s": 991, "text": "Web Technologies" }, { "code": null, "e": 1012, "s": 1008, "text": "PHP" }, { "code": null, "e": 1110, "s": 1012, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1160, "s": 1110, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1200, "s": 1160, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 1261, "s": 1200, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 1311, "s": 1261, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 1356, "s": 1311, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 1418, "s": 1356, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1451, "s": 1418, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1512, "s": 1451, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1562, "s": 1512, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | numpy.fill_diagonal() method
27 Sep, 2019 With the help of numpy.fill_diagonal() method, we can get filled the diagonals of numpy array with the value passed as the parameter in numpy.fill_diagonal() method. Syntax : numpy.fill_diagonal(array, value)Return : Return the filled value in the diagonal of an array. Example #1 :In this example we can see that by using numpy.fill_diagonal() method, we are able to get the diagonals filled with the values passed as parameter. # import numpyimport numpy as np # using numpy.fill_diagonal() methodarray = np.array([[1, 2], [2, 1]])np.fill_diagonal(array, 5) print(array) Output : [[5 2][2 5]] Example #2 : # import numpyimport numpy as np # using numpy.fill_diagonal() methodarray = np.zeros((3, 3), int)np.fill_diagonal(array, 1) print(array) Output : [[1 0 0][0 1 0][0 0 1]] Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2019" }, { "code": null, "e": 194, "s": 28, "text": "With the help of numpy.fill_diagonal() method, we can get filled the diagonals of numpy array with the value passed as the parameter in numpy.fill_diagonal() method." }, { "code": null, "e": 298, "s": 194, "text": "Syntax : numpy.fill_diagonal(array, value)Return : Return the filled value in the diagonal of an array." }, { "code": null, "e": 458, "s": 298, "text": "Example #1 :In this example we can see that by using numpy.fill_diagonal() method, we are able to get the diagonals filled with the values passed as parameter." }, { "code": "# import numpyimport numpy as np # using numpy.fill_diagonal() methodarray = np.array([[1, 2], [2, 1]])np.fill_diagonal(array, 5) print(array)", "e": 603, "s": 458, "text": null }, { "code": null, "e": 612, "s": 603, "text": "Output :" }, { "code": null, "e": 625, "s": 612, "text": "[[5 2][2 5]]" }, { "code": null, "e": 638, "s": 625, "text": "Example #2 :" }, { "code": "# import numpyimport numpy as np # using numpy.fill_diagonal() methodarray = np.zeros((3, 3), int)np.fill_diagonal(array, 1) print(array)", "e": 778, "s": 638, "text": null }, { "code": null, "e": 787, "s": 778, "text": "Output :" }, { "code": null, "e": 811, "s": 787, "text": "[[1 0 0][0 1 0][0 0 1]]" }, { "code": null, "e": 824, "s": 811, "text": "Python-numpy" }, { "code": null, "e": 831, "s": 824, "text": "Python" }, { "code": null, "e": 929, "s": 831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 961, "s": 929, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 988, "s": 961, "text": "Python Classes and Objects" }, { "code": null, "e": 1009, "s": 988, "text": "Python OOPs Concepts" }, { "code": null, "e": 1032, "s": 1009, "text": "Introduction To PYTHON" }, { "code": null, "e": 1063, "s": 1032, "text": "Python | os.path.join() method" }, { "code": null, "e": 1119, "s": 1063, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1161, "s": 1119, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1203, "s": 1161, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1242, "s": 1203, "text": "Python | Get unique values from a list" } ]
VB.Net - CheckBox Control
The CheckBox control allows the user to set true/false or yes/no type options. The user can select or deselect it. When a check box is selected it has the value True, and when it is cleared, it holds the value False. Let's create two check boxes by dragging CheckBox controls from the Toolbox and dropping on the form. The CheckBox control has three states, checked, unchecked and indeterminate. In the indeterminate state, the check box is grayed out. To enable the indeterminate state, the ThreeState property of the check box is set to be True. The following are some of the commonly used properties of the CheckBox control − Appearance Gets or sets a value determining the appearance of the check box. AutoCheck Gets or sets a value indicating whether the Checked or CheckedState value and the appearance of the control automatically change when the check box is selected. CheckAlign Gets or sets the horizontal and vertical alignment of the check mark on the check box. Checked Gets or sets a value indicating whether the check box is selected. CheckState Gets or sets the state of a check box. Text Gets or sets the caption of a check box. ThreeState Gets or sets a value indicating whether or not a check box should allow three check states rather than two. The following are some of the commonly used methods of the CheckBox control − OnCheckedChanged Raises the CheckedChanged event. OnCheckStateChanged Raises the CheckStateChanged event. OnClick Raises the OnClick event. The following are some of the commonly used events of the CheckBox control − AppearanceChanged Occurs when the value of the Appearance property of the check box is changed. CheckedChanged Occurs when the value of the Checked property of the CheckBox control is changed. CheckStateChanged Occurs when the value of the CheckState property of the CheckBox control is changed. Consult Microsoft documentation for detailed list of properties, methods and events of the CheckBox control. In this example, let us add four check boxes in a group box. The check boxes will allow the users to choose the source from which they came to know about the organization. If the user chooses the check box with text "others", then the user is asked to specify and a text box is provided to give input. When the user clicks the Submit button, he/she gets an appropriate message. The form in design view − Let's put the following code in the code editor window − Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) _ Handles MyBase.Load ' Set the caption bar text of the form. Me.Text = "tutorialspoint.com" Label1.Visible = False TextBox1.Visible = False TextBox1.Multiline = True End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) _ Handles Button1.Click Dim str As String str = " " If CheckBox1.Checked = True Then str &= CheckBox1.Text str &= " " End If If CheckBox2.Checked = True Then str &= CheckBox2.Text str &= " " End If If CheckBox3.Checked = True Then str &= CheckBox3.Text str &= " " End If If CheckBox4.Checked = True Then str &= TextBox1.Text str &= " " End If If str <> Nothing Then MsgBox(str + vbLf + "Thank you") End If End Sub Private Sub CheckBox4_CheckedChanged(sender As Object, _ e As EventArgs) Handles CheckBox4.CheckedChanged Label1.Visible = True TextBox1.Visible = True End Sub End Class When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window − Checking all the boxes − Clicking the Submit button −
[ { "code": null, "e": 2651, "s": 2434, "text": "The CheckBox control allows the user to set true/false or yes/no type options. The user can select or deselect it. When a check box is selected it has the value True, and when it is cleared, it holds the value False." }, { "code": null, "e": 2753, "s": 2651, "text": "Let's create two check boxes by dragging CheckBox controls from the Toolbox and dropping on the form." }, { "code": null, "e": 2982, "s": 2753, "text": "The CheckBox control has three states, checked, unchecked and indeterminate. In the indeterminate state, the check box is grayed out. To enable the indeterminate state, the ThreeState property of the check box is set to be True." }, { "code": null, "e": 3063, "s": 2982, "text": "The following are some of the commonly used properties of the CheckBox control −" }, { "code": null, "e": 3074, "s": 3063, "text": "Appearance" }, { "code": null, "e": 3140, "s": 3074, "text": "Gets or sets a value determining the appearance of the check box." }, { "code": null, "e": 3150, "s": 3140, "text": "AutoCheck" }, { "code": null, "e": 3311, "s": 3150, "text": "Gets or sets a value indicating whether the Checked or CheckedState value and the appearance of the control automatically change when the check box is selected." }, { "code": null, "e": 3322, "s": 3311, "text": "CheckAlign" }, { "code": null, "e": 3410, "s": 3322, "text": "Gets or sets the horizontal and vertical alignment of the check mark on the check box. " }, { "code": null, "e": 3418, "s": 3410, "text": "Checked" }, { "code": null, "e": 3485, "s": 3418, "text": "Gets or sets a value indicating whether the check box is selected." }, { "code": null, "e": 3496, "s": 3485, "text": "CheckState" }, { "code": null, "e": 3535, "s": 3496, "text": "Gets or sets the state of a check box." }, { "code": null, "e": 3540, "s": 3535, "text": "Text" }, { "code": null, "e": 3581, "s": 3540, "text": "Gets or sets the caption of a check box." }, { "code": null, "e": 3592, "s": 3581, "text": "ThreeState" }, { "code": null, "e": 3700, "s": 3592, "text": "Gets or sets a value indicating whether or not a check box should allow three check states rather than two." }, { "code": null, "e": 3778, "s": 3700, "text": "The following are some of the commonly used methods of the CheckBox control −" }, { "code": null, "e": 3795, "s": 3778, "text": "OnCheckedChanged" }, { "code": null, "e": 3828, "s": 3795, "text": "Raises the CheckedChanged event." }, { "code": null, "e": 3848, "s": 3828, "text": "OnCheckStateChanged" }, { "code": null, "e": 3884, "s": 3848, "text": "Raises the CheckStateChanged event." }, { "code": null, "e": 3892, "s": 3884, "text": "OnClick" }, { "code": null, "e": 3918, "s": 3892, "text": "Raises the OnClick event." }, { "code": null, "e": 3995, "s": 3918, "text": "The following are some of the commonly used events of the CheckBox control −" }, { "code": null, "e": 4013, "s": 3995, "text": "AppearanceChanged" }, { "code": null, "e": 4091, "s": 4013, "text": "Occurs when the value of the Appearance property of the check box is changed." }, { "code": null, "e": 4106, "s": 4091, "text": "CheckedChanged" }, { "code": null, "e": 4188, "s": 4106, "text": "Occurs when the value of the Checked property of the CheckBox control is changed." }, { "code": null, "e": 4206, "s": 4188, "text": "CheckStateChanged" }, { "code": null, "e": 4291, "s": 4206, "text": "Occurs when the value of the CheckState property of the CheckBox control is changed." }, { "code": null, "e": 4400, "s": 4291, "text": "Consult Microsoft documentation for detailed list of properties, methods and events of the CheckBox control." }, { "code": null, "e": 4778, "s": 4400, "text": "In this example, let us add four check boxes in a group box. The check boxes will allow the users to choose the source from which they came to know about the organization. If the user chooses the check box with text \"others\", then the user is asked to specify and a text box is provided to give input. When the user clicks the Submit button, he/she gets an appropriate message." }, { "code": null, "e": 4804, "s": 4778, "text": "The form in design view −" }, { "code": null, "e": 4861, "s": 4804, "text": "Let's put the following code in the code editor window −" }, { "code": null, "e": 6025, "s": 4861, "text": "Public Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) _\n Handles MyBase.Load\n ' Set the caption bar text of the form. \n Me.Text = \"tutorialspoint.com\"\n Label1.Visible = False\n TextBox1.Visible = False\n TextBox1.Multiline = True\n End Sub\n \n Private Sub Button1_Click(sender As Object, e As EventArgs) _\n Handles Button1.Click\n Dim str As String\n str = \" \"\n \n If CheckBox1.Checked = True Then\n str &= CheckBox1.Text\n str &= \" \"\n End If\n \n If CheckBox2.Checked = True Then\n str &= CheckBox2.Text\n str &= \" \"\n End If\n \n If CheckBox3.Checked = True Then\n str &= CheckBox3.Text\n str &= \" \"\n End If\n \n If CheckBox4.Checked = True Then\n str &= TextBox1.Text\n str &= \" \"\n End If\n If str <> Nothing Then\n MsgBox(str + vbLf + \"Thank you\")\n End If\n End Sub\n \n Private Sub CheckBox4_CheckedChanged(sender As Object, _\n e As EventArgs) Handles CheckBox4.CheckedChanged\n Label1.Visible = True\n TextBox1.Visible = True\n End Sub\nEnd Class" }, { "code": null, "e": 6171, "s": 6025, "text": "When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −" }, { "code": null, "e": 6196, "s": 6171, "text": "Checking all the boxes −" } ]
Delete Contents From Table Using JDBC
24 Nov, 2020 JDBC(Java Database Connectivity) is a standard API(application interface) between the java programming language and various databases like Oracle, SQL, PostgreSQL, etc. It connects the front end(for interacting with the users) with the backend(for storing data). Approach: 1. CREATE DATABASE: Create a database using sqlyog and create some tables in it and fill data inside it in order to delete contents of a table. Here, for example, Name a database as “hotelman” and table names are “cuslogin” and “adminlogin”. Taking “cuslogin” table as an example. 2. CREATE CONNECTION: Open Netbeans and create a new package. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java. Java // Create JDBC Connectionimport java.sql.*; public class connection { Connection con = null; public static Connection connectDB() { try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/hotelman", "root", "1234"); // here,root is the username and 1234 is the // password,you can set your own username and // password. return con; } catch (SQLException e) { System.out.println(e); } }} 3. DELETE CONTENTS IN A TABLE: Delete the customer details from “cuslogin” table whose id is 1. Initialise a string with the sql query as followsString sql=”delete from cuslogin where id=1′′;Initialise the below objects of Connection class, PreparedStatement clas(needed for jdbc ) and connect with database as follows Connection con=null;PreparedStatement p=null;con=connection.connectDB();Now, add the sql query of step 3.1 inside prepareStatement and execute it as followsp =con.prepareStatement(sql);p.execute();Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for deleting the details of customer whose id is 1, from table “cuslogin”. Initialise a string with the sql query as followsString sql=”delete from cuslogin where id=1′′; Initialise the below objects of Connection class, PreparedStatement clas(needed for jdbc ) and connect with database as follows Connection con=null;PreparedStatement p=null;con=connection.connectDB(); Now, add the sql query of step 3.1 inside prepareStatement and execute it as followsp =con.prepareStatement(sql);p.execute(); Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for deleting the details of customer whose id is 1, from table “cuslogin”. NOTE: Both the files viz result.java and connection.java should be inside the same package, else the program won’t give the desired output!! Java /*package whatever //do not write package name here */import java.sql.*;public class result { public static void main(String[] args) { Connection con=null; PreparedStatement p=null; con=connection.connectDB(); try{ String sql="delete from cuslogin where id=1"; p =con.prepareStatement(sql); p.execute(); }catch(SQLException e){ System.out.println(e); } } } Output: The customer whose id was 1, has been deleted. JDBC Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2020" }, { "code": null, "e": 291, "s": 28, "text": "JDBC(Java Database Connectivity) is a standard API(application interface) between the java programming language and various databases like Oracle, SQL, PostgreSQL, etc. It connects the front end(for interacting with the users) with the backend(for storing data)." }, { "code": null, "e": 301, "s": 291, "text": "Approach:" }, { "code": null, "e": 582, "s": 301, "text": "1. CREATE DATABASE: Create a database using sqlyog and create some tables in it and fill data inside it in order to delete contents of a table. Here, for example, Name a database as “hotelman” and table names are “cuslogin” and “adminlogin”. Taking “cuslogin” table as an example." }, { "code": null, "e": 775, "s": 582, "text": "2. CREATE CONNECTION: Open Netbeans and create a new package. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java." }, { "code": null, "e": 780, "s": 775, "text": "Java" }, { "code": "// Create JDBC Connectionimport java.sql.*; public class connection { Connection con = null; public static Connection connectDB() { try { Class.forName(\"com.mysql.jdbc.Driver\"); Connection con = DriverManager.getConnection( \"jdbc:mysql://localhost:3306/hotelman\", \"root\", \"1234\"); // here,root is the username and 1234 is the // password,you can set your own username and // password. return con; } catch (SQLException e) { System.out.println(e); } }}", "e": 1394, "s": 780, "text": null }, { "code": null, "e": 1492, "s": 1396, "text": "3. DELETE CONTENTS IN A TABLE: Delete the customer details from “cuslogin” table whose id is 1." }, { "code": null, "e": 2094, "s": 1492, "text": "Initialise a string with the sql query as followsString sql=”delete from cuslogin where id=1′′;Initialise the below objects of Connection class, PreparedStatement clas(needed for jdbc ) and connect with database as follows Connection con=null;PreparedStatement p=null;con=connection.connectDB();Now, add the sql query of step 3.1 inside prepareStatement and execute it as followsp =con.prepareStatement(sql);p.execute();Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for deleting the details of customer whose id is 1, from table “cuslogin”." }, { "code": null, "e": 2190, "s": 2094, "text": "Initialise a string with the sql query as followsString sql=”delete from cuslogin where id=1′′;" }, { "code": null, "e": 2392, "s": 2190, "text": "Initialise the below objects of Connection class, PreparedStatement clas(needed for jdbc ) and connect with database as follows Connection con=null;PreparedStatement p=null;con=connection.connectDB();" }, { "code": null, "e": 2518, "s": 2392, "text": "Now, add the sql query of step 3.1 inside prepareStatement and execute it as followsp =con.prepareStatement(sql);p.execute();" }, { "code": null, "e": 2699, "s": 2518, "text": "Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for deleting the details of customer whose id is 1, from table “cuslogin”." }, { "code": null, "e": 2840, "s": 2699, "text": "NOTE: Both the files viz result.java and connection.java should be inside the same package, else the program won’t give the desired output!!" }, { "code": null, "e": 2845, "s": 2840, "text": "Java" }, { "code": "/*package whatever //do not write package name here */import java.sql.*;public class result { public static void main(String[] args) { Connection con=null; PreparedStatement p=null; con=connection.connectDB(); try{ String sql=\"delete from cuslogin where id=1\"; p =con.prepareStatement(sql); p.execute(); }catch(SQLException e){ System.out.println(e); } } }", "e": 3320, "s": 2845, "text": null }, { "code": null, "e": 3328, "s": 3320, "text": "Output:" }, { "code": null, "e": 3375, "s": 3328, "text": "The customer whose id was 1, has been deleted." }, { "code": null, "e": 3380, "s": 3375, "text": "JDBC" }, { "code": null, "e": 3387, "s": 3380, "text": "Picked" }, { "code": null, "e": 3411, "s": 3387, "text": "Technical Scripter 2020" }, { "code": null, "e": 3416, "s": 3411, "text": "Java" }, { "code": null, "e": 3435, "s": 3416, "text": "Technical Scripter" }, { "code": null, "e": 3440, "s": 3435, "text": "Java" }, { "code": null, "e": 3538, "s": 3440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3553, "s": 3538, "text": "Stream In Java" }, { "code": null, "e": 3574, "s": 3553, "text": "Introduction to Java" }, { "code": null, "e": 3595, "s": 3574, "text": "Constructors in Java" }, { "code": null, "e": 3614, "s": 3595, "text": "Exceptions in Java" }, { "code": null, "e": 3631, "s": 3614, "text": "Generics in Java" }, { "code": null, "e": 3661, "s": 3631, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3687, "s": 3661, "text": "Java Programming Examples" }, { "code": null, "e": 3703, "s": 3687, "text": "Strings in Java" }, { "code": null, "e": 3740, "s": 3703, "text": "Differences between JDK, JRE and JVM" } ]
Extract and print words separately from a given Camel Case string
26 Jun, 2020 Given a string in Camel Case format, we need to extract all the words which are present in the string. CamelCase is the sequence of one or more than one words having the following properties: It is a concatenation of one or more words consisting of English letters.All letters in the first word are lowercase.For each of the subsequent words, the first letter is uppercase and the rest of the letters are lowercase. It is a concatenation of one or more words consisting of English letters. All letters in the first word are lowercase. For each of the subsequent words, the first letter is uppercase and the rest of the letters are lowercase. Example: Input: str = “GeeksForGeeks”Output:GeeksForGeeks Input: str = “AComputerSciencePortalForGeeks”Output:AComputerSciencePortalForGeeks Approach:A simple approach is to traverse the array and extract every word by looking at its first character, as it will always be in upper-case. Store all extracted words in a new array and print them. C++ // C++ program to print words// from CamelCase String #include <cstring>#include <iostream>using namespace std; // Function to extract a wordchar* mystrtok(char* str){ static char* input = NULL; if (str != NULL) { input = str; } // Base case if (input == NULL) return NULL; // Array for storing tokens // +1 is for '\0' char* output = new char[strlen(input + 1)]; int i = 0; // Storing the upper case character output[i] = input[i]; i++; // Generating Tokens for (; input[i] != '\0'; i++) { if (!isupper(input[i])) output[i] = input[i]; else { output[i] = '\0'; input = input + i; return output; } } output[i] = '\0'; input = NULL; return output;} // Function to extract wordsvoid extractWords(char* s){ // Extract 1st word and print it char* ptr = mystrtok(s); cout << ptr << endl; // Extract the remaining words while (ptr != NULL) { ptr = mystrtok(NULL); cout << ptr << endl; }} // Driver codeint main(){ char s[] = "GeeksForGeeks"; extractWords(s); return 0;} Geeks For Geeks Time Complexity: O(N)Space Complexity: O(N), as we needed a new array to store output. Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Find if a string is interleaved of two other strings | DP-33 Remove first and last character of a string in Java Check if an URL is valid or not using Regular Expression Find the smallest window in a string containing all characters of another string
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jun, 2020" }, { "code": null, "e": 131, "s": 28, "text": "Given a string in Camel Case format, we need to extract all the words which are present in the string." }, { "code": null, "e": 220, "s": 131, "text": "CamelCase is the sequence of one or more than one words having the following properties:" }, { "code": null, "e": 444, "s": 220, "text": "It is a concatenation of one or more words consisting of English letters.All letters in the first word are lowercase.For each of the subsequent words, the first letter is uppercase and the rest of the letters are lowercase." }, { "code": null, "e": 518, "s": 444, "text": "It is a concatenation of one or more words consisting of English letters." }, { "code": null, "e": 563, "s": 518, "text": "All letters in the first word are lowercase." }, { "code": null, "e": 670, "s": 563, "text": "For each of the subsequent words, the first letter is uppercase and the rest of the letters are lowercase." }, { "code": null, "e": 679, "s": 670, "text": "Example:" }, { "code": null, "e": 728, "s": 679, "text": "Input: str = “GeeksForGeeks”Output:GeeksForGeeks" }, { "code": null, "e": 811, "s": 728, "text": "Input: str = “AComputerSciencePortalForGeeks”Output:AComputerSciencePortalForGeeks" }, { "code": null, "e": 1014, "s": 811, "text": "Approach:A simple approach is to traverse the array and extract every word by looking at its first character, as it will always be in upper-case. Store all extracted words in a new array and print them." }, { "code": null, "e": 1018, "s": 1014, "text": "C++" }, { "code": "// C++ program to print words// from CamelCase String #include <cstring>#include <iostream>using namespace std; // Function to extract a wordchar* mystrtok(char* str){ static char* input = NULL; if (str != NULL) { input = str; } // Base case if (input == NULL) return NULL; // Array for storing tokens // +1 is for '\\0' char* output = new char[strlen(input + 1)]; int i = 0; // Storing the upper case character output[i] = input[i]; i++; // Generating Tokens for (; input[i] != '\\0'; i++) { if (!isupper(input[i])) output[i] = input[i]; else { output[i] = '\\0'; input = input + i; return output; } } output[i] = '\\0'; input = NULL; return output;} // Function to extract wordsvoid extractWords(char* s){ // Extract 1st word and print it char* ptr = mystrtok(s); cout << ptr << endl; // Extract the remaining words while (ptr != NULL) { ptr = mystrtok(NULL); cout << ptr << endl; }} // Driver codeint main(){ char s[] = \"GeeksForGeeks\"; extractWords(s); return 0;}", "e": 2182, "s": 1018, "text": null }, { "code": null, "e": 2199, "s": 2182, "text": "Geeks\nFor\nGeeks\n" }, { "code": null, "e": 2286, "s": 2199, "text": "Time Complexity: O(N)Space Complexity: O(N), as we needed a new array to store output." }, { "code": null, "e": 2294, "s": 2286, "text": "Strings" }, { "code": null, "e": 2302, "s": 2294, "text": "Strings" }, { "code": null, "e": 2400, "s": 2302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2445, "s": 2400, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 2509, "s": 2445, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 2554, "s": 2509, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 2589, "s": 2554, "text": "Print all subsequences of a string" }, { "code": null, "e": 2654, "s": 2589, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 2683, "s": 2654, "text": "String class in Java | Set 1" }, { "code": null, "e": 2744, "s": 2683, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 2796, "s": 2744, "text": "Remove first and last character of a string in Java" }, { "code": null, "e": 2853, "s": 2796, "text": "Check if an URL is valid or not using Regular Expression" } ]
Python – Pair lists elements to Dictionary
22 Oct, 2021 Sometimes, while working with records we can have problem in which we can have pair of lists, we need to pair similar like elements to single key value dictionary. This is very peculiar problem but can have applications in data domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + extend() + enumerate()The combination of above functionalities can be employed to solve this question. In this, we iterate for the lists and append like elements to similar key using extend(). # Python3 code to demonstrate working of # Pair lists elements to Dictionary# Using loop + extend() + enumerate() # initializing liststest_list1 = [1, 2, 3, 1, 1, 2, 3]test_list2 = [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Pair lists elements to Dictionary# Using loop + extend() + enumerate()res = dict()for idx, val in enumerate(test_list1): if val in res: res[val].extend(list(test_list2[idx])) else: res[val] = list(test_list2[idx]) # printing result print("The Like elements compiled Dictionary is : " + str(res)) The original list 1 is : [1, 2, 3, 1, 1, 2, 3]The original list 2 is : [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]]The Like elements compiled Dictionary is : {1: [4, 5, 10, 12, 56, 43], 2: [6, 7, 98, 100], 3: [2, 3, 0, 13]} Method #2 : Using defaultdict() + zip()The combination of above tasks can also be used to solve this problem. In this, we pair elements using zip() and initialize the dictionary values as a list to avoid testing for existence of first value. # Python3 code to demonstrate working of # Pair lists elements to Dictionary# Using defaultdict() + zip()from collections import defaultdict # initializing liststest_list1 = [1, 2, 3, 1, 1, 2, 3]test_list2 = [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Pair lists elements to Dictionary# Using defaultdict() + zip()res = defaultdict(list)for ele1, ele2 in zip(test_list1, test_list2): res[ele1].extend(ele2) # printing result print("The Like elements compiled Dictionary is : " + str(dict(res))) The original list 1 is : [1, 2, 3, 1, 1, 2, 3]The original list 2 is : [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]]The Like elements compiled Dictionary is : {1: [4, 5, 10, 12, 56, 43], 2: [6, 7, 98, 100], 3: [2, 3, 0, 13]} khushboogoyal499 Python dictionary-programs Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Oct, 2021" }, { "code": null, "e": 328, "s": 28, "text": "Sometimes, while working with records we can have problem in which we can have pair of lists, we need to pair similar like elements to single key value dictionary. This is very peculiar problem but can have applications in data domains. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 546, "s": 328, "text": "Method #1 : Using loop + extend() + enumerate()The combination of above functionalities can be employed to solve this question. In this, we iterate for the lists and append like elements to similar key using extend()." }, { "code": "# Python3 code to demonstrate working of # Pair lists elements to Dictionary# Using loop + extend() + enumerate() # initializing liststest_list1 = [1, 2, 3, 1, 1, 2, 3]test_list2 = [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Pair lists elements to Dictionary# Using loop + extend() + enumerate()res = dict()for idx, val in enumerate(test_list1): if val in res: res[val].extend(list(test_list2[idx])) else: res[val] = list(test_list2[idx]) # printing result print(\"The Like elements compiled Dictionary is : \" + str(res)) ", "e": 1262, "s": 546, "text": null }, { "code": null, "e": 1506, "s": 1262, "text": "The original list 1 is : [1, 2, 3, 1, 1, 2, 3]The original list 2 is : [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]]The Like elements compiled Dictionary is : {1: [4, 5, 10, 12, 56, 43], 2: [6, 7, 98, 100], 3: [2, 3, 0, 13]}" }, { "code": null, "e": 1750, "s": 1508, "text": "Method #2 : Using defaultdict() + zip()The combination of above tasks can also be used to solve this problem. In this, we pair elements using zip() and initialize the dictionary values as a list to avoid testing for existence of first value." }, { "code": "# Python3 code to demonstrate working of # Pair lists elements to Dictionary# Using defaultdict() + zip()from collections import defaultdict # initializing liststest_list1 = [1, 2, 3, 1, 1, 2, 3]test_list2 = [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Pair lists elements to Dictionary# Using defaultdict() + zip()res = defaultdict(list)for ele1, ele2 in zip(test_list1, test_list2): res[ele1].extend(ele2) # printing result print(\"The Like elements compiled Dictionary is : \" + str(dict(res))) ", "e": 2423, "s": 1750, "text": null }, { "code": null, "e": 2667, "s": 2423, "text": "The original list 1 is : [1, 2, 3, 1, 1, 2, 3]The original list 2 is : [[4, 5], [6, 7], [2, 3], [10, 12], [56, 43], [98, 100], [0, 13]]The Like elements compiled Dictionary is : {1: [4, 5, 10, 12, 56, 43], 2: [6, 7, 98, 100], 3: [2, 3, 0, 13]}" }, { "code": null, "e": 2684, "s": 2667, "text": "khushboogoyal499" }, { "code": null, "e": 2711, "s": 2684, "text": "Python dictionary-programs" }, { "code": null, "e": 2732, "s": 2711, "text": "Python list-programs" }, { "code": null, "e": 2739, "s": 2732, "text": "Python" }, { "code": null, "e": 2755, "s": 2739, "text": "Python Programs" }, { "code": null, "e": 2853, "s": 2755, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2885, "s": 2853, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2912, "s": 2885, "text": "Python Classes and Objects" }, { "code": null, "e": 2933, "s": 2912, "text": "Python OOPs Concepts" }, { "code": null, "e": 2956, "s": 2933, "text": "Introduction To PYTHON" }, { "code": null, "e": 3012, "s": 2956, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3034, "s": 3012, "text": "Defaultdict in Python" }, { "code": null, "e": 3073, "s": 3034, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3111, "s": 3073, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3160, "s": 3111, "text": "Python | Convert string dictionary to dictionary" } ]
How to create proxy server on Heroku in Node.js ?
11 May, 2022 The following approach covers how to create a proxy server on Heroku using NodeJS. Heroku is a cloud application platform that is used as PaaS (Platform as a service) to build, operate and run applications on their cloud. Prerequisites: To create a proxy server, you will need the following to be installed on your computer: Install Heroku CLI. Install node.js. Install git. Git version control skills. Follow these simple steps to create a proxy server on Heroku: Step 1: Setting up a local repository. Clone your remote repository to the local directory. Now cd into your cloned repository and run the command npm install to install all node dependencies into your project. Step 2: Setting up the Heroku environment using the following approach: Login into Heroku from the terminal by using the command Heroku login. After the login command from the terminal follow the prompts in the open browser to log in. After successful execution following will be displayed on your terminal screen. The next step is to create an app on Heroku using the command Heroku create. After the above step, Heroku will display a generic message with deployed URL which can be exchanged for a universal URL anywhere. Step 3: Pushing our proxy server into the Heroku server. The final step is to push our proxy server to Heroku which can be done by using the following command. git push heroku (branch-name) Now your proxy server is successfully created and deployed on Heroku. Heroku Cloud Node.js-Methods NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2022" }, { "code": null, "e": 274, "s": 52, "text": "The following approach covers how to create a proxy server on Heroku using NodeJS. Heroku is a cloud application platform that is used as PaaS (Platform as a service) to build, operate and run applications on their cloud." }, { "code": null, "e": 377, "s": 274, "text": "Prerequisites: To create a proxy server, you will need the following to be installed on your computer:" }, { "code": null, "e": 397, "s": 377, "text": "Install Heroku CLI." }, { "code": null, "e": 414, "s": 397, "text": "Install node.js." }, { "code": null, "e": 427, "s": 414, "text": "Install git." }, { "code": null, "e": 455, "s": 427, "text": "Git version control skills." }, { "code": null, "e": 517, "s": 455, "text": "Follow these simple steps to create a proxy server on Heroku:" }, { "code": null, "e": 609, "s": 517, "text": "Step 1: Setting up a local repository. Clone your remote repository to the local directory." }, { "code": null, "e": 728, "s": 609, "text": "Now cd into your cloned repository and run the command npm install to install all node dependencies into your project." }, { "code": null, "e": 800, "s": 728, "text": "Step 2: Setting up the Heroku environment using the following approach:" }, { "code": null, "e": 871, "s": 800, "text": "Login into Heroku from the terminal by using the command Heroku login." }, { "code": null, "e": 963, "s": 871, "text": "After the login command from the terminal follow the prompts in the open browser to log in." }, { "code": null, "e": 1043, "s": 963, "text": "After successful execution following will be displayed on your terminal screen." }, { "code": null, "e": 1120, "s": 1043, "text": "The next step is to create an app on Heroku using the command Heroku create." }, { "code": null, "e": 1251, "s": 1120, "text": "After the above step, Heroku will display a generic message with deployed URL which can be exchanged for a universal URL anywhere." }, { "code": null, "e": 1411, "s": 1251, "text": "Step 3: Pushing our proxy server into the Heroku server. The final step is to push our proxy server to Heroku which can be done by using the following command." }, { "code": null, "e": 1441, "s": 1411, "text": "git push heroku (branch-name)" }, { "code": null, "e": 1511, "s": 1441, "text": "Now your proxy server is successfully created and deployed on Heroku." }, { "code": null, "e": 1524, "s": 1511, "text": "Heroku Cloud" }, { "code": null, "e": 1540, "s": 1524, "text": "Node.js-Methods" }, { "code": null, "e": 1557, "s": 1540, "text": "NodeJS-Questions" }, { "code": null, "e": 1564, "s": 1557, "text": "Picked" }, { "code": null, "e": 1572, "s": 1564, "text": "Node.js" }, { "code": null, "e": 1589, "s": 1572, "text": "Web Technologies" } ]
How to Use for Each Loop in Excel VBA?
29 Jul, 2021 A For Each loop is used to execute a statement or a set of statements for each element in an array or collection. Syntax: For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ] The For...Each...Next statement syntax has the following three parts: There are 4 basic steps to writing a For Each Next Loop in VBA: Declare a variable. Write the For Each Line with the variable and collection references. Add line(s) of code to repeat for each item in the collection. Write the Next line to terminate the loop. The For...Each block is entered if there is at least one element in the group. Upon entering the loop, all the statements in the loop are executed for each element. When there are no more elements in the group, the loop is exited and execution continues with the statement following the Next statement. The next statement line terminates the loop. Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example, If...Then, and transfers control to the statement immediately following Next. You can also nest For...Each...Next loops by placing one For...Each...Next loop within another. However, each loop element must be unique in its way. NOTE Execution continues as if element is included, if you omit element in a Next statement. An error occurs, If a Next statement is encountered before its corresponding For statement, You can’t use the For...Each...Next statement with an array of user-defined types because a Variant can’t contain a user-defined type. Example 1 Private Sub Demo_Loop() students is an array students = Array(“Akshit”, “Nikita”, “Ritesh”) //Initialising Array-> students Dim studentnames As Variant // Variable is assigned ‘iterating using For each loop. For Each Item In students studentnames =studentnames & Item & Chr(10) Next MsgBox studentnames End Sub It would look somewhat like below: When the above code is executed, it prints all the student names with one item in each line. akshitsaxenaa09 Excel-VBA Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Delete Blank Columns in Excel? How to Get Length of Array in Excel VBA? How to Normalize Data in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Use Solver in Excel? Introduction to Excel Spreadsheet How to make a 3 Axis Graph using Excel? Macros in Excel How to Show Percentages in Stacked Column Chart in Excel? How to Extract the Last Word From a Cell in Excel?
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2021" }, { "code": null, "e": 142, "s": 28, "text": "A For Each loop is used to execute a statement or a set of statements for each element in an array or collection." }, { "code": null, "e": 150, "s": 142, "text": "Syntax:" }, { "code": null, "e": 236, "s": 150, "text": "For Each element In group\n[ statements ]\n[ Exit For ]\n[ statements ]\nNext [ element ]" }, { "code": null, "e": 306, "s": 236, "text": "The For...Each...Next statement syntax has the following three parts:" }, { "code": null, "e": 370, "s": 306, "text": "There are 4 basic steps to writing a For Each Next Loop in VBA:" }, { "code": null, "e": 390, "s": 370, "text": "Declare a variable." }, { "code": null, "e": 459, "s": 390, "text": "Write the For Each Line with the variable and collection references." }, { "code": null, "e": 522, "s": 459, "text": "Add line(s) of code to repeat for each item in the collection." }, { "code": null, "e": 565, "s": 522, "text": "Write the Next line to terminate the loop." }, { "code": null, "e": 913, "s": 565, "text": "The For...Each block is entered if there is at least one element in the group. Upon entering the loop, all the statements in the loop are executed for each element. When there are no more elements in the group, the loop is exited and execution continues with the statement following the Next statement. The next statement line terminates the loop." }, { "code": null, "e": 1160, "s": 913, "text": "Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example, If...Then, and transfers control to the statement immediately following Next." }, { "code": null, "e": 1310, "s": 1160, "text": "You can also nest For...Each...Next loops by placing one For...Each...Next loop within another. However, each loop element must be unique in its way." }, { "code": null, "e": 1315, "s": 1310, "text": "NOTE" }, { "code": null, "e": 1403, "s": 1315, "text": "Execution continues as if element is included, if you omit element in a Next statement." }, { "code": null, "e": 1495, "s": 1403, "text": "An error occurs, If a Next statement is encountered before its corresponding For statement," }, { "code": null, "e": 1630, "s": 1495, "text": "You can’t use the For...Each...Next statement with an array of user-defined types because a Variant can’t contain a user-defined type." }, { "code": null, "e": 1640, "s": 1630, "text": "Example 1" }, { "code": null, "e": 1666, "s": 1640, "text": " Private Sub Demo_Loop()" }, { "code": null, "e": 1695, "s": 1666, "text": " students is an array" }, { "code": null, "e": 1782, "s": 1695, "text": " students = Array(“Akshit”, “Nikita”, “Ritesh”) //Initialising Array-> students" }, { "code": null, "e": 1841, "s": 1782, "text": " Dim studentnames As Variant // Variable is assigned" }, { "code": null, "e": 1878, "s": 1841, "text": " ‘iterating using For each loop." }, { "code": null, "e": 1910, "s": 1878, "text": " For Each Item In students" }, { "code": null, "e": 1959, "s": 1910, "text": " studentnames =studentnames & Item & Chr(10)" }, { "code": null, "e": 1968, "s": 1959, "text": " Next" }, { "code": null, "e": 1995, "s": 1968, "text": " MsgBox studentnames" }, { "code": null, "e": 2003, "s": 1995, "text": "End Sub" }, { "code": null, "e": 2038, "s": 2003, "text": "It would look somewhat like below:" }, { "code": null, "e": 2131, "s": 2038, "text": "When the above code is executed, it prints all the student names with one item in each line." }, { "code": null, "e": 2147, "s": 2131, "text": "akshitsaxenaa09" }, { "code": null, "e": 2157, "s": 2147, "text": "Excel-VBA" }, { "code": null, "e": 2164, "s": 2157, "text": "Picked" }, { "code": null, "e": 2170, "s": 2164, "text": "Excel" }, { "code": null, "e": 2268, "s": 2170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2306, "s": 2268, "text": "How to Delete Blank Columns in Excel?" }, { "code": null, "e": 2347, "s": 2306, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 2379, "s": 2347, "text": "How to Normalize Data in Excel?" }, { "code": null, "e": 2434, "s": 2379, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 2462, "s": 2434, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 2496, "s": 2462, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 2536, "s": 2496, "text": "How to make a 3 Axis Graph using Excel?" }, { "code": null, "e": 2552, "s": 2536, "text": "Macros in Excel" }, { "code": null, "e": 2610, "s": 2552, "text": "How to Show Percentages in Stacked Column Chart in Excel?" } ]
StringIO Module in Python
15 Sep, 2021 The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty. In both cases, the initial cursor on the file starts at zero. NOTE: This module does not exist in the latest version of Python so to work with this module we have to import it from the io module in Python as io.StringIO. Example: Python3 # Importing the StringIO module.from io import StringIO # The arbitrary string.string ='This is initial string.' # Using the StringIO method to set# as file object. Now we have an# object file that we will able to# treat just like a file.file = StringIO(string) # this will read the fileprint(file.read()) # We can also write this file.file.write(" Welcome to geeksforgeeks.") # This will make the cursor at# index 0.file.seek(0) # This will print the file after# writing in the initial string.print('The string after writing is:', file.read()) Output: This is initial string. The string after writing is: This is initial string. Welcome to geeksforgeeks. Some of the important methods of StringIO are as follow: 1. StringIO.getvalue(): This function returns the entire content of the file. Syntax: File_name.getvalue() Example: Python3 # Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method to# set as file object.file = StringIO(string) # Retrieve the entire content of the file.print(file.getvalue()) Output: 'Hello and welcome to GeeksForGeeks.' 2. In this we discuss about some functions of StringIO which returns Boolean values i.e either True or false: StringIO.isatty():This function Return True if the stream is interactive and False if the stream not is interactive StringIO.readable():This function return True if the file is readable and returns False if file is not readable. StringIO.writable():This function return True if the file supports writing and returns False if file does not support writing. StringIO.seekable():This function return True if the file supports random access and returns False if file does not support random access. StringIO.closed:This function return True if the file is closed and returns False if file is open. Syntax: File_name.isatty() File_name.readable() File_name.writable() File_name.seekable() File_name.closed Example: Python3 # Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method to# set as file object.file = StringIO(string) # This will returns whether the file# is interactive or not.print("Is the file stream interactive?", file.isatty()) # This will returns whether the file is# readable or not.print("Is the file stream readable?", file.readable()) # This will returns whether the file supports# writing or not.print("Is the file stream writable?", file.writable()) # This will returns whether the file is# seekable or not.print("Is the file stream seekable?", file.seekable()) # This will returns whether the file is# closed or not.print("Is the file closed?", file.closed) Output: Is the file stream interactive? False Is the file stream readable? True Is the file stream writable? True Is the file stream seekable? True Is the file closed? False 3.StringIO.seek(): The seek() function is used set the cursor position on the file. If we perform any read and write operation on a file the cursor is set on the last index so to move the cursor at starting index of the file seek() is used. Syntax: File_name.seek(argument) # Here the argument is passed to tell the # function where to set the cursor position. Example: Python3 # Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method# to set as file object.file = StringIO(string) # Reading the file:print(file.read()) # Now if we again want to read# the file it shows empty file# because the cursor is set to# the last index. # This does not print anything# because the function returns an# empty string.print(file.read()) # Hence to set the cursor position# to read or write the file again# we use seek().We can pass any index# here form(0 to len(file))file.seek(0) # Now we can able to read the file again()print(file.read()) Output: Hello and welcome to GeeksForGeeks. Hello and welcome to GeeksForGeeks. 4.StringIO.truncate(): This function is used to resize the size of the file stream. This method drops the file after the provided index and saves it. Syntax: File_name.truncate(size = None) # We can provide the size from where # to truncate the file. Example: Python3 # Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method# to set as file object.file = StringIO(string) # Reading the initial file:print(file.read()) # To set the cursor at 0.file.seek(0) # This will drop the file after# index 18.file.truncate(18) # File after truncate.print(file.read()) Output: Hello and welcome to GeeksForGeeks. Hello and welcome 5.StringIO.tell(): This method is used to tell the current stream or cursor position of the file. Syntax: File_name.tell() Example: Python3 # Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method to# set aas file object.file = StringIO(string) # Here the cursor is at index 0.print(file.tell()) # Cursor is set to index 20.file.seek(20) # Print the index of cursorprint(file.tell()) Output: 0 20 6.StringIO.close(): This method is used to close the file. After this function called on a file, we cannot perform any operation on the file. If any operation is performed, it will raise a ValueError. Syntax: File_name.close() Example: Python3 # Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method to# set as file object.file = StringIO(string) # Reading the file.print(file.read()) # Closing the file.file.close() # If we now perform any operation on the file# it will raise an ValueError. # This is to know whether the# file is closed or not.print("Is the file closed?", file.closed) Output: Hello and welcome to GeeksForGeeks. Is the file closed? True j4xhwylysrb0hfly92embh62bo2ks4ui8293qin9 sagar0719kumar sumitgumber28 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Sep, 2021" }, { "code": null, "e": 398, "s": 28, "text": "The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty. In both cases, the initial cursor on the file starts at zero." }, { "code": null, "e": 557, "s": 398, "text": "NOTE: This module does not exist in the latest version of Python so to work with this module we have to import it from the io module in Python as io.StringIO." }, { "code": null, "e": 567, "s": 557, "text": "Example: " }, { "code": null, "e": 575, "s": 567, "text": "Python3" }, { "code": "# Importing the StringIO module.from io import StringIO # The arbitrary string.string ='This is initial string.' # Using the StringIO method to set# as file object. Now we have an# object file that we will able to# treat just like a file.file = StringIO(string) # this will read the fileprint(file.read()) # We can also write this file.file.write(\" Welcome to geeksforgeeks.\") # This will make the cursor at# index 0.file.seek(0) # This will print the file after# writing in the initial string.print('The string after writing is:', file.read())", "e": 1122, "s": 575, "text": null }, { "code": null, "e": 1130, "s": 1122, "text": "Output:" }, { "code": null, "e": 1233, "s": 1130, "text": "This is initial string. The string after writing is: This is initial string. Welcome to geeksforgeeks." }, { "code": null, "e": 1290, "s": 1233, "text": "Some of the important methods of StringIO are as follow:" }, { "code": null, "e": 1369, "s": 1290, "text": "1. StringIO.getvalue(): This function returns the entire content of the file. " }, { "code": null, "e": 1378, "s": 1369, "text": "Syntax: " }, { "code": null, "e": 1399, "s": 1378, "text": "File_name.getvalue()" }, { "code": null, "e": 1409, "s": 1399, "text": "Example: " }, { "code": null, "e": 1417, "s": 1409, "text": "Python3" }, { "code": "# Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method to# set as file object.file = StringIO(string) # Retrieve the entire content of the file.print(file.getvalue())", "e": 1684, "s": 1417, "text": null }, { "code": null, "e": 1693, "s": 1684, "text": "Output: " }, { "code": null, "e": 1731, "s": 1693, "text": "'Hello and welcome to GeeksForGeeks.'" }, { "code": null, "e": 1842, "s": 1731, "text": "2. In this we discuss about some functions of StringIO which returns Boolean values i.e either True or false: " }, { "code": null, "e": 1958, "s": 1842, "text": "StringIO.isatty():This function Return True if the stream is interactive and False if the stream not is interactive" }, { "code": null, "e": 2071, "s": 1958, "text": "StringIO.readable():This function return True if the file is readable and returns False if file is not readable." }, { "code": null, "e": 2198, "s": 2071, "text": "StringIO.writable():This function return True if the file supports writing and returns False if file does not support writing." }, { "code": null, "e": 2337, "s": 2198, "text": "StringIO.seekable():This function return True if the file supports random access and returns False if file does not support random access." }, { "code": null, "e": 2436, "s": 2337, "text": "StringIO.closed:This function return True if the file is closed and returns False if file is open." }, { "code": null, "e": 2445, "s": 2436, "text": "Syntax: " }, { "code": null, "e": 2544, "s": 2445, "text": "File_name.isatty()\nFile_name.readable()\nFile_name.writable()\nFile_name.seekable()\nFile_name.closed" }, { "code": null, "e": 2553, "s": 2544, "text": "Example:" }, { "code": null, "e": 2561, "s": 2553, "text": "Python3" }, { "code": "# Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method to# set as file object.file = StringIO(string) # This will returns whether the file# is interactive or not.print(\"Is the file stream interactive?\", file.isatty()) # This will returns whether the file is# readable or not.print(\"Is the file stream readable?\", file.readable()) # This will returns whether the file supports# writing or not.print(\"Is the file stream writable?\", file.writable()) # This will returns whether the file is# seekable or not.print(\"Is the file stream seekable?\", file.seekable()) # This will returns whether the file is# closed or not.print(\"Is the file closed?\", file.closed)", "e": 3317, "s": 2561, "text": null }, { "code": null, "e": 3326, "s": 3317, "text": "Output: " }, { "code": null, "e": 3492, "s": 3326, "text": "Is the file stream interactive? False\nIs the file stream readable? True\nIs the file stream writable? True\nIs the file stream seekable? True\nIs the file closed? False" }, { "code": null, "e": 3734, "s": 3492, "text": "3.StringIO.seek(): The seek() function is used set the cursor position on the file. If we perform any read and write operation on a file the cursor is set on the last index so to move the cursor at starting index of the file seek() is used. " }, { "code": null, "e": 3743, "s": 3734, "text": "Syntax: " }, { "code": null, "e": 3859, "s": 3743, "text": "File_name.seek(argument) \n# Here the argument is passed to tell the \n# function where to set the cursor position. " }, { "code": null, "e": 3869, "s": 3859, "text": "Example: " }, { "code": null, "e": 3877, "s": 3869, "text": "Python3" }, { "code": "# Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method# to set as file object.file = StringIO(string) # Reading the file:print(file.read()) # Now if we again want to read# the file it shows empty file# because the cursor is set to# the last index. # This does not print anything# because the function returns an# empty string.print(file.read()) # Hence to set the cursor position# to read or write the file again# we use seek().We can pass any index# here form(0 to len(file))file.seek(0) # Now we can able to read the file again()print(file.read())", "e": 4528, "s": 3877, "text": null }, { "code": null, "e": 4537, "s": 4528, "text": "Output: " }, { "code": null, "e": 4609, "s": 4537, "text": "Hello and welcome to GeeksForGeeks.\nHello and welcome to GeeksForGeeks." }, { "code": null, "e": 4760, "s": 4609, "text": "4.StringIO.truncate(): This function is used to resize the size of the file stream. This method drops the file after the provided index and saves it. " }, { "code": null, "e": 4769, "s": 4760, "text": "Syntax: " }, { "code": null, "e": 4863, "s": 4769, "text": "File_name.truncate(size = None)\n# We can provide the size from where \n# to truncate the file." }, { "code": null, "e": 4873, "s": 4863, "text": "Example: " }, { "code": null, "e": 4881, "s": 4873, "text": "Python3" }, { "code": "# Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method# to set as file object.file = StringIO(string) # Reading the initial file:print(file.read()) # To set the cursor at 0.file.seek(0) # This will drop the file after# index 18.file.truncate(18) # File after truncate.print(file.read())", "e": 5269, "s": 4881, "text": null }, { "code": null, "e": 5278, "s": 5269, "text": "Output: " }, { "code": null, "e": 5333, "s": 5278, "text": "Hello and welcome to GeeksForGeeks.\nHello and welcome " }, { "code": null, "e": 5431, "s": 5333, "text": "5.StringIO.tell(): This method is used to tell the current stream or cursor position of the file." }, { "code": null, "e": 5440, "s": 5431, "text": "Syntax: " }, { "code": null, "e": 5457, "s": 5440, "text": "File_name.tell()" }, { "code": null, "e": 5467, "s": 5457, "text": "Example: " }, { "code": null, "e": 5475, "s": 5467, "text": "Python3" }, { "code": "# Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method to# set aas file object.file = StringIO(string) # Here the cursor is at index 0.print(file.tell()) # Cursor is set to index 20.file.seek(20) # Print the index of cursorprint(file.tell())", "e": 5817, "s": 5475, "text": null }, { "code": null, "e": 5826, "s": 5817, "text": "Output: " }, { "code": null, "e": 5831, "s": 5826, "text": "0\n20" }, { "code": null, "e": 6032, "s": 5831, "text": "6.StringIO.close(): This method is used to close the file. After this function called on a file, we cannot perform any operation on the file. If any operation is performed, it will raise a ValueError." }, { "code": null, "e": 6041, "s": 6032, "text": "Syntax: " }, { "code": null, "e": 6059, "s": 6041, "text": "File_name.close()" }, { "code": null, "e": 6069, "s": 6059, "text": "Example: " }, { "code": null, "e": 6077, "s": 6069, "text": "Python3" }, { "code": "# Importing the StringIO module.from io import StringIO # The arbitrary string.string ='Hello and welcome to GeeksForGeeks.' # Using the StringIO method to# set as file object.file = StringIO(string) # Reading the file.print(file.read()) # Closing the file.file.close() # If we now perform any operation on the file# it will raise an ValueError. # This is to know whether the# file is closed or not.print(\"Is the file closed?\", file.closed)", "e": 6520, "s": 6077, "text": null }, { "code": null, "e": 6529, "s": 6520, "text": "Output: " }, { "code": null, "e": 6590, "s": 6529, "text": "Hello and welcome to GeeksForGeeks.\nIs the file closed? True" }, { "code": null, "e": 6631, "s": 6590, "text": "j4xhwylysrb0hfly92embh62bo2ks4ui8293qin9" }, { "code": null, "e": 6646, "s": 6631, "text": "sagar0719kumar" }, { "code": null, "e": 6660, "s": 6646, "text": "sumitgumber28" }, { "code": null, "e": 6675, "s": 6660, "text": "python-modules" }, { "code": null, "e": 6682, "s": 6675, "text": "Python" } ]
Kahan Summation Algorithm
23 Dec, 2021 Prerequisites: Rounding off errors, Introduction to the floating-point representationKahan summation algorithm, also known as compensated summation and summation with the carry algorithm, is used to minimize the loss of significance in the total result obtained by adding a sequence of finite-precision floating-point numbers. This is done by keeping a separate running compensation (a variable to accumulate small errors). Reason for Loss of Significance: As we know in Java language we have two primitive floating-point types, float and double, with single-precision 32-bit and double-precision 64-bit format values and operations specified by IEEE 754. That is, they are represented in a form like: SIGN FRACTION * 2EXP For example, 0.15625 = (0.00101)2, which in floating-point format is represented as: 1.01 * 2-3. However, not all fractions can be represented exactly as a fraction of a power of two. For example, 0.1 = (0.000110011001100110011001100110011001100110011001100110011001... )2 and thus cannot be stored inside a floating-point variable. Therefore, floating-point error/loss of significance refers to when a number that cannot be stored as it is in the IEEE floating-point representation and repetitively some arithmetic operation is performed on it. This leads to some unexpected value and the difference between the expected and the obtained value is the error. Below is an implementation that simulates the significance error: C++ Java Python3 Javascript // C++ program to illustrate the// floating-point error#include<bits/stdc++.h>using namespace std; double floatError(double no){ double sum = 0.0; for(int i = 0; i < 10; i++) { sum = sum + no; } return sum;} // Driver codeint main(){ cout << setprecision(16); cout << floatError(0.1);} // This code is contributed by rutvik_56 // Java program to illustrate the// floating-point error public class GFG { public static double floatError(double no) { double sum = 0.0; for (int i = 0; i < 10; i++) { sum = sum + no; } return sum; } public static void main(String[] args) { System.out.println(floatError(0.1)); }} # Python3 program to illustrate the# floating-point error def floatError(no): sum = 0.0 for i in range(10): sum = sum + no return sum if __name__ == '__main__': print(floatError(0.1)) # This code is contributed by mohit kumar 29 <script>// Javascript program to illustrate the// floating-point error function floatError(no){ let sum = 0.0; for (let i = 0; i < 10; i++) { sum = sum + no; } return sum;} document.write(floatError(0.1)); // This code is contributed by patel2127</script> 0.9999999999999999 Note: The expected value for the above implementation is 1.0 but the value returned is 0.9999999999999999. Therefore, in this article, a method to reduce this error by using Kahan’s Summation algorithm is discussed. Kahan Summation Algorithm: The idea of the Kahan summation algorithm is to compensate for the floating-point error by keeping a separate variable to store the running time errors as the arithmetic operations are being performed. This can be visualised by the following pseudocode: function KahanSum(input) var sum = 0.0 var c = 0.0 for i = 1 to input.length do var y = input[i] - c var t = sum + y c = (t - sum) - y sum = t next i return sum In the above pseudocode, algebraically, the variable c in which the error is stored is always 0. However, when there is a loss of significance, it stores the error in it. Below is the implementation of the above approach: C++ Java Javascript Python3 // C++ program to illustrate the// Kahan summation algorithm #include <bits/stdc++.h>using namespace std; // Function to implement the Kahan// summation algorithmdouble kahanSum(vector<double> &fa){ double sum = 0.0; // Variable to store the error double c = 0.0; // Loop to iterate over the array for(double f : fa) { double y = f - c; double t = sum + y; // Algebraically, c is always 0 // when t is replaced by its // value from the above expression. // But, when there is a loss, // the higher-order y is cancelled // out by subtracting y from c and // all that remains is the // lower-order error in c c = (t - sum) - y; sum = t; } return sum;} // Function to implement the sum// of an arraydouble sum(vector<double> &fa){ double sum = 0.0; // Loop to find the sum of the array for(double f : fa) { sum = sum + f; } return sum;} // Driver codeint main(){ vector<double> no(10); for(int i = 0; i < 10; i++) { no[i] = 0.1; } // Comparing the results cout << setprecision(16); cout << "Normal sum: " << sum(no) << " \n"; cout << "Kahan sum: " << kahanSum(no); } // This code is contributed by ajaykr00kj // Java program to illustrate the// Kahan summation algorithm public class GFG { // Function to implement the Kahan // summation algorithm private static double kahanSum(double... fa) { double sum = 0.0; // Variable to store the error double c = 0.0; // Loop to iterate over the array for (double f : fa) { double y = f - c; double t = sum + y; // Algebraically, c is always 0 // when t is replaced by its // value from the above expression. // But, when there is a loss, // the higher-order y is cancelled // out by subtracting y from c and // all that remains is the // lower-order error in c c = (t - sum) - y; sum = t; } return sum; } // Function to implement the sum // of an array private static double sum(double... fa) { double sum = 0.0; // Loop to find the sum of the array for (double f : fa) { sum = sum + f; } return sum; } // Driver code public static void main(String[] args) { double[] no = new double[10]; for (int i = 0; i < no.length; i++) { no[i] = 0.1; } // Comparing the results System.out.println("Normal sum: " + sum(no)); System.out.println("Kahan sum: " + kahanSum(no)); }} <script> // Javascript program to illustrate the// Kahan summation algorithm // Function to implement the Kahan// summation algorithmfunction kahanSum(fa){ let sum = 0.0; // Variable to store the error let c = 0.0; // Loop to iterate over the array for(let f = 0; f < fa.length; f++) { let y = fa[f] - c; let t = sum + y; // Algebraically, c is always 0 // when t is replaced by its // value from the above expression. // But, when there is a loss, // the higher-order y is cancelled // out by subtracting y from c and // all that remains is the // lower-order error in c c = (t - sum) - y; sum = t; } return sum;} // Function to implement the sum// of an arrayfunction sum(fa){ let sum = 0.0; // Loop to find the sum of the array for(let f = 0; f < fa.length; f++) { sum = sum + fa[f]; } return sum;} // Driver codelet no = new Array(10);for(let i = 0; i < no.length; i++){ no[i] = 0.1;} // Comparing the resultsdocument.write("Normal sum: " + sum(no) + "<br>");document.write("Kahan sum: " + kahanSum(no).toFixed(1) + "<br>"); // This code is contributed by unknown2108 </script> # Python3 program to illustrate the# Kahan summation algorithm # Function to implement the Kahan# summation algorithmdef kahanSum(fa): sum = 0.0 # Variable to store the error c = 0.0 # Loop to iterate over the array for f in fa: y = f - c t = sum + y # Algebraically, c is always 0 # when t is replaced by its # value from the above expression. # But, when there is a loss, # the higher-order y is cancelled # out by subtracting y from c and # all that remains is the # lower-order error in c c = (t - sum) - y sum = t return sum # Driver codeif __name__ == "__main__": no = [0.0] * 10 for i in range(10): no[i] = 0.1 # Comparing the results print("Normal sum: ", sum(no)) print("Kahan sum: ", kahanSum(no)) Normal sum: 0.9999999999999999 Kahan sum: 1.0 Time Complexity: O(N), where N is the length of the list.Auxiliary Space: O(1) mohit kumar 29 rutvik_56 ajaykr00kj patel2127 unknown2108 pankajsharmagfg ashutoshsinghgeeksforgeeks amartyaghoshgfg Algorithms Write From Home Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Dec, 2021" }, { "code": null, "e": 453, "s": 28, "text": "Prerequisites: Rounding off errors, Introduction to the floating-point representationKahan summation algorithm, also known as compensated summation and summation with the carry algorithm, is used to minimize the loss of significance in the total result obtained by adding a sequence of finite-precision floating-point numbers. This is done by keeping a separate running compensation (a variable to accumulate small errors). " }, { "code": null, "e": 487, "s": 453, "text": "Reason for Loss of Significance: " }, { "code": null, "e": 732, "s": 487, "text": "As we know in Java language we have two primitive floating-point types, float and double, with single-precision 32-bit and double-precision 64-bit format values and operations specified by IEEE 754. That is, they are represented in a form like:" }, { "code": null, "e": 753, "s": 732, "text": "SIGN FRACTION * 2EXP" }, { "code": null, "e": 1086, "s": 753, "text": "For example, 0.15625 = (0.00101)2, which in floating-point format is represented as: 1.01 * 2-3. However, not all fractions can be represented exactly as a fraction of a power of two. For example, 0.1 = (0.000110011001100110011001100110011001100110011001100110011001... )2 and thus cannot be stored inside a floating-point variable." }, { "code": null, "e": 1412, "s": 1086, "text": "Therefore, floating-point error/loss of significance refers to when a number that cannot be stored as it is in the IEEE floating-point representation and repetitively some arithmetic operation is performed on it. This leads to some unexpected value and the difference between the expected and the obtained value is the error." }, { "code": null, "e": 1478, "s": 1412, "text": "Below is an implementation that simulates the significance error:" }, { "code": null, "e": 1482, "s": 1478, "text": "C++" }, { "code": null, "e": 1487, "s": 1482, "text": "Java" }, { "code": null, "e": 1495, "s": 1487, "text": "Python3" }, { "code": null, "e": 1506, "s": 1495, "text": "Javascript" }, { "code": "// C++ program to illustrate the// floating-point error#include<bits/stdc++.h>using namespace std; double floatError(double no){ double sum = 0.0; for(int i = 0; i < 10; i++) { sum = sum + no; } return sum;} // Driver codeint main(){ cout << setprecision(16); cout << floatError(0.1);} // This code is contributed by rutvik_56", "e": 1861, "s": 1506, "text": null }, { "code": "// Java program to illustrate the// floating-point error public class GFG { public static double floatError(double no) { double sum = 0.0; for (int i = 0; i < 10; i++) { sum = sum + no; } return sum; } public static void main(String[] args) { System.out.println(floatError(0.1)); }}", "e": 2211, "s": 1861, "text": null }, { "code": "# Python3 program to illustrate the# floating-point error def floatError(no): sum = 0.0 for i in range(10): sum = sum + no return sum if __name__ == '__main__': print(floatError(0.1)) # This code is contributed by mohit kumar 29", "e": 2459, "s": 2211, "text": null }, { "code": "<script>// Javascript program to illustrate the// floating-point error function floatError(no){ let sum = 0.0; for (let i = 0; i < 10; i++) { sum = sum + no; } return sum;} document.write(floatError(0.1)); // This code is contributed by patel2127</script>", "e": 2752, "s": 2459, "text": null }, { "code": null, "e": 2771, "s": 2752, "text": "0.9999999999999999" }, { "code": null, "e": 2990, "s": 2773, "text": "Note: The expected value for the above implementation is 1.0 but the value returned is 0.9999999999999999. Therefore, in this article, a method to reduce this error by using Kahan’s Summation algorithm is discussed. " }, { "code": null, "e": 3272, "s": 2990, "text": "Kahan Summation Algorithm: The idea of the Kahan summation algorithm is to compensate for the floating-point error by keeping a separate variable to store the running time errors as the arithmetic operations are being performed. This can be visualised by the following pseudocode: " }, { "code": null, "e": 3730, "s": 3272, "text": "function KahanSum(input)\n var sum = 0.0 \n var c = 0.0 \n for i = 1 to input.length do \n \n var y = input[i] - c \n var t = sum + y \n c = (t - sum) - y \n \n sum = t \n \n next i \n\n return sum" }, { "code": null, "e": 3902, "s": 3730, "text": "In the above pseudocode, algebraically, the variable c in which the error is stored is always 0. However, when there is a loss of significance, it stores the error in it. " }, { "code": null, "e": 3953, "s": 3902, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3957, "s": 3953, "text": "C++" }, { "code": null, "e": 3962, "s": 3957, "text": "Java" }, { "code": null, "e": 3973, "s": 3962, "text": "Javascript" }, { "code": null, "e": 3981, "s": 3973, "text": "Python3" }, { "code": "// C++ program to illustrate the// Kahan summation algorithm #include <bits/stdc++.h>using namespace std; // Function to implement the Kahan// summation algorithmdouble kahanSum(vector<double> &fa){ double sum = 0.0; // Variable to store the error double c = 0.0; // Loop to iterate over the array for(double f : fa) { double y = f - c; double t = sum + y; // Algebraically, c is always 0 // when t is replaced by its // value from the above expression. // But, when there is a loss, // the higher-order y is cancelled // out by subtracting y from c and // all that remains is the // lower-order error in c c = (t - sum) - y; sum = t; } return sum;} // Function to implement the sum// of an arraydouble sum(vector<double> &fa){ double sum = 0.0; // Loop to find the sum of the array for(double f : fa) { sum = sum + f; } return sum;} // Driver codeint main(){ vector<double> no(10); for(int i = 0; i < 10; i++) { no[i] = 0.1; } // Comparing the results cout << setprecision(16); cout << \"Normal sum: \" << sum(no) << \" \\n\"; cout << \"Kahan sum: \" << kahanSum(no); } // This code is contributed by ajaykr00kj", "e": 5270, "s": 3981, "text": null }, { "code": "// Java program to illustrate the// Kahan summation algorithm public class GFG { // Function to implement the Kahan // summation algorithm private static double kahanSum(double... fa) { double sum = 0.0; // Variable to store the error double c = 0.0; // Loop to iterate over the array for (double f : fa) { double y = f - c; double t = sum + y; // Algebraically, c is always 0 // when t is replaced by its // value from the above expression. // But, when there is a loss, // the higher-order y is cancelled // out by subtracting y from c and // all that remains is the // lower-order error in c c = (t - sum) - y; sum = t; } return sum; } // Function to implement the sum // of an array private static double sum(double... fa) { double sum = 0.0; // Loop to find the sum of the array for (double f : fa) { sum = sum + f; } return sum; } // Driver code public static void main(String[] args) { double[] no = new double[10]; for (int i = 0; i < no.length; i++) { no[i] = 0.1; } // Comparing the results System.out.println(\"Normal sum: \" + sum(no)); System.out.println(\"Kahan sum: \" + kahanSum(no)); }}", "e": 6704, "s": 5270, "text": null }, { "code": "<script> // Javascript program to illustrate the// Kahan summation algorithm // Function to implement the Kahan// summation algorithmfunction kahanSum(fa){ let sum = 0.0; // Variable to store the error let c = 0.0; // Loop to iterate over the array for(let f = 0; f < fa.length; f++) { let y = fa[f] - c; let t = sum + y; // Algebraically, c is always 0 // when t is replaced by its // value from the above expression. // But, when there is a loss, // the higher-order y is cancelled // out by subtracting y from c and // all that remains is the // lower-order error in c c = (t - sum) - y; sum = t; } return sum;} // Function to implement the sum// of an arrayfunction sum(fa){ let sum = 0.0; // Loop to find the sum of the array for(let f = 0; f < fa.length; f++) { sum = sum + fa[f]; } return sum;} // Driver codelet no = new Array(10);for(let i = 0; i < no.length; i++){ no[i] = 0.1;} // Comparing the resultsdocument.write(\"Normal sum: \" + sum(no) + \"<br>\");document.write(\"Kahan sum: \" + kahanSum(no).toFixed(1) + \"<br>\"); // This code is contributed by unknown2108 </script>", "e": 7957, "s": 6704, "text": null }, { "code": "# Python3 program to illustrate the# Kahan summation algorithm # Function to implement the Kahan# summation algorithmdef kahanSum(fa): sum = 0.0 # Variable to store the error c = 0.0 # Loop to iterate over the array for f in fa: y = f - c t = sum + y # Algebraically, c is always 0 # when t is replaced by its # value from the above expression. # But, when there is a loss, # the higher-order y is cancelled # out by subtracting y from c and # all that remains is the # lower-order error in c c = (t - sum) - y sum = t return sum # Driver codeif __name__ == \"__main__\": no = [0.0] * 10 for i in range(10): no[i] = 0.1 # Comparing the results print(\"Normal sum: \", sum(no)) print(\"Kahan sum: \", kahanSum(no))", "e": 8795, "s": 7957, "text": null }, { "code": null, "e": 8841, "s": 8795, "text": "Normal sum: 0.9999999999999999\nKahan sum: 1.0" }, { "code": null, "e": 8922, "s": 8843, "text": "Time Complexity: O(N), where N is the length of the list.Auxiliary Space: O(1)" }, { "code": null, "e": 8937, "s": 8922, "text": "mohit kumar 29" }, { "code": null, "e": 8947, "s": 8937, "text": "rutvik_56" }, { "code": null, "e": 8958, "s": 8947, "text": "ajaykr00kj" }, { "code": null, "e": 8968, "s": 8958, "text": "patel2127" }, { "code": null, "e": 8980, "s": 8968, "text": "unknown2108" }, { "code": null, "e": 8996, "s": 8980, "text": "pankajsharmagfg" }, { "code": null, "e": 9023, "s": 8996, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 9039, "s": 9023, "text": "amartyaghoshgfg" }, { "code": null, "e": 9050, "s": 9039, "text": "Algorithms" }, { "code": null, "e": 9066, "s": 9050, "text": "Write From Home" }, { "code": null, "e": 9077, "s": 9066, "text": "Algorithms" } ]
Understanding “static” in “public static void main” in Java
28 Oct, 2020 Following points explain what is “static” in the main() method: main() method: The main() method, in Java, is the entry point for the JVM(Java Virtual Machine) into the java program. JVM launches the java program by invoking the main() method. Static is a keyword. The role of adding static before any entity is to make that entity a class entity. It means that adding static before methods and variables make them class methods and class variables respectively, instead of instance methods and instance variables. Hence, static methods and variables can be directly accessed with the help of Class, which means that there is no need to create objects in order to access static methods or variables. // Making a function as static static void func() {} // Making a variable as static static int var; Static methods: When a method is declared with static keyword, it is known as static method. As discussed above, any static member can be accessed before any objects of its class are created, and without reference to any object. // Making a static function class GfG { static void func() {} } // Calling a static function GfG.func(); Static main() method: When the static keyword is added in the function definition of main() method, then it is known as static main() method. class GfG { // Making a static main function public static void main(String[] args) {} } Need of static in main() method: Since main() method is the entry point of any Java application, hence making the main() method as static is mandatory due to following reasons: The static main() method makes it very clear for the JVM to call it for launching the Java Application. Otherwise, it would be required to specify the entry function for each Java application build, for the JVM to launch the application. The method is static because otherwise there would be ambiguity which constructor should be called. Example, if the class looks like this: public class GfG{ protected GfG(int g){} public void main(String[] args){ } } The JVM now enters an ambiguity state deciding whether it should call new GfG(int)? If yes, then what should it pass for g? If not, then should the JVM instantiate GfG without executing any constructor method? There are just too many edge cases and ambiguities like this for it to make sense for the JVM to have to instantiate a class before the entry point is called. That’s why main is static. The main() method is static because its convenient for the JDK. Consider a scenario where it’s not mandatory to make main() method static. Then in this case, that just makes it harder on various IDEs to auto-detect the ‘launchable’ classes in a project. Hence making it a convention to make the entry method ‘main()’ as ‘public static void main(String[] args)’ is convenient. What if we don’t write “static” before the main method: If we do not write “static” before the main method then, our program will be compiled without any compilation error(s). But at the time of execution, the JVM searches for the main method which is public, static, with a return type and a String array as an argument. If such a method is not found then an error is generated at the run time. Java /*package whatever //do not write package name here */ import java.io.*; class GFG { public void main (String[] args) { System.out.println("GFG!"); }} Output: An error message will be shown as follows nkmishra0102 java-basics Picked Programming Basics Static Keyword Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Oct, 2020" }, { "code": null, "e": 118, "s": 52, "text": "Following points explain what is “static” in the main() method: " }, { "code": null, "e": 300, "s": 118, "text": "main() method: The main() method, in Java, is the entry point for the JVM(Java Virtual Machine) into the java program. JVM launches the java program by invoking the main() method. " }, { "code": null, "e": 758, "s": 300, "text": "Static is a keyword. The role of adding static before any entity is to make that entity a class entity. It means that adding static before methods and variables make them class methods and class variables respectively, instead of instance methods and instance variables. Hence, static methods and variables can be directly accessed with the help of Class, which means that there is no need to create objects in order to access static methods or variables. " }, { "code": null, "e": 863, "s": 758, "text": "// Making a function as static\nstatic void func()\n{}\n\n// Making a variable as static\nstatic int var;\n\n\n\n" }, { "code": null, "e": 1094, "s": 863, "text": "Static methods: When a method is declared with static keyword, it is known as static method. As discussed above, any static member can be accessed before any objects of its class are created, and without reference to any object. " }, { "code": null, "e": 1212, "s": 1094, "text": "// Making a static function\nclass GfG\n{\n static void func()\n {}\n}\n\n// Calling a static function\nGfG.func();\n\n\n\n" }, { "code": null, "e": 1356, "s": 1212, "text": "Static main() method: When the static keyword is added in the function definition of main() method, then it is known as static main() method. " }, { "code": null, "e": 1461, "s": 1356, "text": "class GfG\n{\n // Making a static main function\n public static void main(String[] args)\n {}\n}\n\n\n\n" }, { "code": null, "e": 1640, "s": 1461, "text": "Need of static in main() method: Since main() method is the entry point of any Java application, hence making the main() method as static is mandatory due to following reasons: " }, { "code": null, "e": 1878, "s": 1640, "text": "The static main() method makes it very clear for the JVM to call it for launching the Java Application. Otherwise, it would be required to specify the entry function for each Java application build, for the JVM to launch the application." }, { "code": null, "e": 2019, "s": 1878, "text": "The method is static because otherwise there would be ambiguity which constructor should be called. Example, if the class looks like this: " }, { "code": null, "e": 2107, "s": 2019, "text": "public class GfG{\n protected GfG(int g){}\n public void main(String[] args){\n }\n}\n\n\n\n" }, { "code": null, "e": 2503, "s": 2107, "text": "The JVM now enters an ambiguity state deciding whether it should call new GfG(int)? If yes, then what should it pass for g? If not, then should the JVM instantiate GfG without executing any constructor method? There are just too many edge cases and ambiguities like this for it to make sense for the JVM to have to instantiate a class before the entry point is called. That’s why main is static." }, { "code": null, "e": 2879, "s": 2503, "text": "The main() method is static because its convenient for the JDK. Consider a scenario where it’s not mandatory to make main() method static. Then in this case, that just makes it harder on various IDEs to auto-detect the ‘launchable’ classes in a project. Hence making it a convention to make the entry method ‘main()’ as ‘public static void main(String[] args)’ is convenient." }, { "code": null, "e": 3275, "s": 2879, "text": "What if we don’t write “static” before the main method: If we do not write “static” before the main method then, our program will be compiled without any compilation error(s). But at the time of execution, the JVM searches for the main method which is public, static, with a return type and a String array as an argument. If such a method is not found then an error is generated at the run time." }, { "code": null, "e": 3280, "s": 3275, "text": "Java" }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public void main (String[] args) { System.out.println(\"GFG!\"); }}", "e": 3444, "s": 3280, "text": null }, { "code": null, "e": 3494, "s": 3444, "text": "Output: An error message will be shown as follows" }, { "code": null, "e": 3507, "s": 3494, "text": "nkmishra0102" }, { "code": null, "e": 3519, "s": 3507, "text": "java-basics" }, { "code": null, "e": 3526, "s": 3519, "text": "Picked" }, { "code": null, "e": 3545, "s": 3526, "text": "Programming Basics" }, { "code": null, "e": 3560, "s": 3545, "text": "Static Keyword" }, { "code": null, "e": 3565, "s": 3560, "text": "Java" }, { "code": null, "e": 3584, "s": 3565, "text": "School Programming" }, { "code": null, "e": 3589, "s": 3584, "text": "Java" } ]
Swift – Convert String to Int Swift
07 Jan, 2022 Swift provides a number of ways to convert a string value into an integer value. Though, we can convert a numeric string only into an integer value. In this article, we will see the two most common methods used to convert a string to an integer value. A string is a collection of characters. Swift provides String data type with the help of which we can store a string. For example, “GeeksforGeeks”, “GFG”, etc. A variable can be declared as String type by following the below syntax, Syntax: let myVariable: String For example: myVariable = “GeeksforGeeks” Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer. let myStringVariable = “25” let myIntegerVariable = Int(myStringVariable) ?? 0 It means that if the string is non-numeric then assign the variable with 0 otherwise convert the numeric string to an integer. Below is the implementation to convert a String into Int: Example: Swift // Swift program to convert String to Int // Here we are converting a numeric string. // Initializing a constant variable of string typelet myStringVariable = "25" // Converting the string into integer typelet myIntegerVariable = Int(myStringVariable) ?? 0 // Print the value represented by myIntegerVariableprint("Integer Value:", myIntegerVariable) // Here, we are converting a non-numeric string.// Initializing a constant variable of string typelet myStringvariable = "GeeksforGeeks" // Trying to convert "GeeksforGeeks" // to the integer equivalent but since // it's non-numeric string hence the// optional value would be assigned // to the integer variable which is// equal to 0 in this caselet myIntegervariable = Int(myStringvariable) ?? 0 // Print the value represented by myIntegervariableprint("Integer Value:", myIntegervariable) Output: Integer Value: 25 Integer Value: 0 NSString in Swift is a class that is used to create objects that lie in heap and they are passed by reference. It provides different types of methods for comparing, searching, and modifying strings. We can convert a numeric string into an integer value indirectly. Firstly, we can convert a string into an NSString then we can use “integerValue” property used with NSStrings to convert an NSString into an integer value. Example: In the below program we have converted the numeric string into NSString then we have applied “integerValue” property to convert a string into an integer value. Swift // Swift program to convert String to Int import Foundationimport Glibc let myString = "25" // Firstly we are converting a string into NSString then// using integerValue property we get integer valuelet myIntegerVariable = (myString as NSString) .integerValue print("Integer Value:", myString) Output: Integer Value: 25 arorakashish0911 Picked Swift Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jan, 2022" }, { "code": null, "e": 537, "s": 52, "text": "Swift provides a number of ways to convert a string value into an integer value. Though, we can convert a numeric string only into an integer value. In this article, we will see the two most common methods used to convert a string to an integer value. A string is a collection of characters. Swift provides String data type with the help of which we can store a string. For example, “GeeksforGeeks”, “GFG”, etc. A variable can be declared as String type by following the below syntax," }, { "code": null, "e": 545, "s": 537, "text": "Syntax:" }, { "code": null, "e": 569, "s": 545, "text": "let myVariable: String " }, { "code": null, "e": 611, "s": 569, "text": "For example: myVariable = “GeeksforGeeks”" }, { "code": null, "e": 840, "s": 611, "text": "Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer. " }, { "code": null, "e": 868, "s": 840, "text": "let myStringVariable = “25”" }, { "code": null, "e": 942, "s": 868, "text": "let myIntegerVariable = Int(myStringVariable) ?? 0 " }, { "code": null, "e": 1127, "s": 942, "text": "It means that if the string is non-numeric then assign the variable with 0 otherwise convert the numeric string to an integer. Below is the implementation to convert a String into Int:" }, { "code": null, "e": 1136, "s": 1127, "text": "Example:" }, { "code": null, "e": 1142, "s": 1136, "text": "Swift" }, { "code": "// Swift program to convert String to Int // Here we are converting a numeric string. // Initializing a constant variable of string typelet myStringVariable = \"25\" // Converting the string into integer typelet myIntegerVariable = Int(myStringVariable) ?? 0 // Print the value represented by myIntegerVariableprint(\"Integer Value:\", myIntegerVariable) // Here, we are converting a non-numeric string.// Initializing a constant variable of string typelet myStringvariable = \"GeeksforGeeks\" // Trying to convert \"GeeksforGeeks\" // to the integer equivalent but since // it's non-numeric string hence the// optional value would be assigned // to the integer variable which is// equal to 0 in this caselet myIntegervariable = Int(myStringvariable) ?? 0 // Print the value represented by myIntegervariableprint(\"Integer Value:\", myIntegervariable)", "e": 1991, "s": 1142, "text": null }, { "code": null, "e": 1999, "s": 1991, "text": "Output:" }, { "code": null, "e": 2034, "s": 1999, "text": "Integer Value: 25\nInteger Value: 0" }, { "code": null, "e": 2456, "s": 2034, "text": "NSString in Swift is a class that is used to create objects that lie in heap and they are passed by reference. It provides different types of methods for comparing, searching, and modifying strings. We can convert a numeric string into an integer value indirectly. Firstly, we can convert a string into an NSString then we can use “integerValue” property used with NSStrings to convert an NSString into an integer value. " }, { "code": null, "e": 2466, "s": 2456, "text": "Example: " }, { "code": null, "e": 2626, "s": 2466, "text": "In the below program we have converted the numeric string into NSString then we have applied “integerValue” property to convert a string into an integer value." }, { "code": null, "e": 2632, "s": 2626, "text": "Swift" }, { "code": "// Swift program to convert String to Int import Foundationimport Glibc let myString = \"25\" // Firstly we are converting a string into NSString then// using integerValue property we get integer valuelet myIntegerVariable = (myString as NSString) .integerValue print(\"Integer Value:\", myString)", "e": 2930, "s": 2632, "text": null }, { "code": null, "e": 2938, "s": 2930, "text": "Output:" }, { "code": null, "e": 2956, "s": 2938, "text": "Integer Value: 25" }, { "code": null, "e": 2973, "s": 2956, "text": "arorakashish0911" }, { "code": null, "e": 2980, "s": 2973, "text": "Picked" }, { "code": null, "e": 2986, "s": 2980, "text": "Swift" } ]
How to check an element with ng-if is visible on DOM ?
23 Sep, 2021 ng-if directive: The ng-if directive in AngularJS is used to remove or recreate a portion of the HTML element based on an expression. If the expression inside it is false then the element is removed and if it is true then the element is added to the DOM. Syntax: <element ng-if="expression"> Contents... </element> Approach: Consider a checkoff list made containing three items. Once all the items are bought then we display a message — “Everything is bought!”. At starting NG-IF removes this message from a portion of the DOM tree and based on the expression when it gets evaluated as true as it is recreated in DOM. To observe these changes we are going to inspect the code on Web Browser. Different ways to approach enable Inspect in Google Chrome:Menu bar -> More tools -> Developer tools.Right Click in the browser -> InspectCtrl + Shift + I (Windows)Cmd + Opt + I (Mac OS) Menu bar -> More tools -> Developer tools. Right Click in the browser -> Inspect Ctrl + Shift + I (Windows) Cmd + Opt + I (Mac OS) Note: For more information go to chrome-inspect-element-tool-shortcut. Code Implementation: HTML <!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.0/angular.min.js"> </script></head> <body ng-app="myApp"> <div ng-controller="myCtrl" class="w3-container"> <h1 align="center" class="w3-text-green"> GeeksforGeeks </h1> <h4 align="center" class="w3-text-green"> A computer science portal for geeks </h4> <ul> <li ng-repeat="item in items"> Buy {{item.name}} {{item.quantity}} <button ng-click=Bought($index) class="w3-button w3-round w3-border w3-margin-bottom"> Bought </button> </li> </ul> <p class="w3-text-red" align="center" ng-if="items.length == 0"> Everything is Bought! </p> </div> <script type="text/javascript"> (function () { angular.module("myApp", []).controller( "myCtrl", function ($scope) { $scope.items = [ { name: "Milk", quantity: "2 Packet" }, { name: "Biscuit", quantity: "10 Packet" }, { name: "Bread", quantity: "5 Packet" } ]; $scope.Bought = function (index) { $scope.items.splice(index, 1); }; }); })(); </script></body> </html> Output: Before Clicking all buttons: Here, we have three buttons to click and buy respective items. In Inspect window: we can see that ng-if is commented out and a part of the DOM tree as expression evaluated to be False. After Clicking all buttons: As we have clicked all the buttons and purchased every item, a message is displayed on the screen. In Inspect window: we can see that ng-if is now not commented anymore and now it is a part of the DOM tree as expression evaluated to be True. This gif output shows what all is happening. anikakapoor AngularJS-Misc AngularJS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Auth Guards in Angular 9/10/11 Routing in Angular 9/10 How to bundle an Angular app for production? What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2021" }, { "code": null, "e": 283, "s": 28, "text": "ng-if directive: The ng-if directive in AngularJS is used to remove or recreate a portion of the HTML element based on an expression. If the expression inside it is false then the element is removed and if it is true then the element is added to the DOM." }, { "code": null, "e": 291, "s": 283, "text": "Syntax:" }, { "code": null, "e": 343, "s": 291, "text": "<element ng-if=\"expression\"> Contents... </element>" }, { "code": null, "e": 353, "s": 343, "text": "Approach:" }, { "code": null, "e": 407, "s": 353, "text": "Consider a checkoff list made containing three items." }, { "code": null, "e": 490, "s": 407, "text": "Once all the items are bought then we display a message — “Everything is bought!”." }, { "code": null, "e": 646, "s": 490, "text": "At starting NG-IF removes this message from a portion of the DOM tree and based on the expression when it gets evaluated as true as it is recreated in DOM." }, { "code": null, "e": 907, "s": 646, "text": "To observe these changes we are going to inspect the code on Web Browser. Different ways to approach enable Inspect in Google Chrome:Menu bar -> More tools -> Developer tools.Right Click in the browser -> InspectCtrl + Shift + I (Windows)Cmd + Opt + I (Mac OS)" }, { "code": null, "e": 950, "s": 907, "text": "Menu bar -> More tools -> Developer tools." }, { "code": null, "e": 988, "s": 950, "text": "Right Click in the browser -> Inspect" }, { "code": null, "e": 1015, "s": 988, "text": "Ctrl + Shift + I (Windows)" }, { "code": null, "e": 1038, "s": 1015, "text": "Cmd + Opt + I (Mac OS)" }, { "code": null, "e": 1109, "s": 1038, "text": "Note: For more information go to chrome-inspect-element-tool-shortcut." }, { "code": null, "e": 1131, "s": 1109, "text": "Code Implementation: " }, { "code": null, "e": 1136, "s": 1131, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://www.w3schools.com/w3css/4/w3.css\"> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.0/angular.min.js\"> </script></head> <body ng-app=\"myApp\"> <div ng-controller=\"myCtrl\" class=\"w3-container\"> <h1 align=\"center\" class=\"w3-text-green\"> GeeksforGeeks </h1> <h4 align=\"center\" class=\"w3-text-green\"> A computer science portal for geeks </h4> <ul> <li ng-repeat=\"item in items\"> Buy {{item.name}} {{item.quantity}} <button ng-click=Bought($index) class=\"w3-button w3-round w3-border w3-margin-bottom\"> Bought </button> </li> </ul> <p class=\"w3-text-red\" align=\"center\" ng-if=\"items.length == 0\"> Everything is Bought! </p> </div> <script type=\"text/javascript\"> (function () { angular.module(\"myApp\", []).controller( \"myCtrl\", function ($scope) { $scope.items = [ { name: \"Milk\", quantity: \"2 Packet\" }, { name: \"Biscuit\", quantity: \"10 Packet\" }, { name: \"Bread\", quantity: \"5 Packet\" } ]; $scope.Bought = function (index) { $scope.items.splice(index, 1); }; }); })(); </script></body> </html>", "e": 2758, "s": 1136, "text": null }, { "code": null, "e": 2766, "s": 2758, "text": "Output:" }, { "code": null, "e": 2858, "s": 2766, "text": "Before Clicking all buttons: Here, we have three buttons to click and buy respective items." }, { "code": null, "e": 2980, "s": 2858, "text": "In Inspect window: we can see that ng-if is commented out and a part of the DOM tree as expression evaluated to be False." }, { "code": null, "e": 3107, "s": 2980, "text": "After Clicking all buttons: As we have clicked all the buttons and purchased every item, a message is displayed on the screen." }, { "code": null, "e": 3250, "s": 3107, "text": "In Inspect window: we can see that ng-if is now not commented anymore and now it is a part of the DOM tree as expression evaluated to be True." }, { "code": null, "e": 3295, "s": 3250, "text": "This gif output shows what all is happening." }, { "code": null, "e": 3307, "s": 3295, "text": "anikakapoor" }, { "code": null, "e": 3322, "s": 3307, "text": "AngularJS-Misc" }, { "code": null, "e": 3332, "s": 3322, "text": "AngularJS" }, { "code": null, "e": 3349, "s": 3332, "text": "Web Technologies" }, { "code": null, "e": 3376, "s": 3349, "text": "Web technologies Questions" }, { "code": null, "e": 3474, "s": 3376, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3505, "s": 3474, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 3529, "s": 3505, "text": "Routing in Angular 9/10" }, { "code": null, "e": 3574, "s": 3529, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 3616, "s": 3574, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 3651, "s": 3616, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 3684, "s": 3651, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3746, "s": 3684, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3807, "s": 3746, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3857, "s": 3807, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part 3
24 Jun, 2022 In Manacher’s Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. Here we will implement the same.We have seen that there are no new character comparison needed in case 1 and case 2. In case 3 and case 4, necessary new comparison are needed. In following figure, If at all we need a comparison, we will only compare actual characters, which are at “odd” positions like 1, 3, 5, 7, etc. Even positions do not represent a character in string, so no comparison will be performed for even positions. If two characters at different odd positions match, then they will increase LPS length by 2. There are many ways to implement this depending on how even and odd positions are handled. One way would be to create a new string 1st where we insert some unique character (say #, $ etc) in all even positions and then run algorithm on that (to avoid different way of even and odd position handling). Other way could be to work on given string itself but here even and odd positions should be handled appropriately. Here we will start with given string itself. When there is a need of expansion and character comparison required, we will expand in left and right positions one by one. When odd position is found, comparison will be done and LPS Length will be incremented by ONE. When even position is found, no comparison done and LPS Length will be incremented by ONE (So overall, one odd and one even positions on both left and right side will increase LPS Length by TWO). Implementation: C Java Python3 C# Javascript // A C program to implement Manacher’s Algorithm#include <stdio.h>#include <string.h> char text[100];void findLongestPalindromicString(){ int N = strlen(text); if(N == 0) return; N = 2*N + 1; //Position count int L[N]; //LPS Length Array L[0] = 0; L[1] = 1; int C = 1; //centerPosition int R = 2; //centerRightPosition int i = 0; //currentRightPosition int iMirror; //currentLeftPosition int expand = -1; int diff = -1; int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; //Uncomment it to print LPS Length array //printf("%d %d ", L[0], L[1]); for (i = 2; i < N; i++) { //get currentLeftPosition iMirror for currentRightPosition i iMirror = 2*C-i; //Reset expand - means no expansion required expand = 0; diff = R - i; //If currentRightPosition i is within centerRightPosition R if(diff >= 0) { if(L[iMirror] < diff) // Case 1 L[i] = L[iMirror]; else if(L[iMirror] == diff && R == N-1) // Case 2 L[i] = L[iMirror]; else if(L[iMirror] == diff && R < N-1) // Case 3 { L[i] = L[iMirror]; expand = 1; // expansion required } else if(L[iMirror] > diff) // Case 4 { L[i] = diff; expand = 1; // expansion required } } else { L[i] = 0; expand = 1; // expansion required } if (expand == 1) { //Attempt to expand palindrome centered at currentRightPosition i //Here for odd positions, we compare characters and //if match then increment LPS Length by ONE //If even position, we just increment LPS by ONE without //any character comparison while (((i + L[i]) < N && (i - L[i]) > 0) && ( ((i + L[i] + 1) % 2 == 0) || (text[(i + L[i] + 1)/2] == text[(i-L[i]-1)/2] ))) { L[i]++; } } if(L[i] > maxLPSLength) // Track maxLPSLength { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at currentRightPosition i // expand beyond centerRightPosition R, // adjust centerPosition C based on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } //Uncomment it to print LPS Length array //printf("%d ", L[i]); } //printf("\n"); start = (maxLPSCenterPosition - maxLPSLength)/2; end = start + maxLPSLength - 1; //printf("start: %d end: %d\n", start, end); printf("LPS of string is %s : ", text); for(i=start; i<=end; i++) printf("%c", text[i]); printf("\n");} int main(int argc, char *argv[]){ strcpy(text, "babcbabcbaccba"); findLongestPalindromicString(); strcpy(text, "abaaba"); findLongestPalindromicString(); strcpy(text, "abababa"); findLongestPalindromicString(); strcpy(text, "abcbabcbabcba"); findLongestPalindromicString(); strcpy(text, "forgeeksskeegfor"); findLongestPalindromicString(); strcpy(text, "caba"); findLongestPalindromicString(); strcpy(text, "abacdfgdcaba"); findLongestPalindromicString(); strcpy(text, "abacdfgdcabba"); findLongestPalindromicString(); strcpy(text, "abacdedcaba"); findLongestPalindromicString(); return 0;} // A Java program to implement Manacher’s Algorithmimport java.lang.*; class GFG{ public static void findLongestPalindromicString( String text){ int N = text.length(); if(N == 0) return; // Position count N = 2 * N + 1; // LPS Length Array int []L = new int [N]; L[0] = 0; L[1] = 1; // centerPosition int C = 1; // centerRightPosition int R = 2; // currentRightPosition int i = 0; // currentLeftPosition int iMirror; int expand = -1; int diff = -1; int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; // Uncomment it to print LPS Length array // printf("%d %d ", L[0], L[1]); for (i = 2; i < N; i++) { // Get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; // Reset expand - means no // expansion required expand = 0; diff = R - i; // If currentRightPosition i is // within centerRightPosition R if(diff >= 0) { // Case 1 if(L[iMirror] < diff) L[i] = L[iMirror]; // Case 2 else if(L[iMirror] == diff && R == N - 1) L[i] = L[iMirror]; // Case 3 else if(L[iMirror] == diff && R < N - 1) { L[i] = L[iMirror]; // Expansion required expand = 1; } // Case 4 else if(L[iMirror] > diff) { L[i] = diff; // Expansion required expand = 1; } } else { L[i] = 0; // Expansion required expand = 1; } if (expand == 1) { // Attempt to expand palindrome centered // at currentRightPosition i. Here for odd // positions, we compare characters and // if match then increment LPS Length by ONE // If even position, we just increment LPS // by ONE without any character comparison try { while (((i + L[i]) < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text.charAt((i + L[i] + 1) / 2) == text.charAt((i - L[i] - 1) / 2)))) { L[i]++; } } catch (Exception e) { assert true; } } // Track maxLPSLength if(L[i] > maxLPSLength) { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at // currentRightPosition i expand // beyond centerRightPosition R, // adjust centerPosition C based // on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } //Uncomment it to print LPS Length array //System.out.print("%d ", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; //System.out.print("start: %d end: %d\n", // start, end); System.out.print("LPS of string is " + text + " : "); for(i = start; i <= end; i++) System.out.print(text.charAt(i)); System.out.println();} // Driver codepublic static void main(String []args){ String text1="babcbabcbaccba"; findLongestPalindromicString(text1); String text2="abaaba"; findLongestPalindromicString(text2); String text3= "abababa"; findLongestPalindromicString(text3); String text4="abcbabcbabcba"; findLongestPalindromicString(text4); String text5="forgeeksskeegfor"; findLongestPalindromicString(text5); String text6="caba"; findLongestPalindromicString(text6); String text7="abacdfgdcaba"; findLongestPalindromicString(text7); String text8="abacdfgdcabba"; findLongestPalindromicString(text8); String text9="abacdedcaba"; findLongestPalindromicString(text9);}} // This code is contributed by SoumikMondal # Python program to implement Manacher's Algorithm def findLongestPalindromicString(text): N = len(text) if N == 0: return N = 2*N+1 # Position count L = [0] * N L[0] = 0 L[1] = 1 C = 1 # centerPosition R = 2 # centerRightPosition i = 0 # currentRightPosition iMirror = 0 # currentLeftPosition maxLPSLength = 0 maxLPSCenterPosition = 0 start = -1 end = -1 diff = -1 # Uncomment it to print LPS Length array # printf("%d %d ", L[0], L[1]); for i in range(2,N): # get currentLeftPosition iMirror for currentRightPosition i iMirror = 2*C-i L[i] = 0 diff = R - i # If currentRightPosition i is within centerRightPosition R if diff > 0: L[i] = min(L[iMirror], diff) # Attempt to expand palindrome centered at currentRightPosition i # Here for odd positions, we compare characters and # if match then increment LPS Length by ONE # If even position, we just increment LPS by ONE without # any character comparison try: while ((i+L[i]) < N and (i-L[i]) > 0) and \ (((i+L[i]+1) % 2 == 0) or \ (text[(i+L[i]+1)//2] == text[(i-L[i]-1)//2])): L[i]+=1 except Exception as e: pass if L[i] > maxLPSLength: # Track maxLPSLength maxLPSLength = L[i] maxLPSCenterPosition = i # If palindrome centered at currentRightPosition i # expand beyond centerRightPosition R, # adjust centerPosition C based on expanded palindrome. if i + L[i] > R: C = i R = i + L[i] # Uncomment it to print LPS Length array # printf("%d ", L[i]); start = (maxLPSCenterPosition - maxLPSLength) // 2 end = start + maxLPSLength - 1 print ("LPS of string is " + text + " : ",text[start:end+1]) # Driver programtext1 = "babcbabcbaccba"findLongestPalindromicString(text1) text2 = "abaaba"findLongestPalindromicString(text2) text3 = "abababa"findLongestPalindromicString(text3) text4 = "abcbabcbabcba"findLongestPalindromicString(text4) text5 = "forgeeksskeegfor"findLongestPalindromicString(text5) text6 = "caba"findLongestPalindromicString(text6) text7 = "abacdfgdcaba"findLongestPalindromicString(text7) text8 = "abacdfgdcabba"findLongestPalindromicString(text8) text9 = "abacdedcaba"findLongestPalindromicString(text9) # This code is contributed by BHAVYA JAIN // A C# program to implement Manacher’s Algorithmusing System;using System.Diagnostics;public class GFG{ public static void findLongestPalindromicString( String text){ int N = text.Length; if(N == 0) return; // Position count N = 2 * N + 1; // LPS Length Array int []L = new int [N]; L[0] = 0; L[1] = 1; // centerPosition int C = 1; // centerRightPosition int R = 2; // currentRightPosition int i = 0; // currentLeftPosition int iMirror; int expand = -1; int diff = -1; int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; // Uncomment it to print LPS Length array // printf("%d %d ", L[0], L[1]); for (i = 2; i < N; i++) { // Get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; // Reset expand - means no // expansion required expand = 0; diff = R - i; // If currentRightPosition i is // within centerRightPosition R if(diff >= 0) { // Case 1 if(L[iMirror] < diff) L[i] = L[iMirror]; // Case 2 else if(L[iMirror] == diff && R == N - 1) L[i] = L[iMirror]; // Case 3 else if(L[iMirror] == diff && R < N - 1) { L[i] = L[iMirror]; // Expansion required expand = 1; } // Case 4 else if(L[iMirror] > diff) { L[i] = diff; // Expansion required expand = 1; } } else { L[i] = 0; // Expansion required expand = 1; } if (expand == 1) { // Attempt to expand palindrome centered // at currentRightPosition i. Here for odd // positions, we compare characters and // if match then increment LPS Length by ONE // If even position, we just increment LPS // by ONE without any character comparison try { while (((i + L[i]) < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text[(i + L[i] + 1) / 2] == text[(i - L[i] - 1) / 2]))) { L[i]++; } } catch (Exception) { Debug.Assert(true); } } // Track maxLPSLength if(L[i] > maxLPSLength) { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at // currentRightPosition i expand // beyond centerRightPosition R, // adjust centerPosition C based // on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } //Uncomment it to print LPS Length array //System.out.print("%d ", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; //System.out.print("start: %d end: %d\n", // start, end); Console.Write("LPS of string is " + text + " : "); for(i = start; i <= end; i++) Console.Write(text[i]); Console.WriteLine();} // Driver codestatic public void Main (){ String text1 = "babcbabcbaccba"; findLongestPalindromicString(text1); String text2 = "abaaba"; findLongestPalindromicString(text2); String text3 = "abababa"; findLongestPalindromicString(text3); String text4 = "abcbabcbabcba"; findLongestPalindromicString(text4); String text5 = "forgeeksskeegfor"; findLongestPalindromicString(text5); String text6 = "caba"; findLongestPalindromicString(text6); String text7 = "abacdfgdcaba"; findLongestPalindromicString(text7); String text8 = "abacdfgdcabba"; findLongestPalindromicString(text8); String text9 = "abacdedcaba"; findLongestPalindromicString(text9);}} // This code is contributed by Dharanendra L V. <script>// A Javascript program to implement Manacher’s Algorithm function findLongestPalindromicString(text){ let N = text.length; if(N == 0) return; // Position count N = 2 * N + 1; // LPS Length Array let L = new Array(N); L[0] = 0; L[1] = 1; // centerPosition let C = 1; // centerRightPosition let R = 2; // currentRightPosition let i = 0; // currentLeftPosition let iMirror; let expand = -1; let diff = -1; let maxLPSLength = 0; let maxLPSCenterPosition = 0; let start = -1; let end = -1; // Uncomment it to print LPS Length array // printf("%d %d ", L[0], L[1]); for (i = 2; i < N; i++) { // Get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; // Reset expand - means no // expansion required expand = 0; diff = R - i; // If currentRightPosition i is // within centerRightPosition R if(diff >= 0) { // Case 1 if(L[iMirror] < diff) L[i] = L[iMirror]; // Case 2 else if(L[iMirror] == diff && R == N - 1) L[i] = L[iMirror]; // Case 3 else if(L[iMirror] == diff && R < N - 1) { L[i] = L[iMirror]; // Expansion required expand = 1; } // Case 4 else if(L[iMirror] > diff) { L[i] = diff; // Expansion required expand = 1; } } else { L[i] = 0; // Expansion required expand = 1; } if (expand == 1) { // Attempt to expand palindrome centered // at currentRightPosition i. Here for odd // positions, we compare characters and // if match then increment LPS Length by ONE // If even position, we just increment LPS // by ONE without any character comparison while (((i + L[i]) < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text[Math.floor((i + L[i] + 1) / 2)] == text[Math.floor((i - L[i] - 1) / 2)]))) { L[i]++; } } // Track maxLPSLength if(L[i] > maxLPSLength) { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at // currentRightPosition i expand // beyond centerRightPosition R, // adjust centerPosition C based // on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } //Uncomment it to print LPS Length array //System.out.print("%d ", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; //System.out.print("start: %d end: %d\n", // start, end); document.write("LPS of string is " + text + " : "); for(i = start; i <= end; i++) document.write(text[i]); document.write("<br>");} // Driver code let text1="babcbabcbaccba";findLongestPalindromicString(text1); let text2="abaaba";findLongestPalindromicString(text2); let text3= "abababa";findLongestPalindromicString(text3); let text4="abcbabcbabcba";findLongestPalindromicString(text4); let text5="forgeeksskeegfor";findLongestPalindromicString(text5); let text6="caba";findLongestPalindromicString(text6); let text7="abacdfgdcaba";findLongestPalindromicString(text7); let text8="abacdfgdcabba";findLongestPalindromicString(text8); let text9="abacdedcaba";findLongestPalindromicString(text9); // This code is contributed by unknown2108</script> LPS of string is babcbabcbaccba : abcbabcba LPS of string is abaaba : abaaba LPS of string is abababa : abababa LPS of string is abcbabcbabcba : abcbabcbabcba LPS of string is forgeeksskeegfor : geeksskeeg LPS of string is caba : aba LPS of string is abacdfgdcaba : aba LPS of string is abacdfgdcabba : abba LPS of string is abacdedcaba : abacdedcaba This is the implementation based on the four cases discussed in Part 2. In Part 4, we have discussed a different way to look at these four cases and few other approaches. DmitriyPhilimonov SoumikMondal dharanendralv23 unknown2108 kashishsoda amartyaghoshgfg hardikkoriintern palindrome Pattern Searching Strings Strings palindrome Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jun, 2022" }, { "code": null, "e": 416, "s": 54, "text": "In Manacher’s Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. Here we will implement the same.We have seen that there are no new character comparison needed in case 1 and case 2. In case 3 and case 4, necessary new comparison are needed. In following figure, " }, { "code": null, "e": 742, "s": 416, "text": "If at all we need a comparison, we will only compare actual characters, which are at “odd” positions like 1, 3, 5, 7, etc. Even positions do not represent a character in string, so no comparison will be performed for even positions. If two characters at different odd positions match, then they will increase LPS length by 2." }, { "code": null, "e": 1158, "s": 742, "text": "There are many ways to implement this depending on how even and odd positions are handled. One way would be to create a new string 1st where we insert some unique character (say #, $ etc) in all even positions and then run algorithm on that (to avoid different way of even and odd position handling). Other way could be to work on given string itself but here even and odd positions should be handled appropriately." }, { "code": null, "e": 1618, "s": 1158, "text": "Here we will start with given string itself. When there is a need of expansion and character comparison required, we will expand in left and right positions one by one. When odd position is found, comparison will be done and LPS Length will be incremented by ONE. When even position is found, no comparison done and LPS Length will be incremented by ONE (So overall, one odd and one even positions on both left and right side will increase LPS Length by TWO)." }, { "code": null, "e": 1634, "s": 1618, "text": "Implementation:" }, { "code": null, "e": 1636, "s": 1634, "text": "C" }, { "code": null, "e": 1641, "s": 1636, "text": "Java" }, { "code": null, "e": 1649, "s": 1641, "text": "Python3" }, { "code": null, "e": 1652, "s": 1649, "text": "C#" }, { "code": null, "e": 1663, "s": 1652, "text": "Javascript" }, { "code": "// A C program to implement Manacher’s Algorithm#include <stdio.h>#include <string.h> char text[100];void findLongestPalindromicString(){ int N = strlen(text); if(N == 0) return; N = 2*N + 1; //Position count int L[N]; //LPS Length Array L[0] = 0; L[1] = 1; int C = 1; //centerPosition int R = 2; //centerRightPosition int i = 0; //currentRightPosition int iMirror; //currentLeftPosition int expand = -1; int diff = -1; int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; //Uncomment it to print LPS Length array //printf(\"%d %d \", L[0], L[1]); for (i = 2; i < N; i++) { //get currentLeftPosition iMirror for currentRightPosition i iMirror = 2*C-i; //Reset expand - means no expansion required expand = 0; diff = R - i; //If currentRightPosition i is within centerRightPosition R if(diff >= 0) { if(L[iMirror] < diff) // Case 1 L[i] = L[iMirror]; else if(L[iMirror] == diff && R == N-1) // Case 2 L[i] = L[iMirror]; else if(L[iMirror] == diff && R < N-1) // Case 3 { L[i] = L[iMirror]; expand = 1; // expansion required } else if(L[iMirror] > diff) // Case 4 { L[i] = diff; expand = 1; // expansion required } } else { L[i] = 0; expand = 1; // expansion required } if (expand == 1) { //Attempt to expand palindrome centered at currentRightPosition i //Here for odd positions, we compare characters and //if match then increment LPS Length by ONE //If even position, we just increment LPS by ONE without //any character comparison while (((i + L[i]) < N && (i - L[i]) > 0) && ( ((i + L[i] + 1) % 2 == 0) || (text[(i + L[i] + 1)/2] == text[(i-L[i]-1)/2] ))) { L[i]++; } } if(L[i] > maxLPSLength) // Track maxLPSLength { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at currentRightPosition i // expand beyond centerRightPosition R, // adjust centerPosition C based on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } //Uncomment it to print LPS Length array //printf(\"%d \", L[i]); } //printf(\"\\n\"); start = (maxLPSCenterPosition - maxLPSLength)/2; end = start + maxLPSLength - 1; //printf(\"start: %d end: %d\\n\", start, end); printf(\"LPS of string is %s : \", text); for(i=start; i<=end; i++) printf(\"%c\", text[i]); printf(\"\\n\");} int main(int argc, char *argv[]){ strcpy(text, \"babcbabcbaccba\"); findLongestPalindromicString(); strcpy(text, \"abaaba\"); findLongestPalindromicString(); strcpy(text, \"abababa\"); findLongestPalindromicString(); strcpy(text, \"abcbabcbabcba\"); findLongestPalindromicString(); strcpy(text, \"forgeeksskeegfor\"); findLongestPalindromicString(); strcpy(text, \"caba\"); findLongestPalindromicString(); strcpy(text, \"abacdfgdcaba\"); findLongestPalindromicString(); strcpy(text, \"abacdfgdcabba\"); findLongestPalindromicString(); strcpy(text, \"abacdedcaba\"); findLongestPalindromicString(); return 0;}", "e": 5204, "s": 1663, "text": null }, { "code": "// A Java program to implement Manacher’s Algorithmimport java.lang.*; class GFG{ public static void findLongestPalindromicString( String text){ int N = text.length(); if(N == 0) return; // Position count N = 2 * N + 1; // LPS Length Array int []L = new int [N]; L[0] = 0; L[1] = 1; // centerPosition int C = 1; // centerRightPosition int R = 2; // currentRightPosition int i = 0; // currentLeftPosition int iMirror; int expand = -1; int diff = -1; int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; // Uncomment it to print LPS Length array // printf(\"%d %d \", L[0], L[1]); for (i = 2; i < N; i++) { // Get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; // Reset expand - means no // expansion required expand = 0; diff = R - i; // If currentRightPosition i is // within centerRightPosition R if(diff >= 0) { // Case 1 if(L[iMirror] < diff) L[i] = L[iMirror]; // Case 2 else if(L[iMirror] == diff && R == N - 1) L[i] = L[iMirror]; // Case 3 else if(L[iMirror] == diff && R < N - 1) { L[i] = L[iMirror]; // Expansion required expand = 1; } // Case 4 else if(L[iMirror] > diff) { L[i] = diff; // Expansion required expand = 1; } } else { L[i] = 0; // Expansion required expand = 1; } if (expand == 1) { // Attempt to expand palindrome centered // at currentRightPosition i. Here for odd // positions, we compare characters and // if match then increment LPS Length by ONE // If even position, we just increment LPS // by ONE without any character comparison try { while (((i + L[i]) < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text.charAt((i + L[i] + 1) / 2) == text.charAt((i - L[i] - 1) / 2)))) { L[i]++; } } catch (Exception e) { assert true; } } // Track maxLPSLength if(L[i] > maxLPSLength) { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at // currentRightPosition i expand // beyond centerRightPosition R, // adjust centerPosition C based // on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } //Uncomment it to print LPS Length array //System.out.print(\"%d \", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; //System.out.print(\"start: %d end: %d\\n\", // start, end); System.out.print(\"LPS of string is \" + text + \" : \"); for(i = start; i <= end; i++) System.out.print(text.charAt(i)); System.out.println();} // Driver codepublic static void main(String []args){ String text1=\"babcbabcbaccba\"; findLongestPalindromicString(text1); String text2=\"abaaba\"; findLongestPalindromicString(text2); String text3= \"abababa\"; findLongestPalindromicString(text3); String text4=\"abcbabcbabcba\"; findLongestPalindromicString(text4); String text5=\"forgeeksskeegfor\"; findLongestPalindromicString(text5); String text6=\"caba\"; findLongestPalindromicString(text6); String text7=\"abacdfgdcaba\"; findLongestPalindromicString(text7); String text8=\"abacdfgdcabba\"; findLongestPalindromicString(text8); String text9=\"abacdedcaba\"; findLongestPalindromicString(text9);}} // This code is contributed by SoumikMondal", "e": 9597, "s": 5204, "text": null }, { "code": "# Python program to implement Manacher's Algorithm def findLongestPalindromicString(text): N = len(text) if N == 0: return N = 2*N+1 # Position count L = [0] * N L[0] = 0 L[1] = 1 C = 1 # centerPosition R = 2 # centerRightPosition i = 0 # currentRightPosition iMirror = 0 # currentLeftPosition maxLPSLength = 0 maxLPSCenterPosition = 0 start = -1 end = -1 diff = -1 # Uncomment it to print LPS Length array # printf(\"%d %d \", L[0], L[1]); for i in range(2,N): # get currentLeftPosition iMirror for currentRightPosition i iMirror = 2*C-i L[i] = 0 diff = R - i # If currentRightPosition i is within centerRightPosition R if diff > 0: L[i] = min(L[iMirror], diff) # Attempt to expand palindrome centered at currentRightPosition i # Here for odd positions, we compare characters and # if match then increment LPS Length by ONE # If even position, we just increment LPS by ONE without # any character comparison try: while ((i+L[i]) < N and (i-L[i]) > 0) and \\ (((i+L[i]+1) % 2 == 0) or \\ (text[(i+L[i]+1)//2] == text[(i-L[i]-1)//2])): L[i]+=1 except Exception as e: pass if L[i] > maxLPSLength: # Track maxLPSLength maxLPSLength = L[i] maxLPSCenterPosition = i # If palindrome centered at currentRightPosition i # expand beyond centerRightPosition R, # adjust centerPosition C based on expanded palindrome. if i + L[i] > R: C = i R = i + L[i] # Uncomment it to print LPS Length array # printf(\"%d \", L[i]); start = (maxLPSCenterPosition - maxLPSLength) // 2 end = start + maxLPSLength - 1 print (\"LPS of string is \" + text + \" : \",text[start:end+1]) # Driver programtext1 = \"babcbabcbaccba\"findLongestPalindromicString(text1) text2 = \"abaaba\"findLongestPalindromicString(text2) text3 = \"abababa\"findLongestPalindromicString(text3) text4 = \"abcbabcbabcba\"findLongestPalindromicString(text4) text5 = \"forgeeksskeegfor\"findLongestPalindromicString(text5) text6 = \"caba\"findLongestPalindromicString(text6) text7 = \"abacdfgdcaba\"findLongestPalindromicString(text7) text8 = \"abacdfgdcabba\"findLongestPalindromicString(text8) text9 = \"abacdedcaba\"findLongestPalindromicString(text9) # This code is contributed by BHAVYA JAIN", "e": 12095, "s": 9597, "text": null }, { "code": "// A C# program to implement Manacher’s Algorithmusing System;using System.Diagnostics;public class GFG{ public static void findLongestPalindromicString( String text){ int N = text.Length; if(N == 0) return; // Position count N = 2 * N + 1; // LPS Length Array int []L = new int [N]; L[0] = 0; L[1] = 1; // centerPosition int C = 1; // centerRightPosition int R = 2; // currentRightPosition int i = 0; // currentLeftPosition int iMirror; int expand = -1; int diff = -1; int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; // Uncomment it to print LPS Length array // printf(\"%d %d \", L[0], L[1]); for (i = 2; i < N; i++) { // Get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; // Reset expand - means no // expansion required expand = 0; diff = R - i; // If currentRightPosition i is // within centerRightPosition R if(diff >= 0) { // Case 1 if(L[iMirror] < diff) L[i] = L[iMirror]; // Case 2 else if(L[iMirror] == diff && R == N - 1) L[i] = L[iMirror]; // Case 3 else if(L[iMirror] == diff && R < N - 1) { L[i] = L[iMirror]; // Expansion required expand = 1; } // Case 4 else if(L[iMirror] > diff) { L[i] = diff; // Expansion required expand = 1; } } else { L[i] = 0; // Expansion required expand = 1; } if (expand == 1) { // Attempt to expand palindrome centered // at currentRightPosition i. Here for odd // positions, we compare characters and // if match then increment LPS Length by ONE // If even position, we just increment LPS // by ONE without any character comparison try { while (((i + L[i]) < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text[(i + L[i] + 1) / 2] == text[(i - L[i] - 1) / 2]))) { L[i]++; } } catch (Exception) { Debug.Assert(true); } } // Track maxLPSLength if(L[i] > maxLPSLength) { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at // currentRightPosition i expand // beyond centerRightPosition R, // adjust centerPosition C based // on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } //Uncomment it to print LPS Length array //System.out.print(\"%d \", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; //System.out.print(\"start: %d end: %d\\n\", // start, end); Console.Write(\"LPS of string is \" + text + \" : \"); for(i = start; i <= end; i++) Console.Write(text[i]); Console.WriteLine();} // Driver codestatic public void Main (){ String text1 = \"babcbabcbaccba\"; findLongestPalindromicString(text1); String text2 = \"abaaba\"; findLongestPalindromicString(text2); String text3 = \"abababa\"; findLongestPalindromicString(text3); String text4 = \"abcbabcbabcba\"; findLongestPalindromicString(text4); String text5 = \"forgeeksskeegfor\"; findLongestPalindromicString(text5); String text6 = \"caba\"; findLongestPalindromicString(text6); String text7 = \"abacdfgdcaba\"; findLongestPalindromicString(text7); String text8 = \"abacdfgdcabba\"; findLongestPalindromicString(text8); String text9 = \"abacdedcaba\"; findLongestPalindromicString(text9);}} // This code is contributed by Dharanendra L V.", "e": 16492, "s": 12095, "text": null }, { "code": "<script>// A Javascript program to implement Manacher’s Algorithm function findLongestPalindromicString(text){ let N = text.length; if(N == 0) return; // Position count N = 2 * N + 1; // LPS Length Array let L = new Array(N); L[0] = 0; L[1] = 1; // centerPosition let C = 1; // centerRightPosition let R = 2; // currentRightPosition let i = 0; // currentLeftPosition let iMirror; let expand = -1; let diff = -1; let maxLPSLength = 0; let maxLPSCenterPosition = 0; let start = -1; let end = -1; // Uncomment it to print LPS Length array // printf(\"%d %d \", L[0], L[1]); for (i = 2; i < N; i++) { // Get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; // Reset expand - means no // expansion required expand = 0; diff = R - i; // If currentRightPosition i is // within centerRightPosition R if(diff >= 0) { // Case 1 if(L[iMirror] < diff) L[i] = L[iMirror]; // Case 2 else if(L[iMirror] == diff && R == N - 1) L[i] = L[iMirror]; // Case 3 else if(L[iMirror] == diff && R < N - 1) { L[i] = L[iMirror]; // Expansion required expand = 1; } // Case 4 else if(L[iMirror] > diff) { L[i] = diff; // Expansion required expand = 1; } } else { L[i] = 0; // Expansion required expand = 1; } if (expand == 1) { // Attempt to expand palindrome centered // at currentRightPosition i. Here for odd // positions, we compare characters and // if match then increment LPS Length by ONE // If even position, we just increment LPS // by ONE without any character comparison while (((i + L[i]) < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text[Math.floor((i + L[i] + 1) / 2)] == text[Math.floor((i - L[i] - 1) / 2)]))) { L[i]++; } } // Track maxLPSLength if(L[i] > maxLPSLength) { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at // currentRightPosition i expand // beyond centerRightPosition R, // adjust centerPosition C based // on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } //Uncomment it to print LPS Length array //System.out.print(\"%d \", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; //System.out.print(\"start: %d end: %d\\n\", // start, end); document.write(\"LPS of string is \" + text + \" : \"); for(i = start; i <= end; i++) document.write(text[i]); document.write(\"<br>\");} // Driver code let text1=\"babcbabcbaccba\";findLongestPalindromicString(text1); let text2=\"abaaba\";findLongestPalindromicString(text2); let text3= \"abababa\";findLongestPalindromicString(text3); let text4=\"abcbabcbabcba\";findLongestPalindromicString(text4); let text5=\"forgeeksskeegfor\";findLongestPalindromicString(text5); let text6=\"caba\";findLongestPalindromicString(text6); let text7=\"abacdfgdcaba\";findLongestPalindromicString(text7); let text8=\"abacdfgdcabba\";findLongestPalindromicString(text8); let text9=\"abacdedcaba\";findLongestPalindromicString(text9); // This code is contributed by unknown2108</script>", "e": 20647, "s": 16492, "text": null }, { "code": null, "e": 20998, "s": 20647, "text": "LPS of string is babcbabcbaccba : abcbabcba\nLPS of string is abaaba : abaaba\nLPS of string is abababa : abababa\nLPS of string is abcbabcbabcba : abcbabcbabcba\nLPS of string is forgeeksskeegfor : geeksskeeg\nLPS of string is caba : aba\nLPS of string is abacdfgdcaba : aba\nLPS of string is abacdfgdcabba : abba\nLPS of string is abacdedcaba : abacdedcaba" }, { "code": null, "e": 21170, "s": 20998, "text": "This is the implementation based on the four cases discussed in Part 2. In Part 4, we have discussed a different way to look at these four cases and few other approaches. " }, { "code": null, "e": 21188, "s": 21170, "text": "DmitriyPhilimonov" }, { "code": null, "e": 21201, "s": 21188, "text": "SoumikMondal" }, { "code": null, "e": 21217, "s": 21201, "text": "dharanendralv23" }, { "code": null, "e": 21229, "s": 21217, "text": "unknown2108" }, { "code": null, "e": 21241, "s": 21229, "text": "kashishsoda" }, { "code": null, "e": 21257, "s": 21241, "text": "amartyaghoshgfg" }, { "code": null, "e": 21274, "s": 21257, "text": "hardikkoriintern" }, { "code": null, "e": 21285, "s": 21274, "text": "palindrome" }, { "code": null, "e": 21303, "s": 21285, "text": "Pattern Searching" }, { "code": null, "e": 21311, "s": 21303, "text": "Strings" }, { "code": null, "e": 21319, "s": 21311, "text": "Strings" }, { "code": null, "e": 21330, "s": 21319, "text": "palindrome" }, { "code": null, "e": 21348, "s": 21330, "text": "Pattern Searching" } ]
Counting number of unique values in a Python list
29 Aug, 2020 Let us see how to count the number of unique values in a Python list.Examples : Input : 10 20 10 30 40 40 Output : 2 Explanation : Only 2 elements, 20 and 30 are unique in the list. Input : 'geeks' 'for' 'geeks' Output : 1 Approach 1 : Traversing the list and counting the frequrency of each element using dictionary, finally counting the elements for which the frequency is 1. # function to count the unique elementsdef count_unique(my_list): # variable to store the unique count count = 0 # creating dictionary to count frequency freq = {} # traversing the list for x in my_list: if (x in freq): freq[x] += 1 else: freq[x] = 1 # traversing the dictionary for key, value in freq.items(): if value == 1: count += 1 # displaying the count of unique elements print(count) # driver functionif __name__ == "__main__": my_list = [10, 20, 10, 30, 40, 40] count_unique(my_list) my_list = ['geeks', 'for', 'geeks'] count_unique(my_list) Output : 2 1 Time complexity : O(N)Space complexity : O(N) Approach 2 : Here we will be using the get() method of the dictionary class to count the frequency. This makes the program shorter and demonstrates how get() method is useful instead of if...else. # function to count the unique elementsdef count_unique(my_list): # variable to store the unique count count = 0 # creating dictionary to count frequency freq = {} # traversing the list for x in my_list: freq[x] = freq.get(x, 0) + 1 # traversing the dictionary for key, value in freq.items(): if value == 1: count += 1 # displaying the count of unique elements print(count) # driver functionif __name__ == "__main__": my_list = [10, 20, 10, 30, 40, 40] count_unique(my_list) my_list = ['geeks', 'for', 'geeks'] count_unique(my_list) Output : 2 1 Time complexity : O(N)Space complexity : O(N) Approach 3 : Here we will be using the count() method of the list class to count the frequency. # function to count the unique elementsdef count_unique(my_list): # variable to store the unique count count = 0 # creating dictionary to count frequency freq = {} # traversing the list for x in my_list: freq[x] = my_list.count(x) # traversing the dictionary for key, value in freq.items(): if value == 1: count += 1 # displaying the count of unique elements print(count) # driver functionif __name__ == "__main__": my_list = [10, 20, 10, 30, 40, 40] count_unique(my_list) my_list = ['geeks', 'for', 'geeks'] count_unique(my_list) Output : 2 1 Time complexity : O(N)Space complexity : O(N) Approach 4 : Here we will be using the Counter() method of the collections module to count the frequency. # importing the moduleimport collections # function to count the unique elementsdef count_unique(my_list): # variable to store the unique count count = 0 # creating dictionary to count frequency freq = collections.Counter(my_list) # traversing the dictionary for key, value in freq.items(): if value == 1: count += 1 # displaying the count of unique elements print(count) # driver functionif __name__ == "__main__": my_list = [10, 20, 10, 30, 40, 40] count_unique(my_list) my_list = ['geeks', 'for', 'geeks'] count_unique(my_list) Output : 2 1 Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 108, "s": 28, "text": "Let us see how to count the number of unique values in a Python list.Examples :" }, { "code": null, "e": 253, "s": 108, "text": "Input : 10 20 10 30 40 40\nOutput : 2\nExplanation : Only 2 elements, 20 and 30 are unique in the list.\n\nInput : 'geeks' 'for' 'geeks'\nOutput : 1\n" }, { "code": null, "e": 408, "s": 253, "text": "Approach 1 : Traversing the list and counting the frequrency of each element using dictionary, finally counting the elements for which the frequency is 1." }, { "code": "# function to count the unique elementsdef count_unique(my_list): # variable to store the unique count count = 0 # creating dictionary to count frequency freq = {} # traversing the list for x in my_list: if (x in freq): freq[x] += 1 else: freq[x] = 1 # traversing the dictionary for key, value in freq.items(): if value == 1: count += 1 # displaying the count of unique elements print(count) # driver functionif __name__ == \"__main__\": my_list = [10, 20, 10, 30, 40, 40] count_unique(my_list) my_list = ['geeks', 'for', 'geeks'] count_unique(my_list)", "e": 1070, "s": 408, "text": null }, { "code": null, "e": 1079, "s": 1070, "text": "Output :" }, { "code": null, "e": 1084, "s": 1079, "text": "2\n1\n" }, { "code": null, "e": 1130, "s": 1084, "text": "Time complexity : O(N)Space complexity : O(N)" }, { "code": null, "e": 1327, "s": 1130, "text": "Approach 2 : Here we will be using the get() method of the dictionary class to count the frequency. This makes the program shorter and demonstrates how get() method is useful instead of if...else." }, { "code": "# function to count the unique elementsdef count_unique(my_list): # variable to store the unique count count = 0 # creating dictionary to count frequency freq = {} # traversing the list for x in my_list: freq[x] = freq.get(x, 0) + 1 # traversing the dictionary for key, value in freq.items(): if value == 1: count += 1 # displaying the count of unique elements print(count) # driver functionif __name__ == \"__main__\": my_list = [10, 20, 10, 30, 40, 40] count_unique(my_list) my_list = ['geeks', 'for', 'geeks'] count_unique(my_list)", "e": 1942, "s": 1327, "text": null }, { "code": null, "e": 1951, "s": 1942, "text": "Output :" }, { "code": null, "e": 1956, "s": 1951, "text": "2\n1\n" }, { "code": null, "e": 2002, "s": 1956, "text": "Time complexity : O(N)Space complexity : O(N)" }, { "code": null, "e": 2098, "s": 2002, "text": "Approach 3 : Here we will be using the count() method of the list class to count the frequency." }, { "code": "# function to count the unique elementsdef count_unique(my_list): # variable to store the unique count count = 0 # creating dictionary to count frequency freq = {} # traversing the list for x in my_list: freq[x] = my_list.count(x) # traversing the dictionary for key, value in freq.items(): if value == 1: count += 1 # displaying the count of unique elements print(count) # driver functionif __name__ == \"__main__\": my_list = [10, 20, 10, 30, 40, 40] count_unique(my_list) my_list = ['geeks', 'for', 'geeks'] count_unique(my_list)", "e": 2711, "s": 2098, "text": null }, { "code": null, "e": 2720, "s": 2711, "text": "Output :" }, { "code": null, "e": 2725, "s": 2720, "text": "2\n1\n" }, { "code": null, "e": 2771, "s": 2725, "text": "Time complexity : O(N)Space complexity : O(N)" }, { "code": null, "e": 2877, "s": 2771, "text": "Approach 4 : Here we will be using the Counter() method of the collections module to count the frequency." }, { "code": "# importing the moduleimport collections # function to count the unique elementsdef count_unique(my_list): # variable to store the unique count count = 0 # creating dictionary to count frequency freq = collections.Counter(my_list) # traversing the dictionary for key, value in freq.items(): if value == 1: count += 1 # displaying the count of unique elements print(count) # driver functionif __name__ == \"__main__\": my_list = [10, 20, 10, 30, 40, 40] count_unique(my_list) my_list = ['geeks', 'for', 'geeks'] count_unique(my_list)", "e": 3476, "s": 2877, "text": null }, { "code": null, "e": 3485, "s": 3476, "text": "Output :" }, { "code": null, "e": 3490, "s": 3485, "text": "2\n1\n" }, { "code": null, "e": 3511, "s": 3490, "text": "Python list-programs" }, { "code": null, "e": 3523, "s": 3511, "text": "python-list" }, { "code": null, "e": 3530, "s": 3523, "text": "Python" }, { "code": null, "e": 3546, "s": 3530, "text": "Python Programs" }, { "code": null, "e": 3558, "s": 3546, "text": "python-list" }, { "code": null, "e": 3656, "s": 3558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3688, "s": 3656, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3715, "s": 3688, "text": "Python Classes and Objects" }, { "code": null, "e": 3736, "s": 3715, "text": "Python OOPs Concepts" }, { "code": null, "e": 3759, "s": 3736, "text": "Introduction To PYTHON" }, { "code": null, "e": 3790, "s": 3759, "text": "Python | os.path.join() method" }, { "code": null, "e": 3812, "s": 3790, "text": "Defaultdict in Python" }, { "code": null, "e": 3851, "s": 3812, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3889, "s": 3851, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3926, "s": 3889, "text": "Python Program for Fibonacci numbers" } ]