title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
QTP - Data Table Object Methods
Consider the following DataTable − 'Accessing Datatable to get Row Count and Column Count rowcount = DataTable.GetSheet("Global").GetRowCount msgbox rowcount ' Displays 4 colcount = DataTable.GetSheet("Global").GetParameterCount msgbox colcount ' Displays 3 DataTable.SetCurrentRow(2) val_rate = DataTable.Value("Rate","Global") print val_rate ' Displays 7% val_ppl = DataTable.Value("Principal","Global") print val_ppl ' Displays 2556 val_Time = DataTable.Value("Time","Global") print val_Time ' Displays 5 108 Lectures 8 hours Pavan Lalwani Print Add Notes Bookmark this page
[ { "code": null, "e": 2157, "s": 2122, "text": "Consider the following DataTable −" }, { "code": null, "e": 2654, "s": 2157, "text": "'Accessing Datatable to get Row Count and Column Count\nrowcount = DataTable.GetSheet(\"Global\").GetRowCount\nmsgbox rowcount ' Displays 4\n \ncolcount = DataTable.GetSheet(\"Global\").GetParameterCount\nmsgbox colcount\t\t ' Displays 3\n \nDataTable.SetCurrentRow(2) \nval_rate = DataTable.Value(\"Rate\",\"Global\")\nprint val_rate ' Displays 7%\n \nval_ppl = DataTable.Value(\"Principal\",\"Global\")\nprint val_ppl\t ' Displays 2556\n \nval_Time = DataTable.Value(\"Time\",\"Global\")\nprint val_Time\t ' Displays 5" }, { "code": null, "e": 2688, "s": 2654, "text": "\n 108 Lectures \n 8 hours \n" }, { "code": null, "e": 2703, "s": 2688, "text": " Pavan Lalwani" }, { "code": null, "e": 2710, "s": 2703, "text": " Print" }, { "code": null, "e": 2721, "s": 2710, "text": " Add Notes" } ]
How to implement reactive streams using Flow API in Java 9?
Flow API is official support for reactive streams specification since Java 9. It is a combination of both Iterator and Observer patterns. The Flow API is an interoperation specification and not an end-user API like RxJava. Flow API consists of four basic interfaces: Subscriber: The Subscriber subscribes to Publisher for callbacks. Publisher: The Publisher publishes the stream of data items to the registered subscribers. Subscription: The link between publisher and subscriber. Processor: The processor sits between Publisher and Subscriber, and transforms one stream to another. In the below example, we have created a basic subscriber that asks for one data object, prints it and asks for one more. We can use a publisher implementation provided by Java (SubmissionPublisher) to complete our session. import java.util.concurrent.Flow; import java.util.List; import java.util.concurrent.SubmissionPublisher; class MySubscriber<T>implements Flow.Subscriber<T> { private Flow.Subscription subscription; @Override public void onSubscribe(Flow.Subscription subscription) { this.subscription = subscription; this.subscription.request(1); } @Override public void onNext(T item) { System.out.println(item); subscription.request(1); } @Override public void onError(Throwable throwable) { throwable.printStackTrace(); } @Override public void onComplete() { System.out.println("Done"); } } // main class public class FlowTest { public static void main(String args[]) { List<String> items = List.of("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); SubmissionPublisher<String> publisher = new SubmissionPublisher<>(); publisher.subscribe(new MySubscriber<>()); items.forEach(s -> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } publisher.submit(s); }); publisher.close(); } } 1 2 3 4 5 6 7 8 9 10 Done
[ { "code": null, "e": 1285, "s": 1062, "text": "Flow API is official support for reactive streams specification since Java 9. It is a combination of both Iterator and Observer patterns. The Flow API is an interoperation specification and not an end-user API like RxJava." }, { "code": null, "e": 1329, "s": 1285, "text": "Flow API consists of four basic interfaces:" }, { "code": null, "e": 1395, "s": 1329, "text": "Subscriber: The Subscriber subscribes to Publisher for callbacks." }, { "code": null, "e": 1486, "s": 1395, "text": "Publisher: The Publisher publishes the stream of data items to the registered subscribers." }, { "code": null, "e": 1543, "s": 1486, "text": "Subscription: The link between publisher and subscriber." }, { "code": null, "e": 1645, "s": 1543, "text": "Processor: The processor sits between Publisher and Subscriber, and transforms one stream to another." }, { "code": null, "e": 1868, "s": 1645, "text": "In the below example, we have created a basic subscriber that asks for one data object, prints it and asks for one more. We can use a publisher implementation provided by Java (SubmissionPublisher) to complete our session." }, { "code": null, "e": 3050, "s": 1868, "text": "import java.util.concurrent.Flow;\nimport java.util.List;\nimport java.util.concurrent.SubmissionPublisher;\n\nclass MySubscriber<T>implements Flow.Subscriber<T> {\n private Flow.Subscription subscription;\n @Override\n public void onSubscribe(Flow.Subscription subscription) {\n this.subscription = subscription;\n this.subscription.request(1);\n }\n @Override\n public void onNext(T item) {\n System.out.println(item);\n subscription.request(1);\n }\n @Override\n public void onError(Throwable throwable) {\n throwable.printStackTrace();\n }\n @Override\n public void onComplete() {\n System.out.println(\"Done\");\n }\n}\n\n// main class\npublic class FlowTest {\n public static void main(String args[]) {\n List<String> items = List.of(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\");\n SubmissionPublisher<String> publisher = new SubmissionPublisher<>();\n publisher.subscribe(new MySubscriber<>());\n items.forEach(s -> {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n publisher.submit(s);\n });\n publisher.close();\n }\n}" }, { "code": null, "e": 3076, "s": 3050, "text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\nDone" } ]
Agile Testing
A software testing practice that follows the principles of agile software development is called Agile Testing. Agile is an iterative development methodology, where requirements evolve through collaboration between the customer and self-organizing teams and agile aligns development with customer needs. Agile Testing Saves Time and Money Agile Testing Saves Time and Money Less Documentation Less Documentation Regular feedback from the end user Regular feedback from the end user Daily meetings can help to determine the issues well in advance Daily meetings can help to determine the issues well in advance Testing is NOT a Phase: Agile team tests continuously and continuous testing is the only way to ensure continuous progress. Testing is NOT a Phase: Agile team tests continuously and continuous testing is the only way to ensure continuous progress. Testing Moves the project Forward: When following conventional methods, testing is considered as quality gate but agile testing provide feedback on an ongoing basis and the product meets the business demands. Testing Moves the project Forward: When following conventional methods, testing is considered as quality gate but agile testing provide feedback on an ongoing basis and the product meets the business demands. Everyone Tests: In conventional SDLC, only test team tests while in agile including developers and BA's test the application. Everyone Tests: In conventional SDLC, only test team tests while in agile including developers and BA's test the application. Shortening Feedback Response Time: In conventional SDLC, only during the acceptance testing, the Business team will get to know the product development, while in agile for each and every iteration, they are involved and continuous feedback shortens the feedback response time and cost involved in fixing is also less. Shortening Feedback Response Time: In conventional SDLC, only during the acceptance testing, the Business team will get to know the product development, while in agile for each and every iteration, they are involved and continuous feedback shortens the feedback response time and cost involved in fixing is also less. Clean Code: Raised defects are fixed within the same iteration and thereby keeping the code clean. Clean Code: Raised defects are fixed within the same iteration and thereby keeping the code clean. Reduce Test Documentation: Instead of very lengthy documentation, agile testers use reusable checklist, focus on the essence of the test rather than the incidental details. Reduce Test Documentation: Instead of very lengthy documentation, agile testers use reusable checklist, focus on the essence of the test rather than the incidental details. Test Driven: In conventional methods, testing is performed after implementation while in agile testing, testing is done while implementation. Test Driven: In conventional methods, testing is performed after implementation while in agile testing, testing is done while implementation. 1. Automated Unit Tests 2. Test Driven Development 3. Automated Regression Tests 4. Exploratory Testing 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": 6048, "s": 5745, "text": "A software testing practice that follows the principles of agile software development is called Agile Testing. Agile is an iterative development methodology, where requirements evolve through collaboration between the customer and self-organizing teams and agile aligns development with customer needs." }, { "code": null, "e": 6084, "s": 6048, "text": "Agile Testing Saves Time and Money " }, { "code": null, "e": 6120, "s": 6084, "text": "Agile Testing Saves Time and Money " }, { "code": null, "e": 6139, "s": 6120, "text": "Less Documentation" }, { "code": null, "e": 6158, "s": 6139, "text": "Less Documentation" }, { "code": null, "e": 6193, "s": 6158, "text": "Regular feedback from the end user" }, { "code": null, "e": 6228, "s": 6193, "text": "Regular feedback from the end user" }, { "code": null, "e": 6292, "s": 6228, "text": "Daily meetings can help to determine the issues well in advance" }, { "code": null, "e": 6356, "s": 6292, "text": "Daily meetings can help to determine the issues well in advance" }, { "code": null, "e": 6480, "s": 6356, "text": "Testing is NOT a Phase: Agile team tests continuously and continuous testing is the only way to ensure continuous progress." }, { "code": null, "e": 6604, "s": 6480, "text": "Testing is NOT a Phase: Agile team tests continuously and continuous testing is the only way to ensure continuous progress." }, { "code": null, "e": 6813, "s": 6604, "text": "Testing Moves the project Forward: When following conventional methods, testing is considered as quality gate but agile testing provide feedback on an ongoing basis and the product meets the business demands." }, { "code": null, "e": 7022, "s": 6813, "text": "Testing Moves the project Forward: When following conventional methods, testing is considered as quality gate but agile testing provide feedback on an ongoing basis and the product meets the business demands." }, { "code": null, "e": 7148, "s": 7022, "text": "Everyone Tests: In conventional SDLC, only test team tests while in agile including developers and BA's test the application." }, { "code": null, "e": 7274, "s": 7148, "text": "Everyone Tests: In conventional SDLC, only test team tests while in agile including developers and BA's test the application." }, { "code": null, "e": 7592, "s": 7274, "text": "Shortening Feedback Response Time: In conventional SDLC, only during the acceptance testing, the Business team will get to know the product development, while in agile for each and every iteration, they are involved and continuous feedback shortens the feedback response time and cost involved in fixing is also less." }, { "code": null, "e": 7910, "s": 7592, "text": "Shortening Feedback Response Time: In conventional SDLC, only during the acceptance testing, the Business team will get to know the product development, while in agile for each and every iteration, they are involved and continuous feedback shortens the feedback response time and cost involved in fixing is also less." }, { "code": null, "e": 8009, "s": 7910, "text": "Clean Code: Raised defects are fixed within the same iteration and thereby keeping the code clean." }, { "code": null, "e": 8108, "s": 8009, "text": "Clean Code: Raised defects are fixed within the same iteration and thereby keeping the code clean." }, { "code": null, "e": 8281, "s": 8108, "text": "Reduce Test Documentation: Instead of very lengthy documentation, agile testers use reusable checklist, focus on the essence of the test rather than the incidental details." }, { "code": null, "e": 8454, "s": 8281, "text": "Reduce Test Documentation: Instead of very lengthy documentation, agile testers use reusable checklist, focus on the essence of the test rather than the incidental details." }, { "code": null, "e": 8596, "s": 8454, "text": "Test Driven: In conventional methods, testing is performed after implementation while in agile testing, testing is done while implementation." }, { "code": null, "e": 8738, "s": 8596, "text": "Test Driven: In conventional methods, testing is performed after implementation while in agile testing, testing is done while implementation." }, { "code": null, "e": 8842, "s": 8738, "text": "1. Automated Unit Tests\n2. Test Driven Development\n3. Automated Regression Tests\n4. Exploratory Testing" }, { "code": null, "e": 8877, "s": 8842, "text": "\n 80 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8896, "s": 8877, "text": " Arnab Chakraborty" }, { "code": null, "e": 8929, "s": 8896, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 8942, "s": 8929, "text": " Zach Miller" }, { "code": null, "e": 8977, "s": 8942, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8990, "s": 8977, "text": " Zach Miller" }, { "code": null, "e": 9023, "s": 8990, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 9034, "s": 9023, "text": " John Shea" }, { "code": null, "e": 9068, "s": 9034, "text": "\n 99 Lectures \n 10 hours \n" }, { "code": null, "e": 9079, "s": 9068, "text": " Daniel IT" }, { "code": null, "e": 9112, "s": 9079, "text": "\n 62 Lectures \n 5 hours \n" }, { "code": null, "e": 9129, "s": 9112, "text": " GlobalETraining" }, { "code": null, "e": 9136, "s": 9129, "text": " Print" }, { "code": null, "e": 9147, "s": 9136, "text": " Add Notes" } ]
How to print the largest value from Python dictionary?
Python's built-in dictionary class has values() method which returns list of value component from each key-value pair. Using built-in function max() the largest value in the dictionary can be obtained >>> dct={1:45,2:76,3:12,4:55,5:33} >>> vlist=dct.values() >>> vlist dict_values([45, 76, 12, 55, 33]) >>> max(vlist) 76
[ { "code": null, "e": 1263, "s": 1062, "text": "Python's built-in dictionary class has values() method which returns list of value component from each key-value pair. Using built-in function max() the largest value in the dictionary can be obtained" }, { "code": null, "e": 1383, "s": 1263, "text": ">>> dct={1:45,2:76,3:12,4:55,5:33}\n>>> vlist=dct.values()\n>>> vlist\ndict_values([45, 76, 12, 55, 33])\n>>> max(vlist)\n76" } ]
Naive Bayes Classifier in R Programming
13 Jul, 2021 Naive Bayes is a Supervised Non-linear classification algorithm in R Programming. Naive Bayes classifiers are a family of simple probabilistic classifiers based on applying Baye’s theorem with strong(Naive) independence assumptions between the features or variables. The Naive Bayes algorithm is called “Naive” because it makes the assumption that the occurrence of a certain feature is independent of the occurrence of other features. Naive Bayes algorithm is based on Bayes theorem. Bayes theorem gives the conditional probability of an event A given another event B has occurred. where, P(A|B) = Conditional probability of A given B. P(B|A) = Conditional probability of B given A. P(A) = Probability of event A. P(B) = Probability of event B. For many predictors, we can formulate the posterior probability as follows: P(A|B) = P(B1|A) * P(B2|A) * P(B3|A) * P(B4|A) ... Example Consider a sample space: {HH, HT, TH, TT} where, H: Head T: Tail P(Second coin being head given = P(A|B) first coin is tail) = P(A|B) = [P(B|A) * P(A)] / P(B) = [P(First coin is tail given second coin is head) * P(Second coin being Head)] / P(first coin being tail) = [(1/2) * (1/2)] / (1/2) = (1/2) = 0.5 Iris dataset consists of 50 samples from each of 3 species of Iris(Iris setosa, Iris virginica, Iris versicolor) and a multivariate dataset introduced by British statistician and biologist Ronald Fisher in his 1936 paper The use of multiple measurements in taxonomic problems. Four features were measured from each sample i.e length and width of the sepals and petals and based on the combination of these four features, Fisher developed a linear discriminant model to distinguish the species from each other. Python3 # Loading datadata(iris) # Structurestr(iris) Using Naive Bayes algorithm on the dataset which includes 11 persons and 6 variables or attributes Python3 # Installing Packagesinstall.packages("e1071")install.packages("caTools")install.packages("caret") # Loading packagelibrary(e1071)library(caTools)library(caret) # Splitting data into train# and test datasplit <- sample.split(iris, SplitRatio = 0.7)train_cl <- subset(iris, split == "TRUE")test_cl <- subset(iris, split == "FALSE") # Feature Scalingtrain_scale <- scale(train_cl[, 1:4])test_scale <- scale(test_cl[, 1:4]) # Fitting Naive Bayes Model# to training datasetset.seed(120) # Setting Seedclassifier_cl <- naiveBayes(Species ~ ., data = train_cl)classifier_cl # Predicting on test data'y_pred <- predict(classifier_cl, newdata = test_cl) # Confusion Matrixcm <- table(test_cl$Species, y_pred)cm # Model EvaluationconfusionMatrix(cm) Model classifier_cl: The Conditional probability for each feature or variable is created by model separately. The apriori probabilities are also calculated which indicates the distribution of our data. Confusion Matrix: So, 20 Setosa are correctly classified as Setosa. Out of 16 Versicolor, 15 Versicolor are correctly classified as Versicolor, and 1 are classified as virginica. Out of 24 virginica, 19 virginica are correctly classified as virginica and 5 are classified as Versicolor. Model Evaluation: The model achieved 90% accuracy with a p-value of less than 1. With Sensitivity, Specificity, and Balanced accuracy, the model build is good. So, Naive Bayes is widely used in Sentiment analysis, document categorization, Email spam filtering etc in industry. surinderdawra388 R-Mathematics R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jul, 2021" }, { "code": null, "e": 465, "s": 28, "text": "Naive Bayes is a Supervised Non-linear classification algorithm in R Programming. Naive Bayes classifiers are a family of simple probabilistic classifiers based on applying Baye’s theorem with strong(Naive) independence assumptions between the features or variables. The Naive Bayes algorithm is called “Naive” because it makes the assumption that the occurrence of a certain feature is independent of the occurrence of other features. " }, { "code": null, "e": 613, "s": 465, "text": "Naive Bayes algorithm is based on Bayes theorem. Bayes theorem gives the conditional probability of an event A given another event B has occurred. " }, { "code": null, "e": 778, "s": 615, "text": "where, P(A|B) = Conditional probability of A given B. P(B|A) = Conditional probability of B given A. P(A) = Probability of event A. P(B) = Probability of event B." }, { "code": null, "e": 855, "s": 778, "text": "For many predictors, we can formulate the posterior probability as follows: " }, { "code": null, "e": 906, "s": 855, "text": "P(A|B) = P(B1|A) * P(B2|A) * P(B3|A) * P(B4|A) ..." }, { "code": null, "e": 916, "s": 906, "text": "Example " }, { "code": null, "e": 1241, "s": 916, "text": "Consider a sample space:\n {HH, HT, TH, TT}\nwhere,\nH: Head\nT: Tail\n\nP(Second coin being head given = P(A|B)\nfirst coin is tail) = P(A|B) \n= [P(B|A) * P(A)] / P(B)\n= [P(First coin is tail given second coin is head) * \n P(Second coin being Head)] / P(first coin being tail)\n= [(1/2) * (1/2)] / (1/2)\n= (1/2) \n= 0.5" }, { "code": null, "e": 1755, "s": 1243, "text": "Iris dataset consists of 50 samples from each of 3 species of Iris(Iris setosa, Iris virginica, Iris versicolor) and a multivariate dataset introduced by British statistician and biologist Ronald Fisher in his 1936 paper The use of multiple measurements in taxonomic problems. Four features were measured from each sample i.e length and width of the sepals and petals and based on the combination of these four features, Fisher developed a linear discriminant model to distinguish the species from each other. " }, { "code": null, "e": 1763, "s": 1755, "text": "Python3" }, { "code": "# Loading datadata(iris) # Structurestr(iris)", "e": 1810, "s": 1763, "text": null }, { "code": null, "e": 1910, "s": 1810, "text": "Using Naive Bayes algorithm on the dataset which includes 11 persons and 6 variables or attributes " }, { "code": null, "e": 1918, "s": 1910, "text": "Python3" }, { "code": "# Installing Packagesinstall.packages(\"e1071\")install.packages(\"caTools\")install.packages(\"caret\") # Loading packagelibrary(e1071)library(caTools)library(caret) # Splitting data into train# and test datasplit <- sample.split(iris, SplitRatio = 0.7)train_cl <- subset(iris, split == \"TRUE\")test_cl <- subset(iris, split == \"FALSE\") # Feature Scalingtrain_scale <- scale(train_cl[, 1:4])test_scale <- scale(test_cl[, 1:4]) # Fitting Naive Bayes Model# to training datasetset.seed(120) # Setting Seedclassifier_cl <- naiveBayes(Species ~ ., data = train_cl)classifier_cl # Predicting on test data'y_pred <- predict(classifier_cl, newdata = test_cl) # Confusion Matrixcm <- table(test_cl$Species, y_pred)cm # Model EvaluationconfusionMatrix(cm)", "e": 2660, "s": 1918, "text": null }, { "code": null, "e": 2682, "s": 2660, "text": "Model classifier_cl: " }, { "code": null, "e": 2863, "s": 2682, "text": "The Conditional probability for each feature or variable is created by model separately. The apriori probabilities are also calculated which indicates the distribution of our data." }, { "code": null, "e": 2882, "s": 2863, "text": "Confusion Matrix: " }, { "code": null, "e": 3151, "s": 2882, "text": "So, 20 Setosa are correctly classified as Setosa. Out of 16 Versicolor, 15 Versicolor are correctly classified as Versicolor, and 1 are classified as virginica. Out of 24 virginica, 19 virginica are correctly classified as virginica and 5 are classified as Versicolor." }, { "code": null, "e": 3171, "s": 3151, "text": "Model Evaluation: " }, { "code": null, "e": 3313, "s": 3171, "text": "The model achieved 90% accuracy with a p-value of less than 1. With Sensitivity, Specificity, and Balanced accuracy, the model build is good." }, { "code": null, "e": 3431, "s": 3313, "text": "So, Naive Bayes is widely used in Sentiment analysis, document categorization, Email spam filtering etc in industry. " }, { "code": null, "e": 3448, "s": 3431, "text": "surinderdawra388" }, { "code": null, "e": 3462, "s": 3448, "text": "R-Mathematics" }, { "code": null, "e": 3475, "s": 3462, "text": "R-Statistics" }, { "code": null, "e": 3486, "s": 3475, "text": "R Language" } ]
Implementation of lower_bound() and upper_bound() in Vector of Pairs in C++
27 May, 2022 In this article we will discuss the implementation of the lower_bound() and upper_bound() in vector of pairs. lower_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than or equals to the given value “val”. But in Vector of Pairs lower_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than or equals x and second value is greater than equals to y. If the above-mentioned criteria are not met, then it returns an iterator to the index which out of the vectors of pairs. upper_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than the given value “val”. But in Vector of Pairs upper_bound() for pair(x, y) will return an iterator pointing to the position of the pair whosefirst value is equal to x and second value is greater than y.orWhose first value is greater than x. first value is equal to x and second value is greater than y.or Whose first value is greater than x. Below is the program to demonstrate lower_bound() and upper_bound() in vector of pairs:Program 1: CPP // C++ program to demonstrate lower_bound()// and upper_bound() in Vectors of Pairs #include <bits/stdc++.h>using namespace std; // Function to implement lower_bound()void findLowerBound(vector<pair<int, int> >& arr, pair<int, int>& p){ // Given iterator points to the // lower_bound() of given pair auto low = lower_bound(arr.begin(), arr.end(), p); cout << "lower_bound() for {2, 5}" << " is at index: " << low - arr.begin() << endl;} // Function to implement upper_bound()void findUpperBound(vector<pair<int, int> >& arr, pair<int, int>& p){ // Given iterator points to the // upper_bound() of given pair auto up = upper_bound(arr.begin(), arr.end(), p); cout << "upper_bound() for {2, 5}" << " is at index: " << up - arr.begin() << endl;} // Driver Codeint main(){ // Given sorted vector of Pairs vector<pair<int, int> > arr; arr = { { 1, 3 }, { 1, 7 }, { 2, 4 }, { 2, 5 }, { 3, 8 }, { 8, 6 } }; // Given pair {2, 5} pair<int, int> p = { 2, 5 }; // Function Call to find lower_bound // of pair p in arr findLowerBound(arr, p); // Function Call to find upper_bound // of pair p in arr findUpperBound(arr, p); return 0;} lower_bound() for {2, 5} is at index: 3 upper_bound() for {2, 5} is at index: 4 ShubhamDamkondwar bhuwanesh cpp-pair cpp-vector C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n27 May, 2022" }, { "code": null, "e": 164, "s": 53, "text": "In this article we will discuss the implementation of the lower_bound() and upper_bound() in vector of pairs. " }, { "code": null, "e": 654, "s": 164, "text": "lower_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than or equals to the given value “val”. But in Vector of Pairs lower_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than or equals x and second value is greater than equals to y. If the above-mentioned criteria are not met, then it returns an iterator to the index which out of the vectors of pairs. " }, { "code": null, "e": 1022, "s": 654, "text": "upper_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than the given value “val”. But in Vector of Pairs upper_bound() for pair(x, y) will return an iterator pointing to the position of the pair whosefirst value is equal to x and second value is greater than y.orWhose first value is greater than x. " }, { "code": null, "e": 1086, "s": 1022, "text": "first value is equal to x and second value is greater than y.or" }, { "code": null, "e": 1124, "s": 1086, "text": "Whose first value is greater than x. " }, { "code": null, "e": 1224, "s": 1124, "text": "Below is the program to demonstrate lower_bound() and upper_bound() in vector of pairs:Program 1: " }, { "code": null, "e": 1228, "s": 1224, "text": "CPP" }, { "code": "// C++ program to demonstrate lower_bound()// and upper_bound() in Vectors of Pairs #include <bits/stdc++.h>using namespace std; // Function to implement lower_bound()void findLowerBound(vector<pair<int, int> >& arr, pair<int, int>& p){ // Given iterator points to the // lower_bound() of given pair auto low = lower_bound(arr.begin(), arr.end(), p); cout << \"lower_bound() for {2, 5}\" << \" is at index: \" << low - arr.begin() << endl;} // Function to implement upper_bound()void findUpperBound(vector<pair<int, int> >& arr, pair<int, int>& p){ // Given iterator points to the // upper_bound() of given pair auto up = upper_bound(arr.begin(), arr.end(), p); cout << \"upper_bound() for {2, 5}\" << \" is at index: \" << up - arr.begin() << endl;} // Driver Codeint main(){ // Given sorted vector of Pairs vector<pair<int, int> > arr; arr = { { 1, 3 }, { 1, 7 }, { 2, 4 }, { 2, 5 }, { 3, 8 }, { 8, 6 } }; // Given pair {2, 5} pair<int, int> p = { 2, 5 }; // Function Call to find lower_bound // of pair p in arr findLowerBound(arr, p); // Function Call to find upper_bound // of pair p in arr findUpperBound(arr, p); return 0;}", "e": 2482, "s": 1228, "text": null }, { "code": null, "e": 2562, "s": 2482, "text": "lower_bound() for {2, 5} is at index: 3\nupper_bound() for {2, 5} is at index: 4" }, { "code": null, "e": 2580, "s": 2562, "text": "ShubhamDamkondwar" }, { "code": null, "e": 2590, "s": 2580, "text": "bhuwanesh" }, { "code": null, "e": 2599, "s": 2590, "text": "cpp-pair" }, { "code": null, "e": 2610, "s": 2599, "text": "cpp-vector" }, { "code": null, "e": 2614, "s": 2610, "text": "C++" }, { "code": null, "e": 2618, "s": 2614, "text": "CPP" } ]
Split large Pandas Dataframe into list of smaller Dataframes
05 Sep, 2020 In this article, we will learn about the splitting of large dataframe into list of smaller dataframes. This can be done mainly in two different ways : By splitting each rowUsing the concept of groupby By splitting each row Using the concept of groupby Here we use a small dataframe to understand the concept easily and this can also be implemented in an easy way. The Dataframe consists of student id, name, marks, and grades. Let’s create the dataframe. Python3 # importing packagesimport pandas as pd # dictionary of datadct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash'}, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'} } # create dataframedf = pd.DataFrame(dct) # view dataframedf Output: Below is the implementation of the above concepts with some examples : Example 1: By splitting each row Here, we use the loop of iteration for each row. Every row is accessed by using DataFrame.loc[] and stored in a list. This list is the required output which consists of small DataFrames. In this example, the dataset (consists of 9 rows data) is divided into smaller dataframes by splitting each row so the list is created of 9 smaller dataframes as shown below in output. Python3 # split dataframe by rowsplits = [df.loc[[i]] for i in df.index] # view splitted dataframeprint(splits) # check datatype of smaller dataframeprint(type(splits[0])) # view smaller dataframeprint(splits[0]) Output: Example 2: Using Groupby Here, we use the DataFrame.groupby() method for splitting the dataset by rows. The same grouped rows are taken as a single element and stored in a list. This list is the required output which consists of small DataFrames. In this example, the dataset (consists of 9 rows data) is divided into smaller dataframes using groupby method on column “Grade”. Here, the total number of distinct grades is 5 so the list is created of 5 smaller dataframes as shown below in output. Python3 # split dataframe using gropubysplits = list(df.groupby("Grade")) # view splitted dataframeprint(splits) # check datatype of smaller dataframeprint(type(splits[0][1])) # view smaller dataframeprint(splits[0][1]) Output: Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Sep, 2020" }, { "code": null, "e": 203, "s": 52, "text": "In this article, we will learn about the splitting of large dataframe into list of smaller dataframes. This can be done mainly in two different ways :" }, { "code": null, "e": 253, "s": 203, "text": "By splitting each rowUsing the concept of groupby" }, { "code": null, "e": 275, "s": 253, "text": "By splitting each row" }, { "code": null, "e": 304, "s": 275, "text": "Using the concept of groupby" }, { "code": null, "e": 507, "s": 304, "text": "Here we use a small dataframe to understand the concept easily and this can also be implemented in an easy way. The Dataframe consists of student id, name, marks, and grades. Let’s create the dataframe." }, { "code": null, "e": 515, "s": 507, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # dictionary of datadct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash'}, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'} } # create dataframedf = pd.DataFrame(dct) # view dataframedf", "e": 1192, "s": 515, "text": null }, { "code": null, "e": 1200, "s": 1192, "text": "Output:" }, { "code": null, "e": 1271, "s": 1200, "text": "Below is the implementation of the above concepts with some examples :" }, { "code": null, "e": 1304, "s": 1271, "text": "Example 1: By splitting each row" }, { "code": null, "e": 1676, "s": 1304, "text": "Here, we use the loop of iteration for each row. Every row is accessed by using DataFrame.loc[] and stored in a list. This list is the required output which consists of small DataFrames. In this example, the dataset (consists of 9 rows data) is divided into smaller dataframes by splitting each row so the list is created of 9 smaller dataframes as shown below in output." }, { "code": null, "e": 1684, "s": 1676, "text": "Python3" }, { "code": "# split dataframe by rowsplits = [df.loc[[i]] for i in df.index] # view splitted dataframeprint(splits) # check datatype of smaller dataframeprint(type(splits[0])) # view smaller dataframeprint(splits[0])", "e": 1892, "s": 1684, "text": null }, { "code": null, "e": 1900, "s": 1892, "text": "Output:" }, { "code": null, "e": 1925, "s": 1900, "text": "Example 2: Using Groupby" }, { "code": null, "e": 2397, "s": 1925, "text": "Here, we use the DataFrame.groupby() method for splitting the dataset by rows. The same grouped rows are taken as a single element and stored in a list. This list is the required output which consists of small DataFrames. In this example, the dataset (consists of 9 rows data) is divided into smaller dataframes using groupby method on column “Grade”. Here, the total number of distinct grades is 5 so the list is created of 5 smaller dataframes as shown below in output." }, { "code": null, "e": 2405, "s": 2397, "text": "Python3" }, { "code": "# split dataframe using gropubysplits = list(df.groupby(\"Grade\")) # view splitted dataframeprint(splits) # check datatype of smaller dataframeprint(type(splits[0][1])) # view smaller dataframeprint(splits[0][1])", "e": 2620, "s": 2405, "text": null }, { "code": null, "e": 2628, "s": 2620, "text": "Output:" }, { "code": null, "e": 2652, "s": 2628, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2675, "s": 2652, "text": "Python Pandas-exercise" }, { "code": null, "e": 2689, "s": 2675, "text": "Python-pandas" }, { "code": null, "e": 2696, "s": 2689, "text": "Python" }, { "code": null, "e": 2794, "s": 2696, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2812, "s": 2794, "text": "Python Dictionary" }, { "code": null, "e": 2854, "s": 2812, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2876, "s": 2854, "text": "Enumerate() in Python" }, { "code": null, "e": 2911, "s": 2876, "text": "Read a file line by line in Python" }, { "code": null, "e": 2937, "s": 2911, "text": "Python String | replace()" }, { "code": null, "e": 2969, "s": 2937, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2998, "s": 2969, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3025, "s": 2998, "text": "Python Classes and Objects" }, { "code": null, "e": 3055, "s": 3025, "text": "Iterate over a list in Python" } ]
How to create a duplicate file of an existing file using Python?
26 Oct, 2021 In this article, we will discuss how to create a duplicate of the existing file in Python. Below are the source and destination folders, before creating the duplicate file in the destination folder. After a duplicate file has been created in the destination folder, it looks like the image below. For automating of copying and removal of files in Python, shutil module is used. It offers a number of high-level operations on files and collections of files. Using shutil module, we can copy files as well as an entire directory. It copies the contents of the source file to the destination file in the most efficient way possible. It does not use file objects and also does not copy metadata and permissions. Syntax : shutil.copyfile(src, dst, *, follow_symlinks=True) Parameters: src – src here is the complete path of the source file. dest – dest is the complete path of the destination file or directory.The destination location must be writable. follow_symlinks (optional) – The default value of this parameter is True. If it is set to False and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to. Return Type:- It returns the path of the newly created duplicate file. Code: Python3 # Python program to create the duplicate of# an already existing fileimport osD = r"F:\Dest" # importing the shutil moduleimport shutil print("Before copying file:")print(os.listdir(D)) # src contains the path of the source filesrc = r"C:\Users\YASH\OneDrive\Desktop\small\Src\Test.py" # dest contains the path of the destination filedest = r"F:\Dest\Test.py" # create duplicate of the file at the destination,# with the name mentioned# at the end of the destination path# if a file with the same name doesn't already# exist at the destination,# a new file with the name mentioned is createdpath = shutil.copyfile(src,dest) print("After copying file:")print(os.listdir(D)) # print path of the newly created duplicate fileprint("Path of the duplicate file is:")print(path) Output: Before copying the file: ['in.txt', 'out.txt'] After copying the file: ['in.txt', 'out.txt', 'Test.py'] Path of the duplicate file is: F:\Dest\Test.py It also copies the contents of the source file to the destination file or directory. Unlike copyfile(), shutil.copy() also copies the permissions of the source file. Syntax : shutil.copy(src, dst, *, follow_symlinks=True) Parameters:- src – src here is the complete path of the source file. dest – dest is the complete path of the destination file or directory.The destination location must be writable. follow_symlinks (optional) – The default value of this parameter is True. If it is set to False and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to. Return Type:- It returns the path of the newly created duplicate file. Code: Python3 # Python program to create the duplicate of# an already existing fileimport os, statD = r"F:\Dest" # importing the shutil moduleimport shutil print("Before copying file:")print(os.listdir(D)) # src contains the path of the source filesrc=r"C:\Users\YASH\OneDrive\Desktop\small\Src\Test.py" # changing the permission(Read, write, and execute # by others)# of the source fileos.chmod(src, stat.S_IRWXO) # dest contains the path of the destination filedest = r"F:\Dest\Test.py" # create duplicate of the file at the# destination, with the name mentioned# at the end of the destination path# if a file with the same name doesn't# already exist at the destination,# a new file with the name mentioned is createdpath = shutil.copy(src,dest) # checking the permission of# the duplicate file to see if the# permissions have also been copied# check the permission(Read, write, and execute # by others)# of the duplicate fileprint(os.access(path, stat.S_IRWXO)) print("After copying file:")print(os.listdir(D)) # print path of the newly created duplicate fileprint("Path of the duplicate file is:")print(path) Output: Before copying the file: ['in.txt', 'out.txt'] After copying the file: False ['in.txt', 'out.txt', 'Test.py'] Path of the duplicate file is: F:\Dest\Test.py It is almost similar to shutil.copy(), except copy2() also attempts to preserve metadata. When follow_symlinks is set to False, and src is a symbolic link, copy2() attempts to copy all metadata from the src symbolic link to the newly-created dst symbolic link. Syntax : shutil.copy2(src, dst, *, follow_symlinks=True) Parameters: src – src here is the complete path of the source file. dest – dest is the complete path of the destination file or directory.The destination location must be writable. follow_symlinks (optional) – The default value of this parameter is True. If it is set to False and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to. Return Type:- It returns the path of the newly created duplicate file. Code: Python3 # Python program to create the duplicate of an already # existing fileimport osD = r"F:\Dest"# importing the shutil moduleimport shutil print("Before copying file:")print(os.listdir(D)) # src contains the path of the source filesrc=r"C:\Users\YASH\OneDrive\Desktop\small\Src\Test.py" # dest contains the path of the destination filedest = r"F:\Dest\Test.py" # using copy2()path=shutil.copy2(src,dest) # A new duplicate file is added at# the destination with name we mention# on the pathprint("After copying file:")print(os.listdir(D)) # print path of the newly created duplicate fileprint("Path of the duplicate file is:")print(path) Output: Before copying the file: ['in.txt', 'out.txt'] After copying the file: ['in.txt', 'out.txt', 'Test.py'] Path of the duplicate file is: F:\Dest\Test.py kashishsoda Picked Python directory-program Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Oct, 2021" }, { "code": null, "e": 252, "s": 53, "text": "In this article, we will discuss how to create a duplicate of the existing file in Python. Below are the source and destination folders, before creating the duplicate file in the destination folder." }, { "code": null, "e": 350, "s": 252, "text": "After a duplicate file has been created in the destination folder, it looks like the image below." }, { "code": null, "e": 581, "s": 350, "text": "For automating of copying and removal of files in Python, shutil module is used. It offers a number of high-level operations on files and collections of files. Using shutil module, we can copy files as well as an entire directory." }, { "code": null, "e": 761, "s": 581, "text": "It copies the contents of the source file to the destination file in the most efficient way possible. It does not use file objects and also does not copy metadata and permissions." }, { "code": null, "e": 821, "s": 761, "text": "Syntax : shutil.copyfile(src, dst, *, follow_symlinks=True)" }, { "code": null, "e": 833, "s": 821, "text": "Parameters:" }, { "code": null, "e": 889, "s": 833, "text": "src – src here is the complete path of the source file." }, { "code": null, "e": 1002, "s": 889, "text": "dest – dest is the complete path of the destination file or directory.The destination location must be writable." }, { "code": null, "e": 1205, "s": 1002, "text": "follow_symlinks (optional) – The default value of this parameter is True. If it is set to False and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to." }, { "code": null, "e": 1276, "s": 1205, "text": "Return Type:- It returns the path of the newly created duplicate file." }, { "code": null, "e": 1282, "s": 1276, "text": "Code:" }, { "code": null, "e": 1290, "s": 1282, "text": "Python3" }, { "code": "# Python program to create the duplicate of# an already existing fileimport osD = r\"F:\\Dest\" # importing the shutil moduleimport shutil print(\"Before copying file:\")print(os.listdir(D)) # src contains the path of the source filesrc = r\"C:\\Users\\YASH\\OneDrive\\Desktop\\small\\Src\\Test.py\" # dest contains the path of the destination filedest = r\"F:\\Dest\\Test.py\" # create duplicate of the file at the destination,# with the name mentioned# at the end of the destination path# if a file with the same name doesn't already# exist at the destination,# a new file with the name mentioned is createdpath = shutil.copyfile(src,dest) print(\"After copying file:\")print(os.listdir(D)) # print path of the newly created duplicate fileprint(\"Path of the duplicate file is:\")print(path)", "e": 2069, "s": 1290, "text": null }, { "code": null, "e": 2077, "s": 2069, "text": "Output:" }, { "code": null, "e": 2228, "s": 2077, "text": "Before copying the file:\n['in.txt', 'out.txt']\nAfter copying the file:\n['in.txt', 'out.txt', 'Test.py']\nPath of the duplicate file is:\nF:\\Dest\\Test.py" }, { "code": null, "e": 2394, "s": 2228, "text": "It also copies the contents of the source file to the destination file or directory. Unlike copyfile(), shutil.copy() also copies the permissions of the source file." }, { "code": null, "e": 2450, "s": 2394, "text": "Syntax : shutil.copy(src, dst, *, follow_symlinks=True)" }, { "code": null, "e": 2463, "s": 2450, "text": "Parameters:-" }, { "code": null, "e": 2519, "s": 2463, "text": "src – src here is the complete path of the source file." }, { "code": null, "e": 2632, "s": 2519, "text": "dest – dest is the complete path of the destination file or directory.The destination location must be writable." }, { "code": null, "e": 2835, "s": 2632, "text": "follow_symlinks (optional) – The default value of this parameter is True. If it is set to False and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to." }, { "code": null, "e": 2906, "s": 2835, "text": "Return Type:- It returns the path of the newly created duplicate file." }, { "code": null, "e": 2912, "s": 2906, "text": "Code:" }, { "code": null, "e": 2920, "s": 2912, "text": "Python3" }, { "code": "# Python program to create the duplicate of# an already existing fileimport os, statD = r\"F:\\Dest\" # importing the shutil moduleimport shutil print(\"Before copying file:\")print(os.listdir(D)) # src contains the path of the source filesrc=r\"C:\\Users\\YASH\\OneDrive\\Desktop\\small\\Src\\Test.py\" # changing the permission(Read, write, and execute # by others)# of the source fileos.chmod(src, stat.S_IRWXO) # dest contains the path of the destination filedest = r\"F:\\Dest\\Test.py\" # create duplicate of the file at the# destination, with the name mentioned# at the end of the destination path# if a file with the same name doesn't# already exist at the destination,# a new file with the name mentioned is createdpath = shutil.copy(src,dest) # checking the permission of# the duplicate file to see if the# permissions have also been copied# check the permission(Read, write, and execute # by others)# of the duplicate fileprint(os.access(path, stat.S_IRWXO)) print(\"After copying file:\")print(os.listdir(D)) # print path of the newly created duplicate fileprint(\"Path of the duplicate file is:\")print(path)", "e": 4029, "s": 2920, "text": null }, { "code": null, "e": 4037, "s": 4029, "text": "Output:" }, { "code": null, "e": 4194, "s": 4037, "text": "Before copying the file:\n['in.txt', 'out.txt']\nAfter copying the file:\nFalse\n['in.txt', 'out.txt', 'Test.py']\nPath of the duplicate file is:\nF:\\Dest\\Test.py" }, { "code": null, "e": 4455, "s": 4194, "text": "It is almost similar to shutil.copy(), except copy2() also attempts to preserve metadata. When follow_symlinks is set to False, and src is a symbolic link, copy2() attempts to copy all metadata from the src symbolic link to the newly-created dst symbolic link." }, { "code": null, "e": 4512, "s": 4455, "text": "Syntax : shutil.copy2(src, dst, *, follow_symlinks=True)" }, { "code": null, "e": 4524, "s": 4512, "text": "Parameters:" }, { "code": null, "e": 4580, "s": 4524, "text": "src – src here is the complete path of the source file." }, { "code": null, "e": 4693, "s": 4580, "text": "dest – dest is the complete path of the destination file or directory.The destination location must be writable." }, { "code": null, "e": 4896, "s": 4693, "text": "follow_symlinks (optional) – The default value of this parameter is True. If it is set to False and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to." }, { "code": null, "e": 4967, "s": 4896, "text": "Return Type:- It returns the path of the newly created duplicate file." }, { "code": null, "e": 4973, "s": 4967, "text": "Code:" }, { "code": null, "e": 4981, "s": 4973, "text": "Python3" }, { "code": "# Python program to create the duplicate of an already # existing fileimport osD = r\"F:\\Dest\"# importing the shutil moduleimport shutil print(\"Before copying file:\")print(os.listdir(D)) # src contains the path of the source filesrc=r\"C:\\Users\\YASH\\OneDrive\\Desktop\\small\\Src\\Test.py\" # dest contains the path of the destination filedest = r\"F:\\Dest\\Test.py\" # using copy2()path=shutil.copy2(src,dest) # A new duplicate file is added at# the destination with name we mention# on the pathprint(\"After copying file:\")print(os.listdir(D)) # print path of the newly created duplicate fileprint(\"Path of the duplicate file is:\")print(path)", "e": 5621, "s": 4981, "text": null }, { "code": null, "e": 5629, "s": 5621, "text": "Output:" }, { "code": null, "e": 5780, "s": 5629, "text": "Before copying the file:\n['in.txt', 'out.txt']\nAfter copying the file:\n['in.txt', 'out.txt', 'Test.py']\nPath of the duplicate file is:\nF:\\Dest\\Test.py" }, { "code": null, "e": 5792, "s": 5780, "text": "kashishsoda" }, { "code": null, "e": 5799, "s": 5792, "text": "Picked" }, { "code": null, "e": 5824, "s": 5799, "text": "Python directory-program" }, { "code": null, "e": 5831, "s": 5824, "text": "Python" } ]
Flutter – WebSockets
10 Sep, 2020 WebSockets are used to connect with the server just like the http package. It supports two-way communication with a server without polling. In this article we will explore the below-listed topics related to WebSockets in Flutter: Connecting to a WebSocket serverListen to messages from the server.Send data to the server.Close the WebSocket connection. Connecting to a WebSocket server Listen to messages from the server. Send data to the server. Close the WebSocket connection. In this article as an example, we will connect to the test server provided by websocket.org. The web_socket_channel package has tools that are needed to connect to a WebSocket server. The package provides a WebSocketChannel that allows users to both listen to messages from the server and push messages to the server. In Flutter, use the following line to create a WebSocketChannel that connects to a server: final channel = IOWebSocketChannel.connect('ws://echo.websocket.org'); Now that we have established the connection to the server, we will send a message to it and get the same message as a response: Dart StreamBuilder( stream: widget.channel.stream, builder: (context, snapshot) { return Text(snapshot.hasData ? '${snapshot.data}' : ''); },); To send data to the server, add() messages to the sink provided by the WebSocketChannel as shown below: channel.sink.add('Hello Geeks!'); To close the connection to the WebSocket use the below: channel.sink.close(); Complete Source Code: Dart import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Loading album failed!'); }} Future<Album> updateAlbum(String title) async { final http.Response response = await http.put( 'https://jsonplaceholder.typicode.com/albums/1', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to update the album!'); }} // the album classclass Album { final int id; final String title; Album({this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }} void main() { runApp(MyApp());} class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() { return _MyAppState(); }} class _MyAppState extends State<MyApp> { final TextEditingController _controller = TextEditingController(); Future<Album> _futureAlbum; @override void initState() { super.initState(); _futureAlbum = getAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Update Data', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Container( alignment: Alignment.center, padding: const EdgeInsets.all(8.0), child: FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(snapshot.data.title), TextField( controller: _controller, decoration: InputDecoration(hintText: 'Enter Title'), ), RaisedButton( child: Text('Update Data'), onPressed: () { setState(() { _futureAlbum = updateAlbum(_controller.text); }); }, ), ], ); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } } return CircularProgressIndicator(); }, ), ), ), ); }} Output: android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter Flutter - Asset Image Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Stack Widget Flutter - Search Bar
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Sep, 2020" }, { "code": null, "e": 194, "s": 54, "text": "WebSockets are used to connect with the server just like the http package. It supports two-way communication with a server without polling." }, { "code": null, "e": 284, "s": 194, "text": "In this article we will explore the below-listed topics related to WebSockets in Flutter:" }, { "code": null, "e": 407, "s": 284, "text": "Connecting to a WebSocket serverListen to messages from the server.Send data to the server.Close the WebSocket connection." }, { "code": null, "e": 440, "s": 407, "text": "Connecting to a WebSocket server" }, { "code": null, "e": 476, "s": 440, "text": "Listen to messages from the server." }, { "code": null, "e": 501, "s": 476, "text": "Send data to the server." }, { "code": null, "e": 533, "s": 501, "text": "Close the WebSocket connection." }, { "code": null, "e": 626, "s": 533, "text": "In this article as an example, we will connect to the test server provided by websocket.org." }, { "code": null, "e": 851, "s": 626, "text": "The web_socket_channel package has tools that are needed to connect to a WebSocket server. The package provides a WebSocketChannel that allows users to both listen to messages from the server and push messages to the server." }, { "code": null, "e": 942, "s": 851, "text": "In Flutter, use the following line to create a WebSocketChannel that connects to a server:" }, { "code": null, "e": 1013, "s": 942, "text": "final channel = IOWebSocketChannel.connect('ws://echo.websocket.org');" }, { "code": null, "e": 1141, "s": 1013, "text": "Now that we have established the connection to the server, we will send a message to it and get the same message as a response:" }, { "code": null, "e": 1146, "s": 1141, "text": "Dart" }, { "code": "StreamBuilder( stream: widget.channel.stream, builder: (context, snapshot) { return Text(snapshot.hasData ? '${snapshot.data}' : ''); },);", "e": 1291, "s": 1146, "text": null }, { "code": null, "e": 1395, "s": 1291, "text": "To send data to the server, add() messages to the sink provided by the WebSocketChannel as shown below:" }, { "code": null, "e": 1429, "s": 1395, "text": "channel.sink.add('Hello Geeks!');" }, { "code": null, "e": 1485, "s": 1429, "text": "To close the connection to the WebSocket use the below:" }, { "code": null, "e": 1507, "s": 1485, "text": "channel.sink.close();" }, { "code": null, "e": 1529, "s": 1507, "text": "Complete Source Code:" }, { "code": null, "e": 1534, "s": 1529, "text": "Dart" }, { "code": "import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Loading album failed!'); }} Future<Album> updateAlbum(String title) async { final http.Response response = await http.put( 'https://jsonplaceholder.typicode.com/albums/1', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to update the album!'); }} // the album classclass Album { final int id; final String title; Album({this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }} void main() { runApp(MyApp());} class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() { return _MyAppState(); }} class _MyAppState extends State<MyApp> { final TextEditingController _controller = TextEditingController(); Future<Album> _futureAlbum; @override void initState() { super.initState(); _futureAlbum = getAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Update Data', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Container( alignment: Alignment.center, padding: const EdgeInsets.all(8.0), child: FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(snapshot.data.title), TextField( controller: _controller, decoration: InputDecoration(hintText: 'Enter Title'), ), RaisedButton( child: Text('Update Data'), onPressed: () { setState(() { _futureAlbum = updateAlbum(_controller.text); }); }, ), ], ); } else if (snapshot.hasError) { return Text(\"${snapshot.error}\"); } } return CircularProgressIndicator(); }, ), ), ), ); }}", "e": 4617, "s": 1534, "text": null }, { "code": null, "e": 4625, "s": 4617, "text": "Output:" }, { "code": null, "e": 4633, "s": 4625, "text": "android" }, { "code": null, "e": 4641, "s": 4633, "text": "Flutter" }, { "code": null, "e": 4646, "s": 4641, "text": "Dart" }, { "code": null, "e": 4654, "s": 4646, "text": "Flutter" }, { "code": null, "e": 4752, "s": 4654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4784, "s": 4752, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 4812, "s": 4784, "text": "Listview.builder in Flutter" }, { "code": null, "e": 4851, "s": 4812, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 4876, "s": 4851, "text": "Splash Screen in Flutter" }, { "code": null, "e": 4898, "s": 4876, "text": "Flutter - Asset Image" }, { "code": null, "e": 4930, "s": 4898, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 4969, "s": 4930, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 4995, "s": 4969, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 5018, "s": 4995, "text": "Flutter - Stack Widget" } ]
How to use xPath in Selenium WebDriver to grab SVG elements?
We can use xpath to grab SVG elements with Selenium webdriver. A SVG element is identified with tagname svg. The svg image has the attributes like width and height attributes. Let us investigate the html code of a svg element. To create a xpath for a svg element, we have the syntax as //*[local-name()='svg']. The local-name function is mandatory for creating a xpath of a svg element. So for the xpath expression for the image highlighted in the above image should be − //*[local-name()='svg' and @data-icon='home']/*[local-name()='path'] Here, data-icon is an attribute of the svg tag element which is added accompanied with @ symbol. The [local-name()='path'] is included since it is the child of the svg tagname. Let us validate the xpath we have created, within the Console tab. The image which is a SVG element before the Home menu gets highlighted with our XPath. Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class SVGElement{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); // wait of 5 seconds driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/index.htm"); // identify element WebElement m= driver.findElement(By.xpath("//*[local-name()='svg' and @dataicon='home']/*[local-name()='path']")); // Action class to move and click element Actions act = new Actions(driver); act.moveToElement(m). click().build().perform(); driver.quit(); } }
[ { "code": null, "e": 1363, "s": 1187, "text": "We can use xpath to grab SVG elements with Selenium webdriver. A SVG element is identified with tagname svg. The svg image has the attributes like width and height attributes." }, { "code": null, "e": 1414, "s": 1363, "text": "Let us investigate the html code of a svg element." }, { "code": null, "e": 1498, "s": 1414, "text": "To create a xpath for a svg element, we have the syntax as //*[local-name()='svg']." }, { "code": null, "e": 1659, "s": 1498, "text": "The local-name function is mandatory for creating a xpath of a svg element. So for the xpath expression for the image highlighted in the above image should be −" }, { "code": null, "e": 1728, "s": 1659, "text": "//*[local-name()='svg' and @data-icon='home']/*[local-name()='path']" }, { "code": null, "e": 1905, "s": 1728, "text": "Here, data-icon is an attribute of the svg tag element which is added accompanied with @ symbol. The [local-name()='path'] is included since it is the child of the svg tagname." }, { "code": null, "e": 1972, "s": 1905, "text": "Let us validate the xpath we have created, within the Console tab." }, { "code": null, "e": 2059, "s": 1972, "text": "The image which is a SVG element before the Home menu gets highlighted with our XPath." }, { "code": null, "e": 2080, "s": 2059, "text": "Code Implementation." }, { "code": null, "e": 2980, "s": 2080, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class SVGElement{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n // wait of 5 seconds\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify element\n WebElement m= driver.findElement(By.xpath(\"//*[local-name()='svg' and @dataicon='home']/*[local-name()='path']\"));\n // Action class to move and click element\n Actions act = new Actions(driver);\n act.moveToElement(m).\n click().build().perform();\n driver.quit();\n }\n}" } ]
Binning in Data Mining
15 Jun, 2022 Data binning, bucketing is a data pre-processing method used to minimize the effects of small observation errors. The original data values are divided into small intervals known as bins and then they are replaced by a general value calculated for that bin. This has a smoothing effect on the input data and may also reduce the chances of overfitting in the case of small datasetsThere are 2 methods of dividing data into bins: Equal Frequency Binning: bins have an equal frequency.Equal Width Binning : bins have equal width with a range of each bin are defined as [min + w], [min + 2w] .... [min + nw] where w = (max – min) / (no of bins). Equal Frequency Binning: bins have an equal frequency. Equal Width Binning : bins have equal width with a range of each bin are defined as [min + w], [min + 2w] .... [min + nw] where w = (max – min) / (no of bins). Equal frequency: Input:[5, 10, 11, 13, 15, 35, 50, 55, 72, 92, 204, 215] Output: [5, 10, 11, 13] [15, 35, 50, 55] [72, 92, 204, 215] Equal Width: Input: [5, 10, 11, 13, 15, 35, 50, 55, 72, 92, 204, 215] Output: [5, 10, 11, 13, 15, 35, 50, 55, 72] [92] [204, 215] Code : Implementation of Binning Technique: Python # equal frequencydef equifreq(arr1, m): a = len(arr1) n = int(a / m) for i in range(0, m): arr = [] for j in range(i * n, (i + 1) * n): if j >= a: break arr = arr + [arr1[j]] print(arr) # equal widthdef equiwidth(arr1, m): a = len(arr1) w = int((max(arr1) - min(arr1)) / m) min1 = min(arr1) arr = [] for i in range(0, m + 1): arr = arr + [min1 + w * i] arri=[] for i in range(0, m): temp = [] for j in arr1: if j >= arr[i] and j <= arr[i+1]: temp += [j] arri += [temp] print(arri) # data to be binneddata = [5, 10, 11, 13, 15, 35, 50, 55, 72, 92, 204, 215] # no of binsm = 3 print("equal frequency binning")equifreq(data, m) print("\n\nequal width binning")equiwidth(data, 3) Output : equal frequency binning [5, 10, 11, 13] [15, 35, 50, 55] [72, 92, 204, 215] equal width binning [[5, 10, 11, 13, 15, 35, 50, 55, 72], [92], [204, 215]] vc17srimouli Kumaramit2000 sumitgumber28 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Decision Tree Introduction with example Search Algorithms in AI Getting started with Machine Learning Support Vector Machine Algorithm Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jun, 2022" }, { "code": null, "e": 457, "s": 28, "text": "Data binning, bucketing is a data pre-processing method used to minimize the effects of small observation errors. The original data values are divided into small intervals known as bins and then they are replaced by a general value calculated for that bin. This has a smoothing effect on the input data and may also reduce the chances of overfitting in the case of small datasetsThere are 2 methods of dividing data into bins: " }, { "code": null, "e": 671, "s": 457, "text": "Equal Frequency Binning: bins have an equal frequency.Equal Width Binning : bins have equal width with a range of each bin are defined as [min + w], [min + 2w] .... [min + nw] where w = (max – min) / (no of bins)." }, { "code": null, "e": 726, "s": 671, "text": "Equal Frequency Binning: bins have an equal frequency." }, { "code": null, "e": 886, "s": 726, "text": "Equal Width Binning : bins have equal width with a range of each bin are defined as [min + w], [min + 2w] .... [min + nw] where w = (max – min) / (no of bins)." }, { "code": null, "e": 904, "s": 886, "text": "Equal frequency: " }, { "code": null, "e": 1022, "s": 904, "text": "Input:[5, 10, 11, 13, 15, 35, 50, 55, 72, 92, 204, 215] \n\nOutput:\n[5, 10, 11, 13]\n[15, 35, 50, 55]\n[72, 92, 204, 215]" }, { "code": null, "e": 1037, "s": 1022, "text": "Equal Width: " }, { "code": null, "e": 1155, "s": 1037, "text": "Input: [5, 10, 11, 13, 15, 35, 50, 55, 72, 92, 204, 215]\n\nOutput:\n[5, 10, 11, 13, 15, 35, 50, 55, 72]\n[92]\n[204, 215]" }, { "code": null, "e": 1200, "s": 1155, "text": "Code : Implementation of Binning Technique: " }, { "code": null, "e": 1207, "s": 1200, "text": "Python" }, { "code": "# equal frequencydef equifreq(arr1, m): a = len(arr1) n = int(a / m) for i in range(0, m): arr = [] for j in range(i * n, (i + 1) * n): if j >= a: break arr = arr + [arr1[j]] print(arr) # equal widthdef equiwidth(arr1, m): a = len(arr1) w = int((max(arr1) - min(arr1)) / m) min1 = min(arr1) arr = [] for i in range(0, m + 1): arr = arr + [min1 + w * i] arri=[] for i in range(0, m): temp = [] for j in arr1: if j >= arr[i] and j <= arr[i+1]: temp += [j] arri += [temp] print(arri) # data to be binneddata = [5, 10, 11, 13, 15, 35, 50, 55, 72, 92, 204, 215] # no of binsm = 3 print(\"equal frequency binning\")equifreq(data, m) print(\"\\n\\nequal width binning\")equiwidth(data, 3)", "e": 2045, "s": 1207, "text": null }, { "code": null, "e": 2055, "s": 2045, "text": "Output : " }, { "code": null, "e": 2210, "s": 2055, "text": "equal frequency binning\n[5, 10, 11, 13]\n[15, 35, 50, 55]\n[72, 92, 204, 215]\n\n\nequal width binning\n[[5, 10, 11, 13, 15, 35, 50, 55, 72], [92], [204, 215]] " }, { "code": null, "e": 2223, "s": 2210, "text": "vc17srimouli" }, { "code": null, "e": 2237, "s": 2223, "text": "Kumaramit2000" }, { "code": null, "e": 2251, "s": 2237, "text": "sumitgumber28" }, { "code": null, "e": 2268, "s": 2251, "text": "Machine Learning" }, { "code": null, "e": 2275, "s": 2268, "text": "Python" }, { "code": null, "e": 2292, "s": 2275, "text": "Machine Learning" }, { "code": null, "e": 2390, "s": 2292, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2413, "s": 2390, "text": "ML | Linear Regression" }, { "code": null, "e": 2453, "s": 2413, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 2477, "s": 2453, "text": "Search Algorithms in AI" }, { "code": null, "e": 2515, "s": 2477, "text": "Getting started with Machine Learning" }, { "code": null, "e": 2548, "s": 2515, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 2576, "s": 2548, "text": "Read JSON file using Python" }, { "code": null, "e": 2598, "s": 2576, "text": "Python map() function" }, { "code": null, "e": 2648, "s": 2598, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2666, "s": 2648, "text": "Python Dictionary" } ]
How to return an array from async function in Node.js ?
01 Jul, 2021 We have to call the async function from another function which can be asynchronous or synchronous (We can pass the array or choose to declare the array in the async function itself) and then return the array from the async function. The basic approach is to include a try-catch block. If anything wrong happens while executing the try block statements, then a catch block is used to handle the exception. Example 1: Below is the code in which we call the print function. We define the array in this function(in this case asynchronous), pass it to another async function sort. The sort function then sorts the array and returns the array, and then we display the array from the print function. index.js const sort = async (arr) => { try { let i, j, temp; // Using bubble sort to sort the array for (i = 0; i < arr.length; i++) { for (j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { // The await prevents the // execution of next line // until this line is executed temp = await arr[i]; arr[i] = await arr[j]; arr[j] = await temp; } } } // Returns the sorted array return arr; } catch (e) { // Display the error in case // enything wrong happened console.log(e) }} const print = async () => { // Use try-catch block to handle error try { // Define and initialize an array let arr = [17, 90, 13, 10, 76] // Call the "sort" function passing // the array and store the result in // "sortedArray", await will prevent // the execution of next line until // this line is executed. const sortedArray = await sort(arr) // Display sortedArray to check if // everything works fine console.log(sortedArray) } catch (e) { // Display the error in case // anything wrong happened console.log(e) }} // Calling print() is calledprint(); Run the index.js file using the following command: node index.js Output: [ 10, 13, 17, 76, 90 ] Example 2: Now let’s see the example of returning an array from an async function which has been declared in that async function. The function will return an array of all the prime numbers that are less than a given number N. index.js const prime = async (N) => { try { const arr = [] // Iterate from 2 to N-1 to check // which numbers are prime for (var i = 2; i < N; i++) { let j = 2 while (j < i) { // Check if the number is // divisble by any number // except 1 and itself if (i % j == 0) { break } j++; } if (j == i) { // If this condition holds // true then it means that // the number is not // divisible by any number // except 1 and itself. // Therefore, it is a prime // number and add this number // to the array. arr.push(j) } } // Return the array return arr } catch (e) { // Display the error in case // anything wrong happened console.log(e) }} const findPrime = async () => { try { let N = 20 // Call prime() passing argument // N which is equal to 20 and // store the result in an array const primeAry = await prime(N) // Print the array console.log(primeAry) } catch (e) { // Display the error in case // anything wrong happened console.log(e) }} // Calling findPrime() methodfindPrime() Output: [ 2, 3, 5, 7, 11, 13, 17, 19 ] 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": 28, "s": 0, "text": "\n01 Jul, 2021" }, { "code": null, "e": 261, "s": 28, "text": "We have to call the async function from another function which can be asynchronous or synchronous (We can pass the array or choose to declare the array in the async function itself) and then return the array from the async function." }, { "code": null, "e": 433, "s": 261, "text": "The basic approach is to include a try-catch block. If anything wrong happens while executing the try block statements, then a catch block is used to handle the exception." }, { "code": null, "e": 721, "s": 433, "text": "Example 1: Below is the code in which we call the print function. We define the array in this function(in this case asynchronous), pass it to another async function sort. The sort function then sorts the array and returns the array, and then we display the array from the print function." }, { "code": null, "e": 730, "s": 721, "text": "index.js" }, { "code": "const sort = async (arr) => { try { let i, j, temp; // Using bubble sort to sort the array for (i = 0; i < arr.length; i++) { for (j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { // The await prevents the // execution of next line // until this line is executed temp = await arr[i]; arr[i] = await arr[j]; arr[j] = await temp; } } } // Returns the sorted array return arr; } catch (e) { // Display the error in case // enything wrong happened console.log(e) }} const print = async () => { // Use try-catch block to handle error try { // Define and initialize an array let arr = [17, 90, 13, 10, 76] // Call the \"sort\" function passing // the array and store the result in // \"sortedArray\", await will prevent // the execution of next line until // this line is executed. const sortedArray = await sort(arr) // Display sortedArray to check if // everything works fine console.log(sortedArray) } catch (e) { // Display the error in case // anything wrong happened console.log(e) }} // Calling print() is calledprint();", "e": 2135, "s": 730, "text": null }, { "code": null, "e": 2188, "s": 2137, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 2202, "s": 2188, "text": "node index.js" }, { "code": null, "e": 2210, "s": 2202, "text": "Output:" }, { "code": null, "e": 2233, "s": 2210, "text": "[ 10, 13, 17, 76, 90 ]" }, { "code": null, "e": 2459, "s": 2233, "text": "Example 2: Now let’s see the example of returning an array from an async function which has been declared in that async function. The function will return an array of all the prime numbers that are less than a given number N." }, { "code": null, "e": 2468, "s": 2459, "text": "index.js" }, { "code": "const prime = async (N) => { try { const arr = [] // Iterate from 2 to N-1 to check // which numbers are prime for (var i = 2; i < N; i++) { let j = 2 while (j < i) { // Check if the number is // divisble by any number // except 1 and itself if (i % j == 0) { break } j++; } if (j == i) { // If this condition holds // true then it means that // the number is not // divisible by any number // except 1 and itself. // Therefore, it is a prime // number and add this number // to the array. arr.push(j) } } // Return the array return arr } catch (e) { // Display the error in case // anything wrong happened console.log(e) }} const findPrime = async () => { try { let N = 20 // Call prime() passing argument // N which is equal to 20 and // store the result in an array const primeAry = await prime(N) // Print the array console.log(primeAry) } catch (e) { // Display the error in case // anything wrong happened console.log(e) }} // Calling findPrime() methodfindPrime()", "e": 3930, "s": 2468, "text": null }, { "code": null, "e": 3938, "s": 3930, "text": "Output:" }, { "code": null, "e": 3979, "s": 3938, "text": "[\n 2, 3, 5, 7,\n 11, 13, 17, 19 \n]" }, { "code": null, "e": 3996, "s": 3979, "text": "NodeJS-Questions" }, { "code": null, "e": 4003, "s": 3996, "text": "Picked" }, { "code": null, "e": 4011, "s": 4003, "text": "Node.js" }, { "code": null, "e": 4028, "s": 4011, "text": "Web Technologies" } ]
C++ Program to Implement Binary Heap
A Binary Heap is a complete binary tree which is either Min Heap or Max Heap. In a Max Binary Heap, the key at root must be maximum among all keys present in Binary Heap. This property must be recursively true for all nodes in that Binary Tree. Min Binary Heap is similar to MinHeap. void BHeap::Insert(int ele): Perform insertion operation to insert element in heap. void BHeap::DeleteMin(): Perform deleteion operation to delete minimum value from heap. int BHeap::ExtractMin(): Perfrom operation to extract minimum value from heap. void BHeap::showHeap(): To show the elements of heap. void BHeap::heapifyup(int in): maintain heap structure in bottom up manner. void BHeap::heapifydown(int in): maintain heap structure in top down manner. #include <iostream> #include <cstdlib> #include <vector> #include <iterator> using namespace std; class BHeap { private: vector <int> heap; int l(int parent); int r(int parent); int par(int child); void heapifyup(int index); void heapifydown(int index); public: BHeap() {} void Insert(int element); void DeleteMin(); int ExtractMin(); void showHeap(); int Size(); }; int main() { BHeap h; while (1) { cout<<"1.Insert Element"<<endl; cout<<"2.Delete Minimum Element"<<endl; cout<<"3.Extract Minimum Element"<<endl; cout<<"4.Show Heap"<<endl; cout<<"5.Exit"<<endl; int c, e; cout<<"Enter your choice: "; cin>>c; switch(c) { case 1: cout<<"Enter the element to be inserted: "; cin>>e; h.Insert(e); break; case 2: h.DeleteMin(); break; case 3: if (h.ExtractMin() == -1) { cout<<"Heap is Empty"<<endl; } else cout<<"Minimum Element: "<<h.ExtractMin()<<endl; break; case 4: cout<<"Displaying elements of Hwap: "; h.showHeap(); break; case 5: exit(1); default: cout<<"Enter Correct Choice"<<endl; } } return 0; } int BHeap::Size() { return heap.size(); } void BHeap::Insert(int ele) { heap.push_back(ele); heapifyup(heap.size() -1); } void BHeap::DeleteMin() { if (heap.size() == 0) { cout<<"Heap is Empty"<<endl; return; } heap[0] = heap.at(heap.size() - 1); heap.pop_back(); heapifydown(0); cout<<"Element Deleted"<<endl; } int BHeap::ExtractMin() { if (heap.size() == 0) { return -1; } else return heap.front(); } void BHeap::showHeap() { vector <int>::iterator pos = heap.begin(); cout<<"Heap --> "; while (pos != heap.end()) { cout<<*pos<<" "; pos++; } cout<<endl; } int BHeap::l(int parent) { int l = 2 * parent + 1; if (l < heap.size()) return l; else return -1; } int BHeap::r(int parent) { int r = 2 * parent + 2; if (r < heap.size()) return r; else return -1; } int BHeap::par(int child) { int p = (child - 1)/2; if (child == 0) return -1; else return p; } void BHeap::heapifyup(int in) { if (in >= 0 && par(in) >= 0 && heap[par(in)] > heap[in]) { int temp = heap[in]; heap[in] = heap[par(in)]; heap[par(in)] = temp; heapifyup(par(in)); } } void BHeap::heapifydown(int in) { int child = l(in); int child1 = r(in); if (child >= 0 && child1 >= 0 && heap[child] > heap[child1]) { child = child1; } if (child > 0 && heap[in] > heap[child]) { int t = heap[in]; heap[in] = heap[child]; heap[child] = t; heapifydown(child); } } 1.Insert Element 2.Delete Minimum Element 3.Extract Minimum Element 4.Show Heap 5.Exit Enter your choice: 1 Enter the element to be inserted: 2 1.Insert Element 2.Delete Minimum Element 3.Extract Minimum Element 4.Show Heap 5.Exit Enter your choice: 1 Enter the element to be inserted: 3 1.Insert Element 2.Delete Minimum Element 3.Extract Minimum Element 4.Show Heap 5.Exit Enter your choice: 1 Enter the element to be inserted: 7 1.Insert Element 2.Delete Minimum Element 3.Extract Minimum Element 4.Show Heap 5.Exit Enter your choice: 1 Enter the element to be inserted: 6 1.Insert Element 2.Delete Minimum Element 3.Extract Minimum Element 4.Show Heap 5.Exit Enter your choice: 4 Displaying elements of Hwap: Heap --> 2 3 7 6 1.Insert Element 2.Delete Minimum Element 3.Extract Minimum Element 4.Show Heap 5.Exit Enter your choice: 3 Minimum Element: 2 1.Insert Element 2.Delete Minimum Element 3.Extract Minimum Element 4.Show Heap 5.Exit Enter your choice: 3 Minimum Element: 2 1.Insert Element 2.Delete Minimum Element 3.Extract Minimum Element 4.Show Heap 5.Exit Enter your choice: 2 Element Deleted 1.Insert Element 2.Delete Minimum Element 3.Extract Minimum Element 4.Show Heap 5.Exit Enter your choice: 4 Displaying elements of Hwap: Heap --> 3 6 7 1.Insert Element 2.Delete Minimum Element 3.Extract Minimum Element 4.Show Heap 5.Exit Enter your choice: 5
[ { "code": null, "e": 1471, "s": 1187, "text": "A Binary Heap is a complete binary tree which is either Min Heap or Max Heap. In a Max Binary Heap, the key at root must be maximum among all keys present in Binary Heap. This property must be recursively true for all nodes in that Binary Tree. Min Binary Heap is similar to MinHeap." }, { "code": null, "e": 1555, "s": 1471, "text": "void BHeap::Insert(int ele): Perform insertion operation to insert element in heap." }, { "code": null, "e": 1643, "s": 1555, "text": "void BHeap::DeleteMin(): Perform deleteion operation to delete minimum value from heap." }, { "code": null, "e": 1722, "s": 1643, "text": "int BHeap::ExtractMin(): Perfrom operation to extract minimum value from heap." }, { "code": null, "e": 1776, "s": 1722, "text": "void BHeap::showHeap(): To show the elements of heap." }, { "code": null, "e": 1852, "s": 1776, "text": "void BHeap::heapifyup(int in): maintain heap structure in bottom up manner." }, { "code": null, "e": 1929, "s": 1852, "text": "void BHeap::heapifydown(int in): maintain heap structure in top down manner." }, { "code": null, "e": 4862, "s": 1929, "text": "#include <iostream>\n#include <cstdlib>\n#include <vector>\n#include <iterator>\nusing namespace std;\nclass BHeap {\n private:\n vector <int> heap;\n int l(int parent);\n int r(int parent);\n int par(int child);\n void heapifyup(int index);\n void heapifydown(int index);\n public:\n BHeap() {}\n void Insert(int element);\n void DeleteMin();\n int ExtractMin();\n void showHeap();\n int Size();\n};\nint main() {\n BHeap h;\n while (1) {\n cout<<\"1.Insert Element\"<<endl;\n cout<<\"2.Delete Minimum Element\"<<endl;\n cout<<\"3.Extract Minimum Element\"<<endl;\n cout<<\"4.Show Heap\"<<endl;\n cout<<\"5.Exit\"<<endl;\n int c, e;\n cout<<\"Enter your choice: \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Enter the element to be inserted: \";\n cin>>e;\n h.Insert(e);\n break;\n case 2:\n h.DeleteMin();\n break;\n case 3:\n if (h.ExtractMin() == -1) {\n cout<<\"Heap is Empty\"<<endl;\n }\n else\n cout<<\"Minimum Element: \"<<h.ExtractMin()<<endl;\n break;\n case 4:\n cout<<\"Displaying elements of Hwap: \";\n h.showHeap();\n break;\n case 5:\n exit(1);\n default:\n cout<<\"Enter Correct Choice\"<<endl;\n }\n }\n return 0;\n}\nint BHeap::Size() {\n return heap.size();\n}\nvoid BHeap::Insert(int ele) {\n heap.push_back(ele);\n heapifyup(heap.size() -1);\n}\nvoid BHeap::DeleteMin() {\n if (heap.size() == 0) {\n cout<<\"Heap is Empty\"<<endl;\n return;\n }\n heap[0] = heap.at(heap.size() - 1);\n heap.pop_back();\n heapifydown(0);\n cout<<\"Element Deleted\"<<endl;\n}\nint BHeap::ExtractMin() {\n if (heap.size() == 0) {\n return -1;\n }\n else\n return heap.front();\n}\nvoid BHeap::showHeap() {\n vector <int>::iterator pos = heap.begin();\n cout<<\"Heap --> \";\n while (pos != heap.end()) {\n cout<<*pos<<\" \";\n pos++;\n }\n cout<<endl;\n}\nint BHeap::l(int parent) {\n int l = 2 * parent + 1;\n if (l < heap.size())\n return l;\n else\n return -1;\n}\nint BHeap::r(int parent) {\n int r = 2 * parent + 2;\n if (r < heap.size())\n return r;\n else\n return -1;\n}\nint BHeap::par(int child) {\n int p = (child - 1)/2;\n if (child == 0)\n return -1;\n else\n return p;\n}\nvoid BHeap::heapifyup(int in) {\n if (in >= 0 && par(in) >= 0 && heap[par(in)] > heap[in]) {\n int temp = heap[in];\n heap[in] = heap[par(in)];\n heap[par(in)] = temp;\n heapifyup(par(in));\n }\n}\nvoid BHeap::heapifydown(int in) {\n int child = l(in);\n int child1 = r(in);\n if (child >= 0 && child1 >= 0 && heap[child] > heap[child1]) {\n child = child1;\n }\n if (child > 0 && heap[in] > heap[child]) {\n int t = heap[in];\n heap[in] = heap[child];\n heap[child] = t;\n heapifydown(child);\n }\n}" }, { "code": null, "e": 6230, "s": 4862, "text": "1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 1\nEnter the element to be inserted: 2\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 1\nEnter the element to be inserted: 3\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 1\nEnter the element to be inserted: 7\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 1\nEnter the element to be inserted: 6\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 4\nDisplaying elements of Hwap: Heap --> 2 3 7 6\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 3\nMinimum Element: 2\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 3\nMinimum Element: 2\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 2\nElement Deleted\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 4\nDisplaying elements of Hwap: Heap --> 3 6 7\n1.Insert Element\n2.Delete Minimum Element\n3.Extract Minimum Element\n4.Show Heap\n5.Exit\nEnter your choice: 5" } ]
Loops in Java
11 May, 2022 Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time. while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax : while (boolean condition) { loop statements... } Flowchart: While loop starts with the checking of condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason it is also called Entry control loopOnce the condition is evaluated to true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.When the condition becomes false, the loop terminates which marks the end of its life cycle. While loop starts with the checking of condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason it is also called Entry control loop Once the condition is evaluated to true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration. When the condition becomes false, the loop terminates which marks the end of its life cycle. for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. Syntax: for (initialization condition; testing condition; increment/decrement) { statement(s) } Flowchart: Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.Increment/ Decrement: It is used for updating the variable for next iteration.Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle. Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only. Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements. Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed. Increment/ Decrement: It is used for updating the variable for next iteration. Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle. do while: do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop. Syntax: do { statements.. } while (condition); Flowchart: do while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to true, next iteration of loop starts.When the condition becomes false, the loop terminates which marks the end of its life cycle.It is important to note that the do-while loop will execute its statements atleast once before any condition is checked, and therefore is an example of exit control loop. do while loop starts with the execution of the statement(s). There is no checking of any condition for the first time. After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to true, next iteration of loop starts. When the condition becomes false, the loop terminates which marks the end of its life cycle. It is important to note that the do-while loop will execute its statements atleast once before any condition is checked, and therefore is an example of exit control loop. Pitfalls of Loops 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. Infinite loop: One of the most common mistakes while implementing any sort of looping is that it may not ever exit, that is the loop runs for infinite time. This happens when the condition fails for some reason. Examples: Java //Java program to illustrate various pitfalls.public class LooppitfallsDemo{ public static void main(String[] args) { // infinite loop because condition is not apt // condition should have been i>0. for (int i = 5; i != 0; i -= 2) { System.out.println(i); } int x = 5; // infinite loop because update statement // is not provided. while (x == 5) { System.out.println("In the loop"); } }} Another pitfall is that you might be adding something into you collection object through loop and you can run out of memory. If you try and execute the below program, after some time, out of memory exception will be thrown. Java //Java program for out of memory exception.import java.util.ArrayList;public class Integer1{ public static void main(String[] args) { ArrayList<Integer> ar = new ArrayList<>(); for (int i = 0; i < Integer.MAX_VALUE; i++) { ar.add(i); } }} Output: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Unknown Source) at java.util.Arrays.copyOf(Unknown Source) at java.util.ArrayList.grow(Unknown Source) at java.util.ArrayList.ensureCapacityInternal(Unknown Source) at java.util.ArrayList.add(Unknown Source) at article.Integer1.main(Integer1.java:9) This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. harshgundecha punamsingh628700 simmytarika5 java-basics Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2022" }, { "code": null, "e": 379, "s": 52, "text": "Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time." }, { "code": null, "e": 574, "s": 379, "text": "while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. " }, { "code": null, "e": 583, "s": 574, "text": "Syntax :" }, { "code": null, "e": 635, "s": 583, "text": "while (boolean condition)\n{\n loop statements...\n}" }, { "code": null, "e": 1158, "s": 635, "text": "Flowchart: While loop starts with the checking of condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason it is also called Entry control loopOnce the condition is evaluated to true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.When the condition becomes false, the loop terminates which marks the end of its life cycle." }, { "code": null, "e": 1387, "s": 1158, "text": "While loop starts with the checking of condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason it is also called Entry control loop" }, { "code": null, "e": 1579, "s": 1387, "text": "Once the condition is evaluated to true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration." }, { "code": null, "e": 1672, "s": 1579, "text": "When the condition becomes false, the loop terminates which marks the end of its life cycle." }, { "code": null, "e": 1923, "s": 1672, "text": "for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. " }, { "code": null, "e": 1931, "s": 1923, "text": "Syntax:" }, { "code": null, "e": 2054, "s": 1931, "text": "for (initialization condition; testing condition; \n increment/decrement)\n{\n statement(s)\n}" }, { "code": null, "e": 2760, "s": 2054, "text": "Flowchart: Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.Increment/ Decrement: It is used for updating the variable for next iteration.Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle." }, { "code": null, "e": 2953, "s": 2760, "text": "Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only." }, { "code": null, "e": 3166, "s": 2953, "text": "Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements." }, { "code": null, "e": 3274, "s": 3166, "text": "Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed." }, { "code": null, "e": 3353, "s": 3274, "text": "Increment/ Decrement: It is used for updating the variable for next iteration." }, { "code": null, "e": 3459, "s": 3353, "text": "Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle." }, { "code": null, "e": 3641, "s": 3459, "text": "do while: do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop. " }, { "code": null, "e": 3649, "s": 3641, "text": "Syntax:" }, { "code": null, "e": 3692, "s": 3649, "text": "do\n{\n statements..\n}\nwhile (condition);" }, { "code": null, "e": 4265, "s": 3692, "text": "Flowchart: do while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to true, next iteration of loop starts.When the condition becomes false, the loop terminates which marks the end of its life cycle.It is important to note that the do-while loop will execute its statements atleast once before any condition is checked, and therefore is an example of exit control loop." }, { "code": null, "e": 4384, "s": 4265, "text": "do while loop starts with the execution of the statement(s). There is no checking of any condition for the first time." }, { "code": null, "e": 4566, "s": 4384, "text": "After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to true, next iteration of loop starts." }, { "code": null, "e": 4659, "s": 4566, "text": "When the condition becomes false, the loop terminates which marks the end of its life cycle." }, { "code": null, "e": 4830, "s": 4659, "text": "It is important to note that the do-while loop will execute its statements atleast once before any condition is checked, and therefore is an example of exit control loop." }, { "code": null, "e": 4848, "s": 4830, "text": "Pitfalls of Loops" }, { "code": null, "e": 4857, "s": 4848, "text": "Chapters" }, { "code": null, "e": 4884, "s": 4857, "text": "descriptions off, selected" }, { "code": null, "e": 4934, "s": 4884, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 4957, "s": 4934, "text": "captions off, selected" }, { "code": null, "e": 4965, "s": 4957, "text": "English" }, { "code": null, "e": 4989, "s": 4965, "text": "This is a modal window." }, { "code": null, "e": 5058, "s": 4989, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 5080, "s": 5058, "text": "End of dialog window." }, { "code": null, "e": 5303, "s": 5080, "text": "Infinite loop: One of the most common mistakes while implementing any sort of looping is that it may not ever exit, that is the loop runs for infinite time. This happens when the condition fails for some reason. Examples: " }, { "code": null, "e": 5308, "s": 5303, "text": "Java" }, { "code": "//Java program to illustrate various pitfalls.public class LooppitfallsDemo{ public static void main(String[] args) { // infinite loop because condition is not apt // condition should have been i>0. for (int i = 5; i != 0; i -= 2) { System.out.println(i); } int x = 5; // infinite loop because update statement // is not provided. while (x == 5) { System.out.println(\"In the loop\"); } }}", "e": 5806, "s": 5308, "text": null }, { "code": null, "e": 6031, "s": 5806, "text": "Another pitfall is that you might be adding something into you collection object through loop and you can run out of memory. If you try and execute the below program, after some time, out of memory exception will be thrown. " }, { "code": null, "e": 6036, "s": 6031, "text": "Java" }, { "code": "//Java program for out of memory exception.import java.util.ArrayList;public class Integer1{ public static void main(String[] args) { ArrayList<Integer> ar = new ArrayList<>(); for (int i = 0; i < Integer.MAX_VALUE; i++) { ar.add(i); } }}", "e": 6323, "s": 6036, "text": null }, { "code": null, "e": 6331, "s": 6323, "text": "Output:" }, { "code": null, "e": 6679, "s": 6331, "text": "Exception in thread \"main\" java.lang.OutOfMemoryError: Java heap space\nat java.util.Arrays.copyOf(Unknown Source)\nat java.util.Arrays.copyOf(Unknown Source)\nat java.util.ArrayList.grow(Unknown Source)\nat java.util.ArrayList.ensureCapacityInternal(Unknown Source)\nat java.util.ArrayList.add(Unknown Source)\nat article.Integer1.main(Integer1.java:9)" }, { "code": null, "e": 7103, "s": 6679, "text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7117, "s": 7103, "text": "harshgundecha" }, { "code": null, "e": 7134, "s": 7117, "text": "punamsingh628700" }, { "code": null, "e": 7147, "s": 7134, "text": "simmytarika5" }, { "code": null, "e": 7159, "s": 7147, "text": "java-basics" }, { "code": null, "e": 7164, "s": 7159, "text": "Java" }, { "code": null, "e": 7183, "s": 7164, "text": "School Programming" }, { "code": null, "e": 7188, "s": 7183, "text": "Java" }, { "code": null, "e": 7286, "s": 7188, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7330, "s": 7286, "text": "Split() String method in Java with examples" }, { "code": null, "e": 7366, "s": 7330, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 7391, "s": 7366, "text": "Reverse a string in Java" }, { "code": null, "e": 7422, "s": 7391, "text": "How to iterate any Map in Java" }, { "code": null, "e": 7437, "s": 7422, "text": "Stream In Java" }, { "code": null, "e": 7455, "s": 7437, "text": "Python Dictionary" }, { "code": null, "e": 7480, "s": 7455, "text": "Reverse a string in Java" }, { "code": null, "e": 7496, "s": 7480, "text": "Arrays in C/C++" }, { "code": null, "e": 7519, "s": 7496, "text": "Introduction To PYTHON" } ]
Sum of Fibonacci Numbers with alternate negatives
06 May, 2021 Given a positive integer n, the task is to find the value of F1 – F2 + F3 -..........+ (-1)n+1Fn where Fi denotes i-th Fibonacci number.Fibonacci Numbers: The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .... In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1.Examples Input: n = 5 Output: 4 Explanation: 1 - 1 + 2 - 3 + 5 = 4 Input: n = 8 Output: -12 Explanation: 1 - 1 + 2 - 3 + 5 - 8 + 13 - 21 = -12 Method 1: (O(n) time Complexity) This method includes solving the problem directly by finding all Fibonacci numbers till n and adding up the alternating sum. But this will require O(n) time complexity.Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ Program to find alternate sum// of Fibonacci numbers #include <bits/stdc++.h>using namespace std; // Computes value of first fibonacci numbers// and stores their alternate sumint calculateAlternateSum(int n){ if (n <= 0) return 0; int fibo[n + 1]; fibo[0] = 0, fibo[1] = 1; // Initialize result int sum = pow(fibo[0], 2) + pow(fibo[1], 2); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum;} // Driver program to test above functionint main(){ // Get n int n = 8; // Find the alternating sum cout << "Alternating Fibonacci Sum upto " << n << " terms: " << calculateAlternateSum(n) << endl; return 0;} // Java Program to find alternate sum// of Fibonacci numbers public class GFG { //Computes value of first fibonacci numbers // and stores their alternate sum static double calculateAlternateSum(int n) { if (n <= 0) return 0; int fibo[] = new int [n + 1]; fibo[0] = 0; fibo[1] = 1; // Initialize result double sum = Math.pow(fibo[0], 2) + Math.pow(fibo[1], 2); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum; } // Driver code public static void main(String args[]) { // Get n int n = 8; // Find the alternating sum System.out.println("Alternating Fibonacci Sum upto " + n + " terms: " + calculateAlternateSum(n)); } // This Code is contributed by ANKITRAI1} # Python 3 Program to find alternate sum# of Fibonacci numbers # Computes value of first fibonacci numbers# and stores their alternate sumdef calculateAlternateSum(n): if (n <= 0): return 0 fibo = [0]*(n + 1) fibo[0] = 0 fibo[1] = 1 # Initialize result sum = pow(fibo[0], 2) + pow(fibo[1], 2) # Add remaining terms for i in range(2, n+1) : fibo[i] = fibo[i - 1] + fibo[i - 2] # For even terms if (i % 2 == 0): sum -= fibo[i] # For odd terms else: sum += fibo[i] # Return the alternating sum return sum # Driver program to test above functionif __name__ == "__main__": # Get n n = 8 # Find the alternating sum print( "Alternating Fibonacci Sum upto " , n ," terms: " , calculateAlternateSum(n)) # this code is contributed by# ChitraNayal // C# Program to find alternate sum// of Fibonacci numbersusing System; class GFG{ // Computes value of first fibonacci numbers// and stores their alternate sumstatic double calculateAlternateSum(int n){ if (n <= 0) return 0; int []fibo = new int [n + 1]; fibo[0] = 0; fibo[1] = 1; // Initialize result double sum = Math.Pow(fibo[0], 2) + Math.Pow(fibo[1], 2); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum;} // Driver codepublic static void Main(){ // Get n int n = 8; // Find the alternating sum Console.WriteLine("Alternating Fibonacci Sum upto " + n + " terms: " + calculateAlternateSum(n)); }} // This code is contributed by inder_verma <?php// PHP Program to find alternate sum// of Fibonacci numbers // Computes value of first fibonacci// numbers and stores their alternate sumfunction calculateAlternateSum($n){ if ($n <= 0) return 0; $fibo = array(); $fibo[0] = 0; $fibo[1] = 1; // Initialize result $sum = pow($fibo[0], 2) + pow($fibo[1], 2); // Add remaining terms for ($i = 2; $i <= $n; $i++) { $fibo[$i] = $fibo[$i - 1] + $fibo[$i - 2]; // For even terms if ($i % 2 == 0) $sum -= $fibo[$i]; // For odd terms else $sum += $fibo[$i]; } // Return the alternating sum return $sum;} // Driver Code // Get n$n = 8; // Find the alternating sumecho ("Alternating Fibonacci Sum upto ");echo $n ;echo " terms: ";echo (calculateAlternateSum($n)) ; // This code isw contributed// by Shivi_Aggarwal?> <script> // Javascript Program to find alternate sum// of Fibonacci numbers // Computes value of first fibonacci numbers // and stores their alternate sum function calculateAlternateSum(n) { if (n <= 0) return 0; var fibo = Array(n + 1).fill(0); fibo[0] = 0; fibo[1] = 1; // Initialize result var sum = Math.pow(fibo[0], 2) + Math.pow(fibo[1], 2); // Add remaining terms for (i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum; } // Driver code // Get n var n = 8; // Find the alternating sum document.write( "Alternating Fibonacci Sum upto " + n +" terms: " + calculateAlternateSum(n) ); // This code contributed by gauravrajput1 </script> Alternating Fibonacci Sum upto 8 terms: -12 Method 2: (O(log n) Complexity) This method involves the following observation to reduce the time complexity: For n = 2, F1 – F2 = 1 – 1 = 0 = 1 + (-1)3 * F1 For n = 3, F1 – F2 + F3 = 1 – 1 + 2 = 2 = 1 + (-1)4 * F2 For n = 4, F1 – F2 + F3 – F4 = 1 – 1 + 2 – 3 = -1 = 1 + (-1)5 * F3 For n = m, F1 – F2 + F3 -.......+ (-1)m+1 * Fm-1 = 1 + (-1)m+1Fm-1Assuming this to be true. Now if (n = m+1) is also true, it means that the assumption is correct. Otherwise, it is wrong. For n = m+1, F1 – F2 + F3 -.......+ (-1)m+1 * Fm + (-1)m+2 * Fm+1 = 1 + (-1)m+1 * Fm-1 + (-1)m+2 * Fm+1 = 1 + (-1)m+1(Fm-1 – Fm+1) = 1 + (-1)m+1(-Fm) = 1 + (-1)m+2(Fm)which is true as per the assumption for n = m. Hence the general term for the alternating Fibonacci Sum: F1 – F2 + F3 -.......+ (-1)n+1 Fn = 1 + (-1)n+1Fn-1 So in order to find an alternate sum, only the n-th Fibonacci term is to be found, which can be done in O(log n) time( Refer to Method 5 or 6 of this article.)Below is the implementation of method 6 of this: C++ Java Python3 C# Javascript // C++ Program to find alternate Fibonacci Sum in// O(Log n) time. #include <bits/stdc++.h>using namespace std; const int MAX = 1000; // Create an array for memoizationint f[MAX] = { 0 }; // Returns n'th Fibonacci number// using table f[]int fib(int n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; int k = (n & 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n];} // Computes value of Alternate Fibonacci Sumint calculateAlternateSum(int n){ if (n % 2 == 0) return (1 - fib(n - 1)); else return (1 + fib(n - 1));} // Driver program to test above functionint main(){ // Get n int n = 8; // Find the alternating sum cout << "Alternating Fibonacci Sum upto " << n << " terms : " << calculateAlternateSum(n) << endl; return 0;} // Java Program to find alternate// Fibonacci Sum in O(Log n) time.class GFG { static final int MAX = 1000; // Create an array for memoization static int f[] = new int[MAX]; // Returns n'th Fibonacci number // using table f[] static int fib(int n) { // Base cases if (n == 0) { return 0; } if (n == 1 || n == 2) { return (f[n] = 1); } // If fib(n) is already computed if (f[n] > 0) { return f[n]; } int k = (n % 2 == 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n % 2 == 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Computes value of Alternate Fibonacci Sum static int calculateAlternateSum(int n) { if (n % 2 == 0) { return (1 - fib(n - 1)); } else { return (1 + fib(n - 1)); } } // Driver program to test above function public static void main(String[] args) { // Get n int n = 8; // Find the alternating sum System.out.println("Alternating Fibonacci Sum upto " + n + " terms : " + calculateAlternateSum(n)); }}// This code is contributed by PrinciRaj1992 # Python3 program to find alternative# Fibonacci Sum in O(Log n) time.MAX = 1000 # List for memorizationf = [0] * MAX # Returns n'th fibonacci number# using table f[]def fib(n): # Base Cases if(n == 0): return(0) if(n == 1 or n == 2): f[n] = 1 return(f[n]) # If fib(n) is already computed if(f[n]): return(f[n]) if(n & 1): k = (n + 1) // 2 else: k = n // 2 # Applying above formula [Note value n&1 is 1 # if n is odd, else 0] if(n & 1): f[n] = (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) else: f[n] = (2 * fib(k-1) + fib(k)) * fib(k) return(f[n]) # Computes value of Alternate Fibonacci Sumdef cal(n): if(n % 2 == 0): return(1 - fib(n - 1)) else: return(1 + fib(n - 1)) # Driver Codeif(__name__=="__main__"): n = 8 print("Alternating Fibonacci Sum upto", n, "terms :", cal(n)) # This code is contributed by arjunsaini9081 // C# Program to find alternate// Fibonacci Sum in O(Log n) time.using System; class GFG{ static readonly int MAX = 1000; // Create an array for memoization static int []f = new int[MAX]; // Returns n'th Fibonacci number // using table f[] static int fib(int n) { // Base cases if (n == 0) { return 0; } if (n == 1 || n == 2) { return (f[n] = 1); } // If fib(n) is already computed if (f[n] > 0) { return f[n]; } int k = (n % 2 == 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n % 2 == 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Computes value of Alternate Fibonacci Sum static int calculateAlternateSum(int n) { if (n % 2 == 0) { return (1 - fib(n - 1)); } else { return (1 + fib(n - 1)); } } // Driver code public static void Main() { // Get n int n = 8; // Find the alternating sum Console.WriteLine("Alternating Fibonacci Sum upto " + n + " terms : " + calculateAlternateSum(n)); }} // This code is contributed by 29AjayKumar <script> //Javascript implementation of the approachMAX = 1000; // Create an array for memoizationf = new Array(MAX);f.fill(0);// Returns n'th Fibonacci number// using table f[]function fib( n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; var k = (n & 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n];}// Computes value of Alternate Fibonacci Sumfunction calculateAlternateSum(n){ if (n % 2 == 0) return (1 - fib(n - 1)); else return (1 + fib(n - 1));} // Get nvar n = 8;// Find the alternating sumdocument.write( "Alternating Fibonacci Sum upto "+ n + " terms : " + calculateAlternateSum(n) + "<br>"); getElement(a, n, S); // This code is contributed by SoumikMondal</script> Alternating Fibonacci Sum upto 8 terms: -12 ankthon inderDuMCA ukasp Shivi_Aggarwal princiraj1992 29AjayKumar Shivam_k arjunsaini9081 GauravRajput1 SoumikMondal Fibonacci series series-sum Technical Scripter 2018 Mathematical Mathematical series Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Merge two sorted arrays with O(1) extra space Segment Tree | Set 1 (Sum of given range) Fizz Buzz Implementation Check if a number is Palindrome Count ways to reach the n'th stair Product of Array except itself Find Union and Intersection of two unsorted arrays Median of two sorted arrays of same size
[ { "code": null, "e": 28, "s": 0, "text": "\n06 May, 2021" }, { "code": null, "e": 257, "s": 28, "text": "Given a positive integer n, the task is to find the value of F1 – F2 + F3 -..........+ (-1)n+1Fn where Fi denotes i-th Fibonacci number.Fibonacci Numbers: The Fibonacci numbers are the numbers in the following integer sequence. " }, { "code": null, "e": 308, "s": 257, "text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...." }, { "code": null, "e": 408, "s": 308, "text": "In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation " }, { "code": null, "e": 425, "s": 408, "text": "Fn = Fn-1 + Fn-2" }, { "code": null, "e": 471, "s": 425, "text": "with seed values F0 = 0 and F1 = 1.Examples " }, { "code": null, "e": 607, "s": 471, "text": "Input: n = 5\nOutput: 4\nExplanation: 1 - 1 + 2 - 3 + 5 = 4\n\nInput: n = 8\nOutput: -12\nExplanation: 1 - 1 + 2 - 3 + 5 - 8 + 13 - 21 = -12" }, { "code": null, "e": 861, "s": 607, "text": "Method 1: (O(n) time Complexity) This method includes solving the problem directly by finding all Fibonacci numbers till n and adding up the alternating sum. But this will require O(n) time complexity.Below is the implementation of the above approach: " }, { "code": null, "e": 865, "s": 861, "text": "C++" }, { "code": null, "e": 870, "s": 865, "text": "Java" }, { "code": null, "e": 879, "s": 870, "text": "Python 3" }, { "code": null, "e": 882, "s": 879, "text": "C#" }, { "code": null, "e": 886, "s": 882, "text": "PHP" }, { "code": null, "e": 897, "s": 886, "text": "Javascript" }, { "code": "// C++ Program to find alternate sum// of Fibonacci numbers #include <bits/stdc++.h>using namespace std; // Computes value of first fibonacci numbers// and stores their alternate sumint calculateAlternateSum(int n){ if (n <= 0) return 0; int fibo[n + 1]; fibo[0] = 0, fibo[1] = 1; // Initialize result int sum = pow(fibo[0], 2) + pow(fibo[1], 2); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum;} // Driver program to test above functionint main(){ // Get n int n = 8; // Find the alternating sum cout << \"Alternating Fibonacci Sum upto \" << n << \" terms: \" << calculateAlternateSum(n) << endl; return 0;}", "e": 1811, "s": 897, "text": null }, { "code": "// Java Program to find alternate sum// of Fibonacci numbers public class GFG { //Computes value of first fibonacci numbers // and stores their alternate sum static double calculateAlternateSum(int n) { if (n <= 0) return 0; int fibo[] = new int [n + 1]; fibo[0] = 0; fibo[1] = 1; // Initialize result double sum = Math.pow(fibo[0], 2) + Math.pow(fibo[1], 2); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum; } // Driver code public static void main(String args[]) { // Get n int n = 8; // Find the alternating sum System.out.println(\"Alternating Fibonacci Sum upto \" + n + \" terms: \" + calculateAlternateSum(n)); } // This Code is contributed by ANKITRAI1}", "e": 2973, "s": 1811, "text": null }, { "code": "# Python 3 Program to find alternate sum# of Fibonacci numbers # Computes value of first fibonacci numbers# and stores their alternate sumdef calculateAlternateSum(n): if (n <= 0): return 0 fibo = [0]*(n + 1) fibo[0] = 0 fibo[1] = 1 # Initialize result sum = pow(fibo[0], 2) + pow(fibo[1], 2) # Add remaining terms for i in range(2, n+1) : fibo[i] = fibo[i - 1] + fibo[i - 2] # For even terms if (i % 2 == 0): sum -= fibo[i] # For odd terms else: sum += fibo[i] # Return the alternating sum return sum # Driver program to test above functionif __name__ == \"__main__\": # Get n n = 8 # Find the alternating sum print( \"Alternating Fibonacci Sum upto \" , n ,\" terms: \" , calculateAlternateSum(n)) # this code is contributed by# ChitraNayal", "e": 3838, "s": 2973, "text": null }, { "code": "// C# Program to find alternate sum// of Fibonacci numbersusing System; class GFG{ // Computes value of first fibonacci numbers// and stores their alternate sumstatic double calculateAlternateSum(int n){ if (n <= 0) return 0; int []fibo = new int [n + 1]; fibo[0] = 0; fibo[1] = 1; // Initialize result double sum = Math.Pow(fibo[0], 2) + Math.Pow(fibo[1], 2); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum;} // Driver codepublic static void Main(){ // Get n int n = 8; // Find the alternating sum Console.WriteLine(\"Alternating Fibonacci Sum upto \" + n + \" terms: \" + calculateAlternateSum(n)); }} // This code is contributed by inder_verma", "e": 4804, "s": 3838, "text": null }, { "code": "<?php// PHP Program to find alternate sum// of Fibonacci numbers // Computes value of first fibonacci// numbers and stores their alternate sumfunction calculateAlternateSum($n){ if ($n <= 0) return 0; $fibo = array(); $fibo[0] = 0; $fibo[1] = 1; // Initialize result $sum = pow($fibo[0], 2) + pow($fibo[1], 2); // Add remaining terms for ($i = 2; $i <= $n; $i++) { $fibo[$i] = $fibo[$i - 1] + $fibo[$i - 2]; // For even terms if ($i % 2 == 0) $sum -= $fibo[$i]; // For odd terms else $sum += $fibo[$i]; } // Return the alternating sum return $sum;} // Driver Code // Get n$n = 8; // Find the alternating sumecho (\"Alternating Fibonacci Sum upto \");echo $n ;echo \" terms: \";echo (calculateAlternateSum($n)) ; // This code isw contributed// by Shivi_Aggarwal?>", "e": 5698, "s": 4804, "text": null }, { "code": "<script> // Javascript Program to find alternate sum// of Fibonacci numbers // Computes value of first fibonacci numbers // and stores their alternate sum function calculateAlternateSum(n) { if (n <= 0) return 0; var fibo = Array(n + 1).fill(0); fibo[0] = 0; fibo[1] = 1; // Initialize result var sum = Math.pow(fibo[0], 2) + Math.pow(fibo[1], 2); // Add remaining terms for (i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; // For even terms if (i % 2 == 0) sum -= fibo[i]; // For odd terms else sum += fibo[i]; } // Return the alternating sum return sum; } // Driver code // Get n var n = 8; // Find the alternating sum document.write( \"Alternating Fibonacci Sum upto \" + n +\" terms: \" + calculateAlternateSum(n) ); // This code contributed by gauravrajput1 </script>", "e": 6741, "s": 5698, "text": null }, { "code": null, "e": 6785, "s": 6741, "text": "Alternating Fibonacci Sum upto 8 terms: -12" }, { "code": null, "e": 6898, "s": 6787, "text": "Method 2: (O(log n) Complexity) This method involves the following observation to reduce the time complexity: " }, { "code": null, "e": 6946, "s": 6898, "text": "For n = 2, F1 – F2 = 1 – 1 = 0 = 1 + (-1)3 * F1" }, { "code": null, "e": 7003, "s": 6946, "text": "For n = 3, F1 – F2 + F3 = 1 – 1 + 2 = 2 = 1 + (-1)4 * F2" }, { "code": null, "e": 7070, "s": 7003, "text": "For n = 4, F1 – F2 + F3 – F4 = 1 – 1 + 2 – 3 = -1 = 1 + (-1)5 * F3" }, { "code": null, "e": 7258, "s": 7070, "text": "For n = m, F1 – F2 + F3 -.......+ (-1)m+1 * Fm-1 = 1 + (-1)m+1Fm-1Assuming this to be true. Now if (n = m+1) is also true, it means that the assumption is correct. Otherwise, it is wrong." }, { "code": null, "e": 7474, "s": 7258, "text": "For n = m+1, F1 – F2 + F3 -.......+ (-1)m+1 * Fm + (-1)m+2 * Fm+1 = 1 + (-1)m+1 * Fm-1 + (-1)m+2 * Fm+1 = 1 + (-1)m+1(Fm-1 – Fm+1) = 1 + (-1)m+1(-Fm) = 1 + (-1)m+2(Fm)which is true as per the assumption for n = m. " }, { "code": null, "e": 7533, "s": 7474, "text": "Hence the general term for the alternating Fibonacci Sum: " }, { "code": null, "e": 7585, "s": 7533, "text": "F1 – F2 + F3 -.......+ (-1)n+1 Fn = 1 + (-1)n+1Fn-1" }, { "code": null, "e": 7795, "s": 7585, "text": "So in order to find an alternate sum, only the n-th Fibonacci term is to be found, which can be done in O(log n) time( Refer to Method 5 or 6 of this article.)Below is the implementation of method 6 of this: " }, { "code": null, "e": 7799, "s": 7795, "text": "C++" }, { "code": null, "e": 7804, "s": 7799, "text": "Java" }, { "code": null, "e": 7812, "s": 7804, "text": "Python3" }, { "code": null, "e": 7815, "s": 7812, "text": "C#" }, { "code": null, "e": 7826, "s": 7815, "text": "Javascript" }, { "code": "// C++ Program to find alternate Fibonacci Sum in// O(Log n) time. #include <bits/stdc++.h>using namespace std; const int MAX = 1000; // Create an array for memoizationint f[MAX] = { 0 }; // Returns n'th Fibonacci number// using table f[]int fib(int n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; int k = (n & 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n];} // Computes value of Alternate Fibonacci Sumint calculateAlternateSum(int n){ if (n % 2 == 0) return (1 - fib(n - 1)); else return (1 + fib(n - 1));} // Driver program to test above functionint main(){ // Get n int n = 8; // Find the alternating sum cout << \"Alternating Fibonacci Sum upto \" << n << \" terms : \" << calculateAlternateSum(n) << endl; return 0;}", "e": 8926, "s": 7826, "text": null }, { "code": "// Java Program to find alternate// Fibonacci Sum in O(Log n) time.class GFG { static final int MAX = 1000; // Create an array for memoization static int f[] = new int[MAX]; // Returns n'th Fibonacci number // using table f[] static int fib(int n) { // Base cases if (n == 0) { return 0; } if (n == 1 || n == 2) { return (f[n] = 1); } // If fib(n) is already computed if (f[n] > 0) { return f[n]; } int k = (n % 2 == 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n % 2 == 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Computes value of Alternate Fibonacci Sum static int calculateAlternateSum(int n) { if (n % 2 == 0) { return (1 - fib(n - 1)); } else { return (1 + fib(n - 1)); } } // Driver program to test above function public static void main(String[] args) { // Get n int n = 8; // Find the alternating sum System.out.println(\"Alternating Fibonacci Sum upto \" + n + \" terms : \" + calculateAlternateSum(n)); }}// This code is contributed by PrinciRaj1992", "e": 10299, "s": 8926, "text": null }, { "code": "# Python3 program to find alternative# Fibonacci Sum in O(Log n) time.MAX = 1000 # List for memorizationf = [0] * MAX # Returns n'th fibonacci number# using table f[]def fib(n): # Base Cases if(n == 0): return(0) if(n == 1 or n == 2): f[n] = 1 return(f[n]) # If fib(n) is already computed if(f[n]): return(f[n]) if(n & 1): k = (n + 1) // 2 else: k = n // 2 # Applying above formula [Note value n&1 is 1 # if n is odd, else 0] if(n & 1): f[n] = (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) else: f[n] = (2 * fib(k-1) + fib(k)) * fib(k) return(f[n]) # Computes value of Alternate Fibonacci Sumdef cal(n): if(n % 2 == 0): return(1 - fib(n - 1)) else: return(1 + fib(n - 1)) # Driver Codeif(__name__==\"__main__\"): n = 8 print(\"Alternating Fibonacci Sum upto\", n, \"terms :\", cal(n)) # This code is contributed by arjunsaini9081", "e": 11292, "s": 10299, "text": null }, { "code": "// C# Program to find alternate// Fibonacci Sum in O(Log n) time.using System; class GFG{ static readonly int MAX = 1000; // Create an array for memoization static int []f = new int[MAX]; // Returns n'th Fibonacci number // using table f[] static int fib(int n) { // Base cases if (n == 0) { return 0; } if (n == 1 || n == 2) { return (f[n] = 1); } // If fib(n) is already computed if (f[n] > 0) { return f[n]; } int k = (n % 2 == 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n % 2 == 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Computes value of Alternate Fibonacci Sum static int calculateAlternateSum(int n) { if (n % 2 == 0) { return (1 - fib(n - 1)); } else { return (1 + fib(n - 1)); } } // Driver code public static void Main() { // Get n int n = 8; // Find the alternating sum Console.WriteLine(\"Alternating Fibonacci Sum upto \" + n + \" terms : \" + calculateAlternateSum(n)); }} // This code is contributed by 29AjayKumar", "e": 12715, "s": 11292, "text": null }, { "code": "<script> //Javascript implementation of the approachMAX = 1000; // Create an array for memoizationf = new Array(MAX);f.fill(0);// Returns n'th Fibonacci number// using table f[]function fib( n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; var k = (n & 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n];}// Computes value of Alternate Fibonacci Sumfunction calculateAlternateSum(n){ if (n % 2 == 0) return (1 - fib(n - 1)); else return (1 + fib(n - 1));} // Get nvar n = 8;// Find the alternating sumdocument.write( \"Alternating Fibonacci Sum upto \"+ n + \" terms : \" + calculateAlternateSum(n) + \"<br>\"); getElement(a, n, S); // This code is contributed by SoumikMondal</script>", "e": 13745, "s": 12715, "text": null }, { "code": null, "e": 13789, "s": 13745, "text": "Alternating Fibonacci Sum upto 8 terms: -12" }, { "code": null, "e": 13799, "s": 13791, "text": "ankthon" }, { "code": null, "e": 13810, "s": 13799, "text": "inderDuMCA" }, { "code": null, "e": 13816, "s": 13810, "text": "ukasp" }, { "code": null, "e": 13831, "s": 13816, "text": "Shivi_Aggarwal" }, { "code": null, "e": 13845, "s": 13831, "text": "princiraj1992" }, { "code": null, "e": 13857, "s": 13845, "text": "29AjayKumar" }, { "code": null, "e": 13866, "s": 13857, "text": "Shivam_k" }, { "code": null, "e": 13881, "s": 13866, "text": "arjunsaini9081" }, { "code": null, "e": 13895, "s": 13881, "text": "GauravRajput1" }, { "code": null, "e": 13908, "s": 13895, "text": "SoumikMondal" }, { "code": null, "e": 13918, "s": 13908, "text": "Fibonacci" }, { "code": null, "e": 13925, "s": 13918, "text": "series" }, { "code": null, "e": 13936, "s": 13925, "text": "series-sum" }, { "code": null, "e": 13960, "s": 13936, "text": "Technical Scripter 2018" }, { "code": null, "e": 13973, "s": 13960, "text": "Mathematical" }, { "code": null, "e": 13986, "s": 13973, "text": "Mathematical" }, { "code": null, "e": 13993, "s": 13986, "text": "series" }, { "code": null, "e": 14003, "s": 13993, "text": "Fibonacci" }, { "code": null, "e": 14101, "s": 14003, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14133, "s": 14101, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 14177, "s": 14133, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 14223, "s": 14177, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 14265, "s": 14223, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 14290, "s": 14265, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 14322, "s": 14290, "text": "Check if a number is Palindrome" }, { "code": null, "e": 14357, "s": 14322, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 14388, "s": 14357, "text": "Product of Array except itself" }, { "code": null, "e": 14439, "s": 14388, "text": "Find Union and Intersection of two unsorted arrays" } ]
SQL - Distinct Keyword
The SQL DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all the duplicate records and fetching only unique records. There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only those unique records instead of fetching duplicate records. The basic syntax of DISTINCT keyword to eliminate the duplicate records is as follows − SELECT DISTINCT column1, column2,.....columnN FROM table_name WHERE [condition] 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 | +----+----------+-----+-----------+----------+ First, let us see how the following SELECT query returns the duplicate salary records. SQL> SELECT SALARY FROM CUSTOMERS ORDER BY SALARY; This would produce the following result, where the salary (2000) is coming twice which is a duplicate record from the original table. +----------+ | SALARY | +----------+ | 1500.00 | | 2000.00 | | 2000.00 | | 4500.00 | | 6500.00 | | 8500.00 | | 10000.00 | +----------+ Now, let us use the DISTINCT keyword with the above SELECT query and then see the result. SQL> SELECT DISTINCT SALARY FROM CUSTOMERS ORDER BY SALARY; This would produce the following result where we do not have any duplicate entry. +----------+ | SALARY | +----------+ | 1500.00 | | 2000.00 | | 4500.00 | | 6500.00 | | 8500.00 | | 10000.00 |
[ { "code": null, "e": 2734, "s": 2587, "text": "The SQL DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all the duplicate records and fetching only unique records." }, { "code": null, "e": 2935, "s": 2734, "text": "There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only those unique records instead of fetching duplicate records." }, { "code": null, "e": 3023, "s": 2935, "text": "The basic syntax of DISTINCT keyword to eliminate the duplicate records is as follows −" }, { "code": null, "e": 3105, "s": 3023, "text": "SELECT DISTINCT column1, column2,.....columnN \nFROM table_name\nWHERE [condition]\n" }, { "code": null, "e": 3165, "s": 3105, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 3683, "s": 3165, "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+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 3770, "s": 3683, "text": "First, let us see how the following SELECT query returns the duplicate salary records." }, { "code": null, "e": 3824, "s": 3770, "text": "SQL> SELECT SALARY FROM CUSTOMERS\n ORDER BY SALARY;" }, { "code": null, "e": 3958, "s": 3824, "text": "This would produce the following result, where the salary (2000) is coming twice which is a duplicate record from the original table." }, { "code": null, "e": 4102, "s": 3958, "text": "+----------+\n| SALARY |\n+----------+\n| 1500.00 |\n| 2000.00 |\n| 2000.00 |\n| 4500.00 |\n| 6500.00 |\n| 8500.00 |\n| 10000.00 |\n+----------+\n" }, { "code": null, "e": 4192, "s": 4102, "text": "Now, let us use the DISTINCT keyword with the above SELECT query and then see the result." }, { "code": null, "e": 4255, "s": 4192, "text": "SQL> SELECT DISTINCT SALARY FROM CUSTOMERS\n ORDER BY SALARY;" }, { "code": null, "e": 4337, "s": 4255, "text": "This would produce the following result where we do not have any duplicate entry." } ]
Node.js NPM string-to-arraybuffer Module
02 Feb, 2022 NPM(Node Package Manager) is a package manager of Node.js packages. There is a NPM package called ‘shortid’ used to short non-sequential url-friendly unique ids. Command to install: npm install string-to-arraybuffer Syntax to import the package in local file const str2ab = require('string-to-arraybuffer') Syntax to convert string to an array buffer const arrBuff = str2Ab(string) Parameters : It takes one parameter ‘string’ that we wants to convert in array buffer. Example 1: This example illustrates how to use ‘string-to-arraybuffer to convert from string to array buffer. Filename – index.js : This file contains logic to convert string to array buffer. Javascript const express = require('express')const bodyParser = require('body-parser')const str2Ab =require('string-to-arraybuffer')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { const {str} = req.body // Converting from utf8 string to array buffer const arrBuffer = str2Ab(str) // Create view of array buffer const view = new Int8Array(arrBuffer) // Printing on console console.log(`Original string : ${str}\n`) console.log('ArrayBuffer :' + view)}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)}) Filename-form.js : This file contain logic to render the form. Javascript module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> String </label> </div> <input class='input' type='text' name='str' placeholder= 'string(plain text/base64/dataURI)' for='str'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `} Output: Submitting utf8(plain text) string to convert it to array buffer Response printed in command prompt when submitting the plain text(utf8) string Submitting base64 input string to convert it to array buffer Response printed in command prompt when submitting the base64 string Note: Look at the response in both cases, since the submitted string is same although in different form, their array buffer view is also same. Example 2: In this example we use both ‘string-to-arraybuffer’ and ‘arraybuffer-to-string’ to illustrates the transparency between them. we use plain text string here to convert it from one form to other form. Filename – index.js : This file contains logic to convert plain text string to array buffer and again decode it to plain text string. Javascript const express = require('express')const bodyParser = require('body-parser')const str2Ab = require('string-to-arraybuffer')const ab2Str = require('arraybuffer-to-string')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { const {str} = req.body // Converting from utf8 string to array buffer const arrBuffer = str2Ab(str) // Create view of array buffer const view = new Int8Array(arrBuffer) // Decode string from array buffer const decodedStr = ab2Str(arrBuffer) // Printing on console console.log(`Original string : ${str}\n`) console.log(`Array Buffer : ${view}\n`) console.log(`Decoded String: ${decodedStr}`)}) // Server set to runapp.listen(port, () => { console.log(`Server start on port ${port}`)}) Filename-form.js : This file contain logic to render the form. Javascript module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> Plain text string </label> </div> <input class='input' type='text' name='str' placeholder= 'plain text string' for='str'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `} Output: Submitting plain text string Response printed in command prompt when submitting the plain text string Example 3: In this example, we use both string-to-arraybuffer and arraybuffer-to-string to illustrates the transparency between them. we use base64 string here to convert it from one form to other form. Filename – index.js : This file contains logic to convert base64 string to array buffer and again decode it to base64 string. Javascript const express = require('express')const bodyParser = require('body-parser')const str2Ab = require('string-to-arraybuffer')const ab2Str = require('arraybuffer-to-string')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { const {str} = req.body // Converting from base64 string to array buffer const arrBuffer = str2Ab(str) // Create view of array buffer const view = new Int8Array(arrBuffer) // Decode base64 string from array buffer // using arraybuffer-to-string package const decodedStr = ab2Str(arrBuffer, 'base64') // Printing on console console.log(`Original string : ${str}\n`) console.log(`Array Buffer : ${view}\n`) console.log(`Decoded String: ${decodedStr}`)}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)}) Filename-form.js : This file contain logic to render the form. Javascript module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> Base64 string </label> </div> <input class='input' type='text' name='str' placeholder= 'base64 string' for='str'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `} Output: Submitting base64 string Response printed in command prompt when submitting the base64 string Note: We have used some Bulma classes in form.js file to design the content. mridulmanochagfg sagartomar9927 sweetyty Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Installation of Node.js on Windows 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Feb, 2022" }, { "code": null, "e": 190, "s": 28, "text": "NPM(Node Package Manager) is a package manager of Node.js packages. There is a NPM package called ‘shortid’ used to short non-sequential url-friendly unique ids." }, { "code": null, "e": 212, "s": 190, "text": "Command to install: " }, { "code": null, "e": 246, "s": 212, "text": "npm install string-to-arraybuffer" }, { "code": null, "e": 289, "s": 246, "text": "Syntax to import the package in local file" }, { "code": null, "e": 337, "s": 289, "text": "const str2ab = require('string-to-arraybuffer')" }, { "code": null, "e": 381, "s": 337, "text": "Syntax to convert string to an array buffer" }, { "code": null, "e": 412, "s": 381, "text": "const arrBuff = str2Ab(string)" }, { "code": null, "e": 499, "s": 412, "text": "Parameters : It takes one parameter ‘string’ that we wants to convert in array buffer." }, { "code": null, "e": 609, "s": 499, "text": "Example 1: This example illustrates how to use ‘string-to-arraybuffer to convert from string to array buffer." }, { "code": null, "e": 691, "s": 609, "text": "Filename – index.js : This file contains logic to convert string to array buffer." }, { "code": null, "e": 702, "s": 691, "text": "Javascript" }, { "code": "const express = require('express')const bodyParser = require('body-parser')const str2Ab =require('string-to-arraybuffer')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { const {str} = req.body // Converting from utf8 string to array buffer const arrBuffer = str2Ab(str) // Create view of array buffer const view = new Int8Array(arrBuffer) // Printing on console console.log(`Original string : ${str}\\n`) console.log('ArrayBuffer :' + view)}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})", "e": 1562, "s": 702, "text": null }, { "code": null, "e": 1625, "s": 1562, "text": "Filename-form.js : This file contain logic to render the form." }, { "code": null, "e": 1636, "s": 1625, "text": "Javascript" }, { "code": "module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> String </label> </div> <input class='input' type='text' name='str' placeholder= 'string(plain text/base64/dataURI)' for='str'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}", "e": 2547, "s": 1636, "text": null }, { "code": null, "e": 2555, "s": 2547, "text": "Output:" }, { "code": null, "e": 2620, "s": 2555, "text": "Submitting utf8(plain text) string to convert it to array buffer" }, { "code": null, "e": 2699, "s": 2620, "text": "Response printed in command prompt when submitting the plain text(utf8) string" }, { "code": null, "e": 2760, "s": 2699, "text": "Submitting base64 input string to convert it to array buffer" }, { "code": null, "e": 2829, "s": 2760, "text": "Response printed in command prompt when submitting the base64 string" }, { "code": null, "e": 2973, "s": 2829, "text": "Note: Look at the response in both cases, since the submitted string is same although in different form, their array buffer view is also same. " }, { "code": null, "e": 3184, "s": 2973, "text": "Example 2: In this example we use both ‘string-to-arraybuffer’ and ‘arraybuffer-to-string’ to illustrates the transparency between them. we use plain text string here to convert it from one form to other form." }, { "code": null, "e": 3318, "s": 3184, "text": "Filename – index.js : This file contains logic to convert plain text string to array buffer and again decode it to plain text string." }, { "code": null, "e": 3329, "s": 3318, "text": "Javascript" }, { "code": "const express = require('express')const bodyParser = require('body-parser')const str2Ab = require('string-to-arraybuffer')const ab2Str = require('arraybuffer-to-string')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { const {str} = req.body // Converting from utf8 string to array buffer const arrBuffer = str2Ab(str) // Create view of array buffer const view = new Int8Array(arrBuffer) // Decode string from array buffer const decodedStr = ab2Str(arrBuffer) // Printing on console console.log(`Original string : ${str}\\n`) console.log(`Array Buffer : ${view}\\n`) console.log(`Decoded String: ${decodedStr}`)}) // Server set to runapp.listen(port, () => { console.log(`Server start on port ${port}`)})", "e": 4367, "s": 3329, "text": null }, { "code": null, "e": 4430, "s": 4367, "text": "Filename-form.js : This file contain logic to render the form." }, { "code": null, "e": 4441, "s": 4430, "text": "Javascript" }, { "code": "module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> Plain text string </label> </div> <input class='input' type='text' name='str' placeholder= 'plain text string' for='str'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}", "e": 5334, "s": 4441, "text": null }, { "code": null, "e": 5342, "s": 5334, "text": "Output:" }, { "code": null, "e": 5371, "s": 5342, "text": "Submitting plain text string" }, { "code": null, "e": 5444, "s": 5371, "text": "Response printed in command prompt when submitting the plain text string" }, { "code": null, "e": 5647, "s": 5444, "text": "Example 3: In this example, we use both string-to-arraybuffer and arraybuffer-to-string to illustrates the transparency between them. we use base64 string here to convert it from one form to other form." }, { "code": null, "e": 5773, "s": 5647, "text": "Filename – index.js : This file contains logic to convert base64 string to array buffer and again decode it to base64 string." }, { "code": null, "e": 5784, "s": 5773, "text": "Javascript" }, { "code": "const express = require('express')const bodyParser = require('body-parser')const str2Ab = require('string-to-arraybuffer')const ab2Str = require('arraybuffer-to-string')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { const {str} = req.body // Converting from base64 string to array buffer const arrBuffer = str2Ab(str) // Create view of array buffer const view = new Int8Array(arrBuffer) // Decode base64 string from array buffer // using arraybuffer-to-string package const decodedStr = ab2Str(arrBuffer, 'base64') // Printing on console console.log(`Original string : ${str}\\n`) console.log(`Array Buffer : ${view}\\n`) console.log(`Decoded String: ${decodedStr}`)}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})", "e": 6876, "s": 5784, "text": null }, { "code": null, "e": 6939, "s": 6876, "text": "Filename-form.js : This file contain logic to render the form." }, { "code": null, "e": 6950, "s": 6939, "text": "Javascript" }, { "code": "module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> Base64 string </label> </div> <input class='input' type='text' name='str' placeholder= 'base64 string' for='str'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}", "e": 7837, "s": 6950, "text": null }, { "code": null, "e": 7845, "s": 7837, "text": "Output:" }, { "code": null, "e": 7870, "s": 7845, "text": "Submitting base64 string" }, { "code": null, "e": 7939, "s": 7870, "text": "Response printed in command prompt when submitting the base64 string" }, { "code": null, "e": 8017, "s": 7939, "text": "Note: We have used some Bulma classes in form.js file to design the content." }, { "code": null, "e": 8034, "s": 8017, "text": "mridulmanochagfg" }, { "code": null, "e": 8049, "s": 8034, "text": "sagartomar9927" }, { "code": null, "e": 8058, "s": 8049, "text": "sweetyty" }, { "code": null, "e": 8071, "s": 8058, "text": "Node.js-Misc" }, { "code": null, "e": 8079, "s": 8071, "text": "Node.js" }, { "code": null, "e": 8096, "s": 8079, "text": "Web Technologies" }, { "code": null, "e": 8194, "s": 8096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8251, "s": 8194, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 8305, "s": 8251, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 8345, "s": 8305, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 8377, "s": 8345, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 8412, "s": 8377, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 8474, "s": 8412, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8535, "s": 8474, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8585, "s": 8535, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 8628, "s": 8585, "text": "How to fetch data from an API in ReactJS ?" } ]
Java Program for Coin Change
19 Jan, 2018 Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn\’t matter. For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5. /* Dynamic Programming Java implementation of Coin Change problem */import java.util.Arrays; class CoinChange{ static long countWays(int S[], int m, int n) { // Time complexity of this function: O(mn) // table[i] will be storing the number of solutions // for value i. We need n+1 rows as the table is // constructed in bottom up manner using the base // case (n = 0) long[] table = new long[n+1]; // Initialize all table values as 0 Arrays.fill(table, 0); //O(n) // Base case (If given value is 0) table[0] = 1; // Pick all coins one by one and update the table[] // values after the index greater than or equal to // the value of the picked coin for (int i=0; i<m; i++) for (int j=S[i]; j<=n; j++) table[j] += table[j-S[i]]; return table[n]; } // Driver Function to test above function public static void main(String args[]) { int arr[] = {1, 2, 3}; int m = arr.length; int n = 4; System.out.println(countWays(arr, m, n)); }}// This code is contributed by Pankaj Kumar Please refer complete article on Dynamic Programming | Set 7 (Coin Change) for more details! dp-coin-change Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Java Program to Read a File to String Comparing two ArrayList In Java Java Program to Convert File to a Byte Array SHA-1 Hash Java Program to Find Sum of Array Elements
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jan, 2018" }, { "code": null, "e": 258, "s": 52, "text": "Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn\\’t matter." }, { "code": null, "e": 516, "s": 258, "text": "For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5." }, { "code": "/* Dynamic Programming Java implementation of Coin Change problem */import java.util.Arrays; class CoinChange{ static long countWays(int S[], int m, int n) { // Time complexity of this function: O(mn) // table[i] will be storing the number of solutions // for value i. We need n+1 rows as the table is // constructed in bottom up manner using the base // case (n = 0) long[] table = new long[n+1]; // Initialize all table values as 0 Arrays.fill(table, 0); //O(n) // Base case (If given value is 0) table[0] = 1; // Pick all coins one by one and update the table[] // values after the index greater than or equal to // the value of the picked coin for (int i=0; i<m; i++) for (int j=S[i]; j<=n; j++) table[j] += table[j-S[i]]; return table[n]; } // Driver Function to test above function public static void main(String args[]) { int arr[] = {1, 2, 3}; int m = arr.length; int n = 4; System.out.println(countWays(arr, m, n)); }}// This code is contributed by Pankaj Kumar", "e": 1684, "s": 516, "text": null }, { "code": null, "e": 1777, "s": 1684, "text": "Please refer complete article on Dynamic Programming | Set 7 (Coin Change) for more details!" }, { "code": null, "e": 1792, "s": 1777, "text": "dp-coin-change" }, { "code": null, "e": 1806, "s": 1792, "text": "Java Programs" }, { "code": null, "e": 1904, "s": 1806, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1952, "s": 1904, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 1991, "s": 1952, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 2042, "s": 1991, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 2076, "s": 2042, "text": "Java Program to Write into a File" }, { "code": null, "e": 2123, "s": 2076, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 2161, "s": 2123, "text": "Java Program to Read a File to String" }, { "code": null, "e": 2193, "s": 2161, "text": "Comparing two ArrayList In Java" }, { "code": null, "e": 2238, "s": 2193, "text": "Java Program to Convert File to a Byte Array" }, { "code": null, "e": 2249, "s": 2238, "text": "SHA-1 Hash" } ]
Difference between an id and class in HTML?
29 Jul, 2021 HTML id Attribute: The id attribute is a unique identifier which is used to specify the document. It is used by CSS and JavaScript to perform a certain task for a unique element. In CSS, the id attribute is written using # symbol followed by id.Syntax: <element id="id_name"> In CSS Stylesheet: #id_name { // CSS Property } Example: html <!DOCTYPE html><html> <head> <title> HTML id attribute </title> <style> #geeks{ color:green; font-size:25px; } </style></head> <body style="text-align:center"> <h1>Geeks for Geeks</h1> <p id="geeks">Welcome to Geeks for Geeks</p> <p>A Computer Science portal for geeks</p> </body> </html> Output: HTML class Attribute: The class attribute is used to specify one or more class names for an HTML element. The class attribute can be used on any HTML element. The class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. The class name in CSS stylesheet using “.” symbol.Syntax: <element class="class_name"> In CSS Stylesheet: .class { // CSS Property } Example: html <!DOCTYPE html><html> <head> <style> .geeks{ color:green; font-size:25px; } </style></head> <body style="text-align:center;"> <h1>Geeks for Geeks</h1> <p> Welcome to Geeks for Geeks</p> <p class="geeks"> A Computer Science portal for geeks </p> </body> </html> Output: Difference between id and class attribute: The only difference between them is that “id” is unique in a page and can only apply to at most one element, while “class” selector can apply to multiple elements. HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. trehanshanya23 Picked HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Jul, 2021" }, { "code": null, "e": 308, "s": 53, "text": "HTML id Attribute: The id attribute is a unique identifier which is used to specify the document. It is used by CSS and JavaScript to perform a certain task for a unique element. In CSS, the id attribute is written using # symbol followed by id.Syntax: " }, { "code": null, "e": 384, "s": 308, "text": "<element id=\"id_name\">\n\nIn CSS Stylesheet:\n#id_name {\n // CSS Property\n}" }, { "code": null, "e": 395, "s": 384, "text": "Example: " }, { "code": null, "e": 400, "s": 395, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML id attribute </title> <style> #geeks{ color:green; font-size:25px; } </style></head> <body style=\"text-align:center\"> <h1>Geeks for Geeks</h1> <p id=\"geeks\">Welcome to Geeks for Geeks</p> <p>A Computer Science portal for geeks</p> </body> </html> ", "e": 787, "s": 400, "text": null }, { "code": null, "e": 797, "s": 787, "text": "Output: " }, { "code": null, "e": 1134, "s": 797, "text": "HTML class Attribute: The class attribute is used to specify one or more class names for an HTML element. The class attribute can be used on any HTML element. The class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. The class name in CSS stylesheet using “.” symbol.Syntax: " }, { "code": null, "e": 1214, "s": 1134, "text": "<element class=\"class_name\">\n\nIn CSS Stylesheet:\n.class {\n // CSS Property\n}" }, { "code": null, "e": 1225, "s": 1214, "text": "Example: " }, { "code": null, "e": 1230, "s": 1225, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> .geeks{ color:green; font-size:25px; } </style></head> <body style=\"text-align:center;\"> <h1>Geeks for Geeks</h1> <p> Welcome to Geeks for Geeks</p> <p class=\"geeks\"> A Computer Science portal for geeks </p> </body> </html> ", "e": 1580, "s": 1230, "text": null }, { "code": null, "e": 1590, "s": 1580, "text": "Output: " }, { "code": null, "e": 1799, "s": 1590, "text": "Difference between id and class attribute: The only difference between them is that “id” is unique in a page and can only apply to at most one element, while “class” selector can apply to multiple elements. " }, { "code": null, "e": 1993, "s": 1799, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 2008, "s": 1993, "text": "trehanshanya23" }, { "code": null, "e": 2015, "s": 2008, "text": "Picked" }, { "code": null, "e": 2020, "s": 2015, "text": "HTML" }, { "code": null, "e": 2037, "s": 2020, "text": "Web Technologies" }, { "code": null, "e": 2064, "s": 2037, "text": "Web technologies Questions" }, { "code": null, "e": 2069, "s": 2064, "text": "HTML" }, { "code": null, "e": 2167, "s": 2069, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2215, "s": 2167, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2239, "s": 2215, "text": "REST API (Introduction)" }, { "code": null, "e": 2289, "s": 2239, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2326, "s": 2289, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2365, "s": 2326, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2398, "s": 2365, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2459, "s": 2398, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2502, "s": 2459, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2574, "s": 2502, "text": "Differences between Functional Components and Class Components in React" } ]
send_keys method – Action Chains in Selenium Python
15 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around send_keys method on Action Chains in Python Selenium. send_keys method is used to send keys to current focused element. Syntax – send_keys(*keys_to_send) Example – <input type ="text" name ="passwd" id ="passwd-id" /> To find an element one needs to use one of the locating strategies, For example, element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd") Now one can use send_keys method as an Action chain as below – action.click(on_element=element) action.send_keys("Arrays") To demonstrate, send_keys method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element. Program – # import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_class_name("gsc-input") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # send keysaction.send_keys("Arrays") # perform the operationaction.perform() Output – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Introduction To PYTHON Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n15 May, 2020" }, { "code": null, "e": 600, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around send_keys method on Action Chains in Python Selenium. send_keys method is used to send keys to current focused element." }, { "code": null, "e": 609, "s": 600, "text": "Syntax –" }, { "code": null, "e": 634, "s": 609, "text": "send_keys(*keys_to_send)" }, { "code": null, "e": 644, "s": 634, "text": "Example –" }, { "code": "<input type =\"text\" name =\"passwd\" id =\"passwd-id\" />", "e": 698, "s": 644, "text": null }, { "code": null, "e": 779, "s": 698, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": "element = driver.find_element_by_id(\"passwd-id\")element = driver.find_element_by_name(\"passwd\")", "e": 875, "s": 779, "text": null }, { "code": null, "e": 938, "s": 875, "text": "Now one can use send_keys method as an Action chain as below –" }, { "code": null, "e": 999, "s": 938, "text": "action.click(on_element=element)\naction.send_keys(\"Arrays\")\n" }, { "code": null, "e": 1140, "s": 999, "text": "To demonstrate, send_keys method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element." }, { "code": null, "e": 1150, "s": 1140, "text": "Program –" }, { "code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_class_name(\"gsc-input\") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # send keysaction.send_keys(\"Arrays\") # perform the operationaction.perform()", "e": 1675, "s": 1150, "text": null }, { "code": null, "e": 1684, "s": 1675, "text": "Output –" }, { "code": null, "e": 1700, "s": 1684, "text": "Python-selenium" }, { "code": null, "e": 1709, "s": 1700, "text": "selenium" }, { "code": null, "e": 1716, "s": 1709, "text": "Python" }, { "code": null, "e": 1814, "s": 1716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1832, "s": 1814, "text": "Python Dictionary" }, { "code": null, "e": 1874, "s": 1832, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1896, "s": 1874, "text": "Enumerate() in Python" }, { "code": null, "e": 1922, "s": 1896, "text": "Python String | replace()" }, { "code": null, "e": 1954, "s": 1922, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1983, "s": 1954, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2010, "s": 1983, "text": "Python Classes and Objects" }, { "code": null, "e": 2033, "s": 2010, "text": "Introduction To PYTHON" }, { "code": null, "e": 2054, "s": 2033, "text": "Python OOPs Concepts" } ]
How to close child browser window in Selenium WebDriver using Java?
We can close the child browser window in Selenium webdriver. The getWindowHandles and getWindowHandle methods can be used to handle child windows. The getWindowHandles method is used to store all the opened window handles in the Set data structure. The getWindowHandle method is used to store the browser window currently active. To iterate over the window handles, the iterator method is used. We have to add import java.util.Set to accommodate Set and import java.util.List and import java.util.Iterator statements to accommodate iterator in our code. By default, the driver object can access the elements of the parent window. In order to switch its focus from the parent to the child window, we shall take the help of the switchTo().window method and pass the window handle id of the child window as an argument to the method. Then to move from the child window to the parent window, we shall take the help of the switchTo().window method and pass the parent window handle id as an argument to the method. Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; import java.util.Set; import java.util.Iterator; public class CloseChildWindow { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://secure.indeed.com/account/login"); //implicit wait driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); driver.findElement(By.id("login-google-button")).click(); // window handles Set w = driver.getWindowHandles(); // window handles iterate Iterator t = w.iterator(); String ch = t.next(); String pw = t.next(); // switching child window driver.switchTo().window(ch); System.out.println("Child window title "+ driver.getTitle()); // close the child browser window driver.close(); // switching parent window driver.switchTo().window(pw); System.out.println("Parent window title: "+ driver.getTitle()); driver.quit();
[ { "code": null, "e": 1436, "s": 1187, "text": "We can close the child browser window in Selenium webdriver. The getWindowHandles and getWindowHandle methods can be used to handle child windows. The getWindowHandles method is used to store all the opened window handles in the Set data structure." }, { "code": null, "e": 1741, "s": 1436, "text": "The getWindowHandle method is used to store the browser window currently active. To iterate over the window handles, the iterator method is used. We have to add import java.util.Set to accommodate Set and import java.util.List and import java.util.Iterator statements to accommodate iterator in our code." }, { "code": null, "e": 2197, "s": 1741, "text": "By default, the driver object can access the elements of the parent window. In order to switch its focus from the parent to the child window, we shall take the help of the switchTo().window method and pass the window handle id of the child window as an argument to the method. Then to move from the child window to the parent window, we shall take the help of the switchTo().window method and pass the parent window handle id as an argument to the method." }, { "code": null, "e": 2218, "s": 2197, "text": "Code Implementation." }, { "code": null, "e": 3474, "s": 2218, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Iterator;\npublic class CloseChildWindow {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://secure.indeed.com/account/login\");\n //implicit wait\n driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);\n driver.findElement(By.id(\"login-google-button\")).click();\n // window handles\n Set w = driver.getWindowHandles();\n // window handles iterate\n Iterator t = w.iterator();\n String ch = t.next();\n String pw = t.next();\n // switching child window\n driver.switchTo().window(ch);\n System.out.println(\"Child window title \"+ driver.getTitle());\n // close the child browser window\n driver.close();\n // switching parent window\n driver.switchTo().window(pw);\n System.out.println(\"Parent window title: \"+ driver.getTitle());\n driver.quit();" } ]
turtle.pen() function in Python
24 Dec, 2021 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This function is used to return or set the pen’s attributes in a ‘pen-dictionary’ with the following key/value pairs: “shown” : True/False “pendown” : True/False “pencolor” : color-string or color-tuple “fillcolor” : color-string or color-tuple “pensize” : positive number “speed” : number in range 0..10 “resizemode” : “auto” or “user” or “noresize” “stretchfactor”: (positive number, positive number) “shearfactor” : number “outline” : positive number “tilt” : number This dictionary can be used as an argument for a subsequent pen()-call to restore the former pen-state. Moreover, one or more of these attributes can be provided as keyword-arguments. This can be used to set several pen attributes in one statement. Syntax : turtle.pen(pen=None, **pendict) Parameters: pen : a dictionary with some or all of the below listed keys. **pendict : one or more keyword-arguments with the below listed keys as keywords. Below is the implementation of the above method with some examples : Example 1 : Python3 # import packageimport turtle # check default valuesprint(turtle.pen()) Output : {‘shown’: True, ‘pendown’: True, ‘pencolor’: ‘black’, ‘fillcolor’: ‘black’, ‘pensize’: 1, ‘speed’: 3, ‘resizemode’: ‘noresize’, ‘stretchfactor’: (1.0, 1.0), ‘shearfactor’: 0.0, ‘outline’: 1, ’tilt’: 0.0} Example 2 : Python3 # import packageimport turtle # check default to compareprint(turtle.pen()) # update with some inputsturtle.pen(pencolor="red", outline=2) # again checkprint(turtle.pen()) Output : {‘shown’: True, ‘pendown’: True, ‘pencolor’: ‘black’, ‘fillcolor’: ‘black’, ‘pensize’: 1, ‘speed’: 3, ‘resizemode’: ‘noresize’, ‘stretchfactor’: (1.0, 1.0), ‘shearfactor’: 0.0, ‘outline’: 1, ’tilt’: 0.0} {‘shown’: True, ‘pendown’: True, ‘pencolor’: ‘red’, ‘fillcolor’: ‘black’, ‘pensize’: 1, ‘speed’: 3, ‘resizemode’: ‘noresize’, ‘stretchfactor’: (1.0, 1.0), ‘shearfactor’: 0.0, ‘outline’: 2, ’tilt’: 0.0} simmytarika5 Python-turtle 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": "\n24 Dec, 2021" }, { "code": null, "e": 245, "s": 28, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 363, "s": 245, "text": "This function is used to return or set the pen’s attributes in a ‘pen-dictionary’ with the following key/value pairs:" }, { "code": null, "e": 384, "s": 363, "text": "“shown” : True/False" }, { "code": null, "e": 407, "s": 384, "text": "“pendown” : True/False" }, { "code": null, "e": 448, "s": 407, "text": "“pencolor” : color-string or color-tuple" }, { "code": null, "e": 490, "s": 448, "text": "“fillcolor” : color-string or color-tuple" }, { "code": null, "e": 518, "s": 490, "text": "“pensize” : positive number" }, { "code": null, "e": 550, "s": 518, "text": "“speed” : number in range 0..10" }, { "code": null, "e": 596, "s": 550, "text": "“resizemode” : “auto” or “user” or “noresize”" }, { "code": null, "e": 648, "s": 596, "text": "“stretchfactor”: (positive number, positive number)" }, { "code": null, "e": 671, "s": 648, "text": "“shearfactor” : number" }, { "code": null, "e": 699, "s": 671, "text": "“outline” : positive number" }, { "code": null, "e": 715, "s": 699, "text": "“tilt” : number" }, { "code": null, "e": 964, "s": 715, "text": "This dictionary can be used as an argument for a subsequent pen()-call to restore the former pen-state. Moreover, one or more of these attributes can be provided as keyword-arguments. This can be used to set several pen attributes in one statement." }, { "code": null, "e": 1006, "s": 964, "text": "Syntax : turtle.pen(pen=None, **pendict) " }, { "code": null, "e": 1018, "s": 1006, "text": "Parameters:" }, { "code": null, "e": 1080, "s": 1018, "text": "pen : a dictionary with some or all of the below listed keys." }, { "code": null, "e": 1162, "s": 1080, "text": "**pendict : one or more keyword-arguments with the below listed keys as keywords." }, { "code": null, "e": 1231, "s": 1162, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 1243, "s": 1231, "text": "Example 1 :" }, { "code": null, "e": 1251, "s": 1243, "text": "Python3" }, { "code": "# import packageimport turtle # check default valuesprint(turtle.pen())", "e": 1323, "s": 1251, "text": null }, { "code": null, "e": 1333, "s": 1323, "text": "Output : " }, { "code": null, "e": 1538, "s": 1333, "text": "{‘shown’: True, ‘pendown’: True, ‘pencolor’: ‘black’, ‘fillcolor’: ‘black’, ‘pensize’: 1, ‘speed’: 3, ‘resizemode’: ‘noresize’, ‘stretchfactor’: (1.0, 1.0), ‘shearfactor’: 0.0, ‘outline’: 1, ’tilt’: 0.0} " }, { "code": null, "e": 1550, "s": 1538, "text": "Example 2 :" }, { "code": null, "e": 1558, "s": 1550, "text": "Python3" }, { "code": "# import packageimport turtle # check default to compareprint(turtle.pen()) # update with some inputsturtle.pen(pencolor=\"red\", outline=2) # again checkprint(turtle.pen())", "e": 1730, "s": 1558, "text": null }, { "code": null, "e": 1739, "s": 1730, "text": "Output :" }, { "code": null, "e": 2146, "s": 1739, "text": "{‘shown’: True, ‘pendown’: True, ‘pencolor’: ‘black’, ‘fillcolor’: ‘black’, ‘pensize’: 1, ‘speed’: 3, ‘resizemode’: ‘noresize’, ‘stretchfactor’: (1.0, 1.0), ‘shearfactor’: 0.0, ‘outline’: 1, ’tilt’: 0.0} {‘shown’: True, ‘pendown’: True, ‘pencolor’: ‘red’, ‘fillcolor’: ‘black’, ‘pensize’: 1, ‘speed’: 3, ‘resizemode’: ‘noresize’, ‘stretchfactor’: (1.0, 1.0), ‘shearfactor’: 0.0, ‘outline’: 2, ’tilt’: 0.0} " }, { "code": null, "e": 2159, "s": 2146, "text": "simmytarika5" }, { "code": null, "e": 2173, "s": 2159, "text": "Python-turtle" }, { "code": null, "e": 2180, "s": 2173, "text": "Python" }, { "code": null, "e": 2278, "s": 2180, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2310, "s": 2278, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2337, "s": 2310, "text": "Python Classes and Objects" }, { "code": null, "e": 2358, "s": 2337, "text": "Python OOPs Concepts" }, { "code": null, "e": 2381, "s": 2358, "text": "Introduction To PYTHON" }, { "code": null, "e": 2412, "s": 2381, "text": "Python | os.path.join() method" }, { "code": null, "e": 2468, "s": 2412, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2510, "s": 2468, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2552, "s": 2510, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2591, "s": 2552, "text": "Python | Get unique values from a list" } ]
Number of Longest Increasing Subsequences
09 Jun, 2021 Given an array arr[] of size N, the task is to count the number of longest increasing subsequences present in the given array. Examples: Input: arr[] = {2, 2, 2, 2, 2}Output: 5Explanation: The length of the longest increasing subsequence is 1, i.e. {2}. Therefore, count of longest increasing subsequences of length 1 is 5. Input: arr[] = {1, 3, 5, 4, 7}Output: 2Explanation: The length of the longest increasing subsequence is 4, and there are 2 longest increasing subsequences of length 4, i.e. {1, 3, 4, 7} and {1, 3, 5, 7}. Naive Approach: The simplest approach is to generate all possible subsequences present in the given array arr[] and count the increasing subsequences of maximum length. Print the count after checking all subsequences. Time Complexity: O(N*2N)Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming as the above problem has overlapping subproblems that need to be calculated more than once, and to reduce that calculation use tabulation or memoization. Follow the steps below to solve the problem: Initialize two arrays dp_l[] and dp_c[] to store the length of the longest increasing subsequences and the count of the longest increasing subsequence at each index respectively. Iterate over the range [1, N – 1] using the variable i:Iterate over the range [0, i – 1] using the variable j:If arr[i] > arr[j] then check for the following cases: ~ If (dp_l[j]+1) greater than dp_l[i], then update dp_l[i] as dp_l[j] + 1 and dp_c[i] as dp_c[j] ~ Else if (dp_l[j] + 1) is the same as dp_l[i], then update dp_c[i] as dp_c[i] + dp_c[j]. Iterate over the range [0, i – 1] using the variable j:If arr[i] > arr[j] then check for the following cases: ~ If (dp_l[j]+1) greater than dp_l[i], then update dp_l[i] as dp_l[j] + 1 and dp_c[i] as dp_c[j] ~ Else if (dp_l[j] + 1) is the same as dp_l[i], then update dp_c[i] as dp_c[i] + dp_c[j]. If arr[i] > arr[j] then check for the following cases: ~ If (dp_l[j]+1) greater than dp_l[i], then update dp_l[i] as dp_l[j] + 1 and dp_c[i] as dp_c[j] ~ Else if (dp_l[j] + 1) is the same as dp_l[i], then update dp_c[i] as dp_c[i] + dp_c[j]. Find the maximum element in the array dp_l[] and store it in a variable max_length that will give the length of LIS. Initialize a variable count with 0 to store the number of the longest increasing subsequence. Traverse the array dp_l[] and if at any index idx, dp_l[idx] is the same as max_length then increment the count by dp_c[idx]. After the above steps, print the value of count, which is the number of longest increasing subsequences in the given array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the// above approach#include <bits/stdc++.h>using namespace std; //Function to count the number// of LIS in the array nums[]int findNumberOfLIS(vector<int> nums){ //Base Case if (nums.size() == 0) return 0; int n = nums.size(); //Initialize dp_l array with // 1s vector<int> dp_l(n, 1); //Initialize dp_c array with // 1s vector<int> dp_c(n, 1); for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { //If current element is // smaller if (nums[i] <= nums[j]) continue; if (dp_l[j] + 1 > dp_l[i]) { dp_l[i] = dp_l[j] + 1; dp_c[i] = dp_c[j]; } else if (dp_l[j] + 1 == dp_l[i]) dp_c[i] += dp_c[j]; } } //Store the maximum element // from dp_l int max_length = 0; for (int i : dp_l) max_length = max(i,max_length); //Stores the count of LIS int count = 0; //Traverse dp_l and dp_c // simultaneously for(int i = 0; i < n; i++) { //Update the count if (dp_l[i] == max_length) count += dp_c[i]; } //Return the count of LIS return count;} //Driver codeint main(){ //Given array arr[] vector<int> arr = {1, 3, 5, 4, 7}; //Function Call cout << findNumberOfLIS(arr) << endl;} // This code is contributed by Mohit Kumar 29 // Java program for the// above approachimport java.util.*; class GFG{ // Function to count the number// of LIS in the array nums[]static int findNumberOfLIS(int[] nums){ // Base Case if (nums.length == 0) return 0; int n = nums.length; // Initialize dp_l array with // 1s int[] dp_l = new int[n]; Arrays.fill(dp_l, 1); // Initialize dp_c array with // 1s int[] dp_c = new int[n]; Arrays.fill(dp_c, 1); for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { // If current element is // smaller if (nums[i] <= nums[j]) continue; if (dp_l[j] + 1 > dp_l[i]) { dp_l[i] = dp_l[j] + 1; dp_c[i] = dp_c[j]; } else if (dp_l[j] + 1 == dp_l[i]) dp_c[i] += dp_c[j]; } } // Store the maximum element // from dp_l int max_length = 0; for(int i : dp_l) max_length = Math.max(i, max_length); // Stores the count of LIS int count = 0; // Traverse dp_l and dp_c // simultaneously for(int i = 0; i < n; i++) { // Update the count if (dp_l[i] == max_length) count += dp_c[i]; } // Return the count of LIS return count;} // Driver codepublic static void main(String[] args){ // Given array arr[] int[] arr = { 1, 3, 5, 4, 7 }; // Function Call System.out.print(findNumberOfLIS(arr) + "\n");}} // This code is contributed by shikhasingrajput # Python3 program for the above approach # Function to count the number of LIS# in the array nums[]def findNumberOfLIS(nums): # Base Case if not nums: return 0 n = len(nums) # Initialize dp_l array with 1s dp_l = [1] * n # Initialize dp_c array with 1s dp_c = [1] * n for i, num in enumerate(nums): for j in range(i): # If current element is smaller if nums[i] <= nums[j]: continue # Otherwise if dp_l[j] + 1 > dp_l[i]: dp_l[i] = dp_l[j] + 1 dp_c[i] = dp_c[j] elif dp_l[j] + 1 == dp_l[i]: dp_c[i] += dp_c[j] # Store the maximum element from dp_l max_length = max(x for x in dp_l) # Stores the count of LIS count = 0 # Traverse dp_l and dp_c simultaneously for l, c in zip(dp_l, dp_c): # Update the count if l == max_length: count += c # Return the count of LIS return count # Driver Code # Given array arr[]arr = [1, 3, 5, 4, 7] # Function Callprint(findNumberOfLIS(arr)) // C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG { // Function to count the number // of LIS in the array nums[] static int findNumberOfLIS(int[] nums) { // Base Case if (nums.Length == 0) return 0; int n = nums.Length; // Initialize dp_l array with // 1s int[] dp_l = new int[n]; Array.Fill(dp_l, 1); // Initialize dp_c array with // 1s int[] dp_c = new int[n]; Array.Fill(dp_c, 1); for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { // If current element is // smaller if (nums[i] <= nums[j]) continue; if (dp_l[j] + 1 > dp_l[i]) { dp_l[i] = dp_l[j] + 1; dp_c[i] = dp_c[j]; } else if (dp_l[j] + 1 == dp_l[i]) dp_c[i] += dp_c[j]; } } // Store the maximum element // from dp_l int max_length = 0; foreach(int i in dp_l) max_length = Math.Max(i, max_length); // Stores the count of LIS int count = 0; // Traverse dp_l and dp_c // simultaneously for(int i = 0; i < n; i++) { // Update the count if (dp_l[i] == max_length) count += dp_c[i]; } // Return the count of LIS return count; } // Driver code static void Main() { // Given array arr[] int[] arr = { 1, 3, 5, 4, 7 }; // Function Call Console.WriteLine(findNumberOfLIS(arr)); }} // This code is contributed by divyeshrabadiya07 <script> // Javascript program for the// above approach // Function to count the number// of LIS in the array nums[]function findNumberOfLIS(nums){ //Base Case if (nums.length == 0) return 0; var n = nums.length; // Initialize dp_l array with // 1s var dp_l = Array(n).fill(1); // Initialize dp_c array with // 1s var dp_c = Array(n).fill(1); for (var i = 0; i < n; i++) { for (var j = 0; j < i; j++) { // If current element is // smaller if (nums[i] <= nums[j]) continue; if (dp_l[j] + 1 > dp_l[i]) { dp_l[i] = dp_l[j] + 1; dp_c[i] = dp_c[j]; } else if (dp_l[j] + 1 == dp_l[i]) dp_c[i] += dp_c[j]; } } // Store the maximum element // from dp_l var max_length = 0; dp_l.forEach(i => { max_length = Math.max(i,max_length); }); // Stores the count of LIS var count = 0; //Traverse dp_l and dp_c // simultaneously for(var i = 0; i < n; i++) { // Update the count if (dp_l[i] == max_length) count += dp_c[i]; } // Return the count of LIS return count;} // Driver code// Given array arr[]var arr = [1, 3, 5, 4, 7]; // Function Calldocument.write( findNumberOfLIS(arr)); // This code is contributed by rutvik_56.</script> 2 Time Complexity: O(N2)Auxiliary Space: O(N) mohit kumar 29 shikhasingrajput divyeshrabadiya07 tridib_samanta rutvik_56 LIS Memoization subsequence Arrays Dynamic Programming Recursion Arrays Dynamic Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Introduction to Arrays Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2021" }, { "code": null, "e": 181, "s": 54, "text": "Given an array arr[] of size N, the task is to count the number of longest increasing subsequences present in the given array." }, { "code": null, "e": 191, "s": 181, "text": "Examples:" }, { "code": null, "e": 378, "s": 191, "text": "Input: arr[] = {2, 2, 2, 2, 2}Output: 5Explanation: The length of the longest increasing subsequence is 1, i.e. {2}. Therefore, count of longest increasing subsequences of length 1 is 5." }, { "code": null, "e": 582, "s": 378, "text": "Input: arr[] = {1, 3, 5, 4, 7}Output: 2Explanation: The length of the longest increasing subsequence is 4, and there are 2 longest increasing subsequences of length 4, i.e. {1, 3, 4, 7} and {1, 3, 5, 7}." }, { "code": null, "e": 801, "s": 582, "text": "Naive Approach: The simplest approach is to generate all possible subsequences present in the given array arr[] and count the increasing subsequences of maximum length. Print the count after checking all subsequences. " }, { "code": null, "e": 847, "s": 801, "text": "Time Complexity: O(N*2N)Auxiliary Space: O(1)" }, { "code": null, "e": 1137, "s": 847, "text": "Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming as the above problem has overlapping subproblems that need to be calculated more than once, and to reduce that calculation use tabulation or memoization. Follow the steps below to solve the problem:" }, { "code": null, "e": 1316, "s": 1137, "text": "Initialize two arrays dp_l[] and dp_c[] to store the length of the longest increasing subsequences and the count of the longest increasing subsequence at each index respectively." }, { "code": null, "e": 1682, "s": 1316, "text": "Iterate over the range [1, N – 1] using the variable i:Iterate over the range [0, i – 1] using the variable j:If arr[i] > arr[j] then check for the following cases: ~ If (dp_l[j]+1) greater than dp_l[i], then update dp_l[i] as dp_l[j] + 1 and dp_c[i] as dp_c[j] ~ Else if (dp_l[j] + 1) is the same as dp_l[i], then update dp_c[i] as dp_c[i] + dp_c[j]." }, { "code": null, "e": 1993, "s": 1682, "text": "Iterate over the range [0, i – 1] using the variable j:If arr[i] > arr[j] then check for the following cases: ~ If (dp_l[j]+1) greater than dp_l[i], then update dp_l[i] as dp_l[j] + 1 and dp_c[i] as dp_c[j] ~ Else if (dp_l[j] + 1) is the same as dp_l[i], then update dp_c[i] as dp_c[i] + dp_c[j]." }, { "code": null, "e": 2249, "s": 1993, "text": "If arr[i] > arr[j] then check for the following cases: ~ If (dp_l[j]+1) greater than dp_l[i], then update dp_l[i] as dp_l[j] + 1 and dp_c[i] as dp_c[j] ~ Else if (dp_l[j] + 1) is the same as dp_l[i], then update dp_c[i] as dp_c[i] + dp_c[j]." }, { "code": null, "e": 2366, "s": 2249, "text": "Find the maximum element in the array dp_l[] and store it in a variable max_length that will give the length of LIS." }, { "code": null, "e": 2460, "s": 2366, "text": "Initialize a variable count with 0 to store the number of the longest increasing subsequence." }, { "code": null, "e": 2586, "s": 2460, "text": "Traverse the array dp_l[] and if at any index idx, dp_l[idx] is the same as max_length then increment the count by dp_c[idx]." }, { "code": null, "e": 2710, "s": 2586, "text": "After the above steps, print the value of count, which is the number of longest increasing subsequences in the given array." }, { "code": null, "e": 2761, "s": 2710, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2765, "s": 2761, "text": "C++" }, { "code": null, "e": 2770, "s": 2765, "text": "Java" }, { "code": null, "e": 2778, "s": 2770, "text": "Python3" }, { "code": null, "e": 2781, "s": 2778, "text": "C#" }, { "code": null, "e": 2792, "s": 2781, "text": "Javascript" }, { "code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; //Function to count the number// of LIS in the array nums[]int findNumberOfLIS(vector<int> nums){ //Base Case if (nums.size() == 0) return 0; int n = nums.size(); //Initialize dp_l array with // 1s vector<int> dp_l(n, 1); //Initialize dp_c array with // 1s vector<int> dp_c(n, 1); for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { //If current element is // smaller if (nums[i] <= nums[j]) continue; if (dp_l[j] + 1 > dp_l[i]) { dp_l[i] = dp_l[j] + 1; dp_c[i] = dp_c[j]; } else if (dp_l[j] + 1 == dp_l[i]) dp_c[i] += dp_c[j]; } } //Store the maximum element // from dp_l int max_length = 0; for (int i : dp_l) max_length = max(i,max_length); //Stores the count of LIS int count = 0; //Traverse dp_l and dp_c // simultaneously for(int i = 0; i < n; i++) { //Update the count if (dp_l[i] == max_length) count += dp_c[i]; } //Return the count of LIS return count;} //Driver codeint main(){ //Given array arr[] vector<int> arr = {1, 3, 5, 4, 7}; //Function Call cout << findNumberOfLIS(arr) << endl;} // This code is contributed by Mohit Kumar 29", "e": 4061, "s": 2792, "text": null }, { "code": "// Java program for the// above approachimport java.util.*; class GFG{ // Function to count the number// of LIS in the array nums[]static int findNumberOfLIS(int[] nums){ // Base Case if (nums.length == 0) return 0; int n = nums.length; // Initialize dp_l array with // 1s int[] dp_l = new int[n]; Arrays.fill(dp_l, 1); // Initialize dp_c array with // 1s int[] dp_c = new int[n]; Arrays.fill(dp_c, 1); for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { // If current element is // smaller if (nums[i] <= nums[j]) continue; if (dp_l[j] + 1 > dp_l[i]) { dp_l[i] = dp_l[j] + 1; dp_c[i] = dp_c[j]; } else if (dp_l[j] + 1 == dp_l[i]) dp_c[i] += dp_c[j]; } } // Store the maximum element // from dp_l int max_length = 0; for(int i : dp_l) max_length = Math.max(i, max_length); // Stores the count of LIS int count = 0; // Traverse dp_l and dp_c // simultaneously for(int i = 0; i < n; i++) { // Update the count if (dp_l[i] == max_length) count += dp_c[i]; } // Return the count of LIS return count;} // Driver codepublic static void main(String[] args){ // Given array arr[] int[] arr = { 1, 3, 5, 4, 7 }; // Function Call System.out.print(findNumberOfLIS(arr) + \"\\n\");}} // This code is contributed by shikhasingrajput", "e": 5441, "s": 4061, "text": null }, { "code": "# Python3 program for the above approach # Function to count the number of LIS# in the array nums[]def findNumberOfLIS(nums): # Base Case if not nums: return 0 n = len(nums) # Initialize dp_l array with 1s dp_l = [1] * n # Initialize dp_c array with 1s dp_c = [1] * n for i, num in enumerate(nums): for j in range(i): # If current element is smaller if nums[i] <= nums[j]: continue # Otherwise if dp_l[j] + 1 > dp_l[i]: dp_l[i] = dp_l[j] + 1 dp_c[i] = dp_c[j] elif dp_l[j] + 1 == dp_l[i]: dp_c[i] += dp_c[j] # Store the maximum element from dp_l max_length = max(x for x in dp_l) # Stores the count of LIS count = 0 # Traverse dp_l and dp_c simultaneously for l, c in zip(dp_l, dp_c): # Update the count if l == max_length: count += c # Return the count of LIS return count # Driver Code # Given array arr[]arr = [1, 3, 5, 4, 7] # Function Callprint(findNumberOfLIS(arr))", "e": 6528, "s": 5441, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG { // Function to count the number // of LIS in the array nums[] static int findNumberOfLIS(int[] nums) { // Base Case if (nums.Length == 0) return 0; int n = nums.Length; // Initialize dp_l array with // 1s int[] dp_l = new int[n]; Array.Fill(dp_l, 1); // Initialize dp_c array with // 1s int[] dp_c = new int[n]; Array.Fill(dp_c, 1); for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { // If current element is // smaller if (nums[i] <= nums[j]) continue; if (dp_l[j] + 1 > dp_l[i]) { dp_l[i] = dp_l[j] + 1; dp_c[i] = dp_c[j]; } else if (dp_l[j] + 1 == dp_l[i]) dp_c[i] += dp_c[j]; } } // Store the maximum element // from dp_l int max_length = 0; foreach(int i in dp_l) max_length = Math.Max(i, max_length); // Stores the count of LIS int count = 0; // Traverse dp_l and dp_c // simultaneously for(int i = 0; i < n; i++) { // Update the count if (dp_l[i] == max_length) count += dp_c[i]; } // Return the count of LIS return count; } // Driver code static void Main() { // Given array arr[] int[] arr = { 1, 3, 5, 4, 7 }; // Function Call Console.WriteLine(findNumberOfLIS(arr)); }} // This code is contributed by divyeshrabadiya07", "e": 8225, "s": 6528, "text": null }, { "code": "<script> // Javascript program for the// above approach // Function to count the number// of LIS in the array nums[]function findNumberOfLIS(nums){ //Base Case if (nums.length == 0) return 0; var n = nums.length; // Initialize dp_l array with // 1s var dp_l = Array(n).fill(1); // Initialize dp_c array with // 1s var dp_c = Array(n).fill(1); for (var i = 0; i < n; i++) { for (var j = 0; j < i; j++) { // If current element is // smaller if (nums[i] <= nums[j]) continue; if (dp_l[j] + 1 > dp_l[i]) { dp_l[i] = dp_l[j] + 1; dp_c[i] = dp_c[j]; } else if (dp_l[j] + 1 == dp_l[i]) dp_c[i] += dp_c[j]; } } // Store the maximum element // from dp_l var max_length = 0; dp_l.forEach(i => { max_length = Math.max(i,max_length); }); // Stores the count of LIS var count = 0; //Traverse dp_l and dp_c // simultaneously for(var i = 0; i < n; i++) { // Update the count if (dp_l[i] == max_length) count += dp_c[i]; } // Return the count of LIS return count;} // Driver code// Given array arr[]var arr = [1, 3, 5, 4, 7]; // Function Calldocument.write( findNumberOfLIS(arr)); // This code is contributed by rutvik_56.</script>", "e": 9476, "s": 8225, "text": null }, { "code": null, "e": 9478, "s": 9476, "text": "2" }, { "code": null, "e": 9524, "s": 9480, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 9539, "s": 9524, "text": "mohit kumar 29" }, { "code": null, "e": 9556, "s": 9539, "text": "shikhasingrajput" }, { "code": null, "e": 9574, "s": 9556, "text": "divyeshrabadiya07" }, { "code": null, "e": 9589, "s": 9574, "text": "tridib_samanta" }, { "code": null, "e": 9599, "s": 9589, "text": "rutvik_56" }, { "code": null, "e": 9603, "s": 9599, "text": "LIS" }, { "code": null, "e": 9615, "s": 9603, "text": "Memoization" }, { "code": null, "e": 9627, "s": 9615, "text": "subsequence" }, { "code": null, "e": 9634, "s": 9627, "text": "Arrays" }, { "code": null, "e": 9654, "s": 9634, "text": "Dynamic Programming" }, { "code": null, "e": 9664, "s": 9654, "text": "Recursion" }, { "code": null, "e": 9671, "s": 9664, "text": "Arrays" }, { "code": null, "e": 9691, "s": 9671, "text": "Dynamic Programming" }, { "code": null, "e": 9701, "s": 9691, "text": "Recursion" }, { "code": null, "e": 9799, "s": 9701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9843, "s": 9799, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 9875, "s": 9843, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 9923, "s": 9875, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 9937, "s": 9923, "text": "Linear Search" }, { "code": null, "e": 9960, "s": 9937, "text": "Introduction to Arrays" }, { "code": null, "e": 9990, "s": 9960, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 10019, "s": 9990, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 10053, "s": 10019, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 10080, "s": 10053, "text": "Subset Sum Problem | DP-25" } ]
Instant toString() method in Java with Examples
28 Nov, 2018 The toString() method of Instant class returns string representation of this instant using ISO-8601 representation and format used is the same as DateTimeFormatter.ISO_INSTANT. Syntax: public String toString() Returns: This method returns an ISO-8601 representation of this instant, not null. Below programs illustrate the toString() method: Program 1: // Java program to demonstrate// Instant.toString() method import java.time.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse("2018-10-28T19:34:50.63Z"); // print Instant using toString() System.out.println("Instant: " + instant.toString()); // addition of 84000 seconds to this instant Instant returnedValue = instant.plusSeconds(84000); // print result Instant using toString() System.out.println("Returned Instant: " + returnedValue.toString()); }} Program 2: // Java program to demonstrate// Instant.toString() method import java.time.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse("2022-06-21T19:34:50.63Z"); // print Instant using toString() System.out.println("Instant: " + instant); }} References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#toString() Java-Functions Java-Instant Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Functional Interfaces in Java Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2018" }, { "code": null, "e": 205, "s": 28, "text": "The toString() method of Instant class returns string representation of this instant using ISO-8601 representation and format used is the same as DateTimeFormatter.ISO_INSTANT." }, { "code": null, "e": 213, "s": 205, "text": "Syntax:" }, { "code": null, "e": 238, "s": 213, "text": "public String toString()" }, { "code": null, "e": 321, "s": 238, "text": "Returns: This method returns an ISO-8601 representation of this instant, not null." }, { "code": null, "e": 370, "s": 321, "text": "Below programs illustrate the toString() method:" }, { "code": null, "e": 381, "s": 370, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Instant.toString() method import java.time.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse(\"2018-10-28T19:34:50.63Z\"); // print Instant using toString() System.out.println(\"Instant: \" + instant.toString()); // addition of 84000 seconds to this instant Instant returnedValue = instant.plusSeconds(84000); // print result Instant using toString() System.out.println(\"Returned Instant: \" + returnedValue.toString()); }}", "e": 1054, "s": 381, "text": null }, { "code": null, "e": 1065, "s": 1054, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Instant.toString() method import java.time.*; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse(\"2022-06-21T19:34:50.63Z\"); // print Instant using toString() System.out.println(\"Instant: \" + instant); }}", "e": 1451, "s": 1065, "text": null }, { "code": null, "e": 1540, "s": 1451, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#toString()" }, { "code": null, "e": 1555, "s": 1540, "text": "Java-Functions" }, { "code": null, "e": 1568, "s": 1555, "text": "Java-Instant" }, { "code": null, "e": 1586, "s": 1568, "text": "Java-time package" }, { "code": null, "e": 1591, "s": 1586, "text": "Java" }, { "code": null, "e": 1596, "s": 1591, "text": "Java" }, { "code": null, "e": 1694, "s": 1596, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1709, "s": 1694, "text": "Stream In Java" }, { "code": null, "e": 1730, "s": 1709, "text": "Introduction to Java" }, { "code": null, "e": 1751, "s": 1730, "text": "Constructors in Java" }, { "code": null, "e": 1770, "s": 1751, "text": "Exceptions in Java" }, { "code": null, "e": 1787, "s": 1770, "text": "Generics in Java" }, { "code": null, "e": 1813, "s": 1787, "text": "Java Programming Examples" }, { "code": null, "e": 1843, "s": 1813, "text": "Functional Interfaces in Java" }, { "code": null, "e": 1859, "s": 1843, "text": "Strings in Java" }, { "code": null, "e": 1896, "s": 1859, "text": "Differences between JDK, JRE and JVM" } ]
How does inline JavaScript work with HTML ?
30 Sep, 2019 Inline JavaScript can be achieved by using Script tag inside the body of the HTML, and instead of specifying the source(src=”...”) of the JavaScript file in the Script tag, we have to write all the JavaScript code inside the Script tag. Syntax: <script> // JavaScript Code </script> Example: <!DOCTYPE html> <html> <head> <title>Inline JavaScript</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"></head> <body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <form> <div class="form-group"> <label for="">Enter Your Name:</label> <input id="name" class="form-control" type="text" placeholder="Input Your Name Here"> </div> <div class="form-group"> <button id="btn-alert" class="btn btn-success btn-lg float-right" type="submit"> Submit </button> </div> </form> </div> <script> var user_name = document.getElementById("name"); document.getElementById("btn-alert").addEventListener("click", function(){ var value=user_name.value.trim(); if(!value) alert("Name Cannot be empty!"); else alert("Hello, " + value + "!\nGreetings From GeeksforGeeks."); }); </script></body> </html> Output: As soon as we enter a name and press the submit button, the JavaScript code inside the script tag will be triggered and we will get a pop-up message with our name and greeting text. For deeper knowledge, you can visit What is the inline function in JavaScript ? Note: Using Inline JavaScript is a bad practice and it is not recommended. It can be used for demonstration purposes so that the demonstrator doesn’t have to deal with 2 separate files at a time. It is recommended to write JavaScript code in a separate .js file and then link the same using src attribute in the script tag. Picked JavaScript Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? 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": "\n30 Sep, 2019" }, { "code": null, "e": 265, "s": 28, "text": "Inline JavaScript can be achieved by using Script tag inside the body of the HTML, and instead of specifying the source(src=”...”) of the JavaScript file in the Script tag, we have to write all the JavaScript code inside the Script tag." }, { "code": null, "e": 273, "s": 265, "text": "Syntax:" }, { "code": null, "e": 316, "s": 273, "text": "<script>\n // JavaScript Code\n</script>\n" }, { "code": null, "e": 325, "s": 316, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>Inline JavaScript</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"></head> <body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <form> <div class=\"form-group\"> <label for=\"\">Enter Your Name:</label> <input id=\"name\" class=\"form-control\" type=\"text\" placeholder=\"Input Your Name Here\"> </div> <div class=\"form-group\"> <button id=\"btn-alert\" class=\"btn btn-success btn-lg float-right\" type=\"submit\"> Submit </button> </div> </form> </div> <script> var user_name = document.getElementById(\"name\"); document.getElementById(\"btn-alert\").addEventListener(\"click\", function(){ var value=user_name.value.trim(); if(!value) alert(\"Name Cannot be empty!\"); else alert(\"Hello, \" + value + \"!\\nGreetings From GeeksforGeeks.\"); }); </script></body> </html> ", "e": 1736, "s": 325, "text": null }, { "code": null, "e": 1744, "s": 1736, "text": "Output:" }, { "code": null, "e": 1926, "s": 1744, "text": "As soon as we enter a name and press the submit button, the JavaScript code inside the script tag will be triggered and we will get a pop-up message with our name and greeting text." }, { "code": null, "e": 2006, "s": 1926, "text": "For deeper knowledge, you can visit What is the inline function in JavaScript ?" }, { "code": null, "e": 2330, "s": 2006, "text": "Note: Using Inline JavaScript is a bad practice and it is not recommended. It can be used for demonstration purposes so that the demonstrator doesn’t have to deal with 2 separate files at a time. It is recommended to write JavaScript code in a separate .js file and then link the same using src attribute in the script tag." }, { "code": null, "e": 2337, "s": 2330, "text": "Picked" }, { "code": null, "e": 2348, "s": 2337, "text": "JavaScript" }, { "code": null, "e": 2367, "s": 2348, "text": "Technical Scripter" }, { "code": null, "e": 2384, "s": 2367, "text": "Web Technologies" }, { "code": null, "e": 2411, "s": 2384, "text": "Web technologies Questions" }, { "code": null, "e": 2509, "s": 2411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2570, "s": 2509, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2642, "s": 2570, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2682, "s": 2642, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2723, "s": 2682, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2769, "s": 2723, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 2831, "s": 2769, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2864, "s": 2831, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2925, "s": 2864, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2975, "s": 2925, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Different ways to import csv file in Pandas
19 Dec, 2018 CSV files are the “comma separated values”, these values are separated by commas, this file can be view like as excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can get in CSV file format. Let’s see the different ways to import csv file in Pandas. Method #1: Using read_csv() method. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df.head(10) Output: Providing file_path. # import pandas as pdimport pandas as pd # Takes the file's folderfilepath = r"C:\Gfg\datasets\nba.csv" # read the CSV filedf = pd.read_csv(filepath) # print the first five rowsprint(df.head()) Output: Method #2: Using csv module. One can directly import the csv files using csv module. # import the module csvimport csvimport pandas as pd # open the csv filewith open(r"C:\Users\Admin\Downloads\nba.csv") as csv_file: # read the csv file csv_reader = csv.reader(csv_file, delimiter=',') # now we can use this csv files into the pandas df = pd.DataFrame([csv_reader], index=None) df.head() # iterating values of first columnfor val in list(df[1]): print(val) Output: Picked Python pandas-basics Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Dec, 2018" }, { "code": null, "e": 352, "s": 53, "text": "CSV files are the “comma separated values”, these values are separated by commas, this file can be view like as excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can get in CSV file format." }, { "code": null, "e": 411, "s": 352, "text": "Let’s see the different ways to import csv file in Pandas." }, { "code": null, "e": 447, "s": 411, "text": "Method #1: Using read_csv() method." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") df.head(10) ", "e": 619, "s": 447, "text": null }, { "code": null, "e": 627, "s": 619, "text": "Output:" }, { "code": null, "e": 649, "s": 627, "text": " Providing file_path." }, { "code": "# import pandas as pdimport pandas as pd # Takes the file's folderfilepath = r\"C:\\Gfg\\datasets\\nba.csv\" # read the CSV filedf = pd.read_csv(filepath) # print the first five rowsprint(df.head())", "e": 849, "s": 649, "text": null }, { "code": null, "e": 886, "s": 849, "text": "Output: Method #2: Using csv module." }, { "code": null, "e": 942, "s": 886, "text": "One can directly import the csv files using csv module." }, { "code": "# import the module csvimport csvimport pandas as pd # open the csv filewith open(r\"C:\\Users\\Admin\\Downloads\\nba.csv\") as csv_file: # read the csv file csv_reader = csv.reader(csv_file, delimiter=',') # now we can use this csv files into the pandas df = pd.DataFrame([csv_reader], index=None) df.head() # iterating values of first columnfor val in list(df[1]): print(val)", "e": 1353, "s": 942, "text": null }, { "code": null, "e": 1361, "s": 1353, "text": "Output:" }, { "code": null, "e": 1368, "s": 1361, "text": "Picked" }, { "code": null, "e": 1389, "s": 1368, "text": "Python pandas-basics" }, { "code": null, "e": 1403, "s": 1389, "text": "Python-pandas" }, { "code": null, "e": 1410, "s": 1403, "text": "Python" }, { "code": null, "e": 1508, "s": 1410, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1526, "s": 1508, "text": "Python Dictionary" }, { "code": null, "e": 1568, "s": 1526, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1590, "s": 1568, "text": "Enumerate() in Python" }, { "code": null, "e": 1625, "s": 1590, "text": "Read a file line by line in Python" }, { "code": null, "e": 1651, "s": 1625, "text": "Python String | replace()" }, { "code": null, "e": 1683, "s": 1651, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1712, "s": 1683, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1739, "s": 1712, "text": "Python Classes and Objects" }, { "code": null, "e": 1769, "s": 1739, "text": "Iterate over a list in Python" } ]
Deflater deflate() function in Java with examples
24 Jun, 2019 The deflate() function of the Deflater class in java.util.zip is used to compress the input data and fill the given buffer with the compressed data. The function returns the number of bytes of the compressed data. Function Signature: public int deflate(byte[] b) public int deflate(byte[] b, int offset, int length, int flush) public int deflate(byte[] b, int offset, int length) Syntax: d.deflate(byte[]) d.deflate(byte[], int, int, int) d.deflate(byte[], int, int ) Parameter: The various parameters accepted by these overloaded functions are: byte[] b: This is the input array that is to be deflated int offset: This is the starting offset from which the values are to be read in the given array int length: This is the maximum length to be compressed from the starting offset. int flush: This is the flush mode passed as the parameter Return Type: The function returns an integer value which is the size of the compressed data. Exception: The function throws IllegalArgumentException if is the flush mode is invalid. There are three valid flush modes which are NO_FLUSH, SYNC_FLUSH, FULL_FLUSH. Below examples demonstrate the use of the above function: Example 1: To demonstrate the use of deflate(byte[] b) function // Java program to demonstrate// the use of deflate(byte[] b) function import java.util.zip.*;import java.io.UnsupportedEncodingException; class GFG { public static void main(String args[]) throws UnsupportedEncodingException { // deflater Deflater d = new Deflater(); // get the text String pattern = "GeeksforGeeks", text = ""; // generate the text for (int i = 0; i < 4; i++) text += pattern; // set the input for deflator d.setInput(text.getBytes("UTF-8")); // finish d.finish(); // output bytes byte output[] = new byte[1024]; // compress the data int size = d.deflate(output); // compressed String System.out.println("Compressed String :" + new String(output) + "\n Size " + size); // original String System.out.println("Original String :" + text + "\n Size " + text.length()); // end d.end(); }} Output: Compressed String :x?sOM?.N?/r???q?? Size 21 Original String :GeeksforGeeksGeeksforGeeksGeeksforGeeksGeeksforGeeks Size 52 Example 2: To demonstrate the use of deflate(byte[] b, int offset, int length) function // Java program to demonstrate the use// of deflate(byte[] b, int offset, int length) function import java.util.zip.*;import java.io.UnsupportedEncodingException; class GFG { public static void main(String args[]) throws UnsupportedEncodingException { // deflater Deflater d = new Deflater(); // get the text String pattern = "GeeksforGeeks", text = ""; // generate the text for (int i = 0; i < 4; i++) text += pattern; // set the input for deflator d.setInput(text.getBytes("UTF-8")); // finish d.finish(); // output bytes byte output[] = new byte[1024]; // compress the data, with given offset and // set maximum size of compressed string int size = d.deflate(output, 2, 13); // compressed String System.out.println("Compressed String :" + new String(output) + "\n Size " + size); // original String System.out.println("Original String :" + text + "\n Size " + text.length()); // end d.end(); }} Output: Compressed String :x?sOM?.N?/r? Size 13 Original String :GeeksforGeeksGeeksforGeeksGeeksforGeeksGeeksforGeeks Size 52 Example 3: To demonstrate the use of deflate(byte[] b, int offset, int length, int flush) function // Java program to demonstrate the use of// deflate(byte[] b, int offset, int length, int flush) function import java.util.zip.*;import java.io.UnsupportedEncodingException; class GFG { public static void main(String args[]) throws UnsupportedEncodingException { // deflater Deflater d = new Deflater(); // get the text String pattern = "GeeksforGeeks", text = ""; // generate the text for (int i = 0; i < 4; i++) text += pattern; // set the input for deflator d.setInput(text.getBytes("UTF-8")); // finish d.finish(); // output bytes byte output[] = new byte[1024]; // compress the data, with given offset and // set maximum size of compressed string // and specified Flush int size = d.deflate(output, 2, 13, Deflater.FULL_FLUSH); // compressed String System.out.println("Compressed String :" + new String(output) + "\n Size " + size); // original String System.out.println("Original String :" + text + "\n Size " + text.length()); // end d.end(); }} Output: Compressed String :x?sOM?.N?/r? Size 13 Original String :GeeksforGeeksGeeksforGeeksGeeksforGeeksGeeksforGeeks Size 52 Reference: https://docs.oracle.com/javase/9/docs/api/java/util/zip/Deflater.html#deflate-byte:A- https://docs.oracle.com/javase/9/docs/api/java/util/zip/Deflater.html#deflate-byte:A-int-int- https://docs.oracle.com/javase/9/docs/api/java/util/zip/Deflater.html#deflate-byte:A-int-int-int- Java-Deflater Java-Functions Java-util-zip package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2019" }, { "code": null, "e": 242, "s": 28, "text": "The deflate() function of the Deflater class in java.util.zip is used to compress the input data and fill the given buffer with the compressed data. The function returns the number of bytes of the compressed data." }, { "code": null, "e": 262, "s": 242, "text": "Function Signature:" }, { "code": null, "e": 409, "s": 262, "text": "public int deflate(byte[] b)\npublic int deflate(byte[] b, int offset, int length, int flush)\npublic int deflate(byte[] b, int offset, int length)\n" }, { "code": null, "e": 417, "s": 409, "text": "Syntax:" }, { "code": null, "e": 498, "s": 417, "text": "d.deflate(byte[])\nd.deflate(byte[], int, int, int)\nd.deflate(byte[], int, int )\n" }, { "code": null, "e": 576, "s": 498, "text": "Parameter: The various parameters accepted by these overloaded functions are:" }, { "code": null, "e": 633, "s": 576, "text": "byte[] b: This is the input array that is to be deflated" }, { "code": null, "e": 729, "s": 633, "text": "int offset: This is the starting offset from which the values are to be read in the given array" }, { "code": null, "e": 811, "s": 729, "text": "int length: This is the maximum length to be compressed from the starting offset." }, { "code": null, "e": 869, "s": 811, "text": "int flush: This is the flush mode passed as the parameter" }, { "code": null, "e": 962, "s": 869, "text": "Return Type: The function returns an integer value which is the size of the compressed data." }, { "code": null, "e": 1129, "s": 962, "text": "Exception: The function throws IllegalArgumentException if is the flush mode is invalid. There are three valid flush modes which are NO_FLUSH, SYNC_FLUSH, FULL_FLUSH." }, { "code": null, "e": 1187, "s": 1129, "text": "Below examples demonstrate the use of the above function:" }, { "code": null, "e": 1251, "s": 1187, "text": "Example 1: To demonstrate the use of deflate(byte[] b) function" }, { "code": "// Java program to demonstrate// the use of deflate(byte[] b) function import java.util.zip.*;import java.io.UnsupportedEncodingException; class GFG { public static void main(String args[]) throws UnsupportedEncodingException { // deflater Deflater d = new Deflater(); // get the text String pattern = \"GeeksforGeeks\", text = \"\"; // generate the text for (int i = 0; i < 4; i++) text += pattern; // set the input for deflator d.setInput(text.getBytes(\"UTF-8\")); // finish d.finish(); // output bytes byte output[] = new byte[1024]; // compress the data int size = d.deflate(output); // compressed String System.out.println(\"Compressed String :\" + new String(output) + \"\\n Size \" + size); // original String System.out.println(\"Original String :\" + text + \"\\n Size \" + text.length()); // end d.end(); }}", "e": 2345, "s": 1251, "text": null }, { "code": null, "e": 2353, "s": 2345, "text": "Output:" }, { "code": null, "e": 2479, "s": 2353, "text": "Compressed String :x?sOM?.N?/r???q??\n Size 21\nOriginal String :GeeksforGeeksGeeksforGeeksGeeksforGeeksGeeksforGeeks\n Size 52\n" }, { "code": null, "e": 2567, "s": 2479, "text": "Example 2: To demonstrate the use of deflate(byte[] b, int offset, int length) function" }, { "code": "// Java program to demonstrate the use// of deflate(byte[] b, int offset, int length) function import java.util.zip.*;import java.io.UnsupportedEncodingException; class GFG { public static void main(String args[]) throws UnsupportedEncodingException { // deflater Deflater d = new Deflater(); // get the text String pattern = \"GeeksforGeeks\", text = \"\"; // generate the text for (int i = 0; i < 4; i++) text += pattern; // set the input for deflator d.setInput(text.getBytes(\"UTF-8\")); // finish d.finish(); // output bytes byte output[] = new byte[1024]; // compress the data, with given offset and // set maximum size of compressed string int size = d.deflate(output, 2, 13); // compressed String System.out.println(\"Compressed String :\" + new String(output) + \"\\n Size \" + size); // original String System.out.println(\"Original String :\" + text + \"\\n Size \" + text.length()); // end d.end(); }}", "e": 3763, "s": 2567, "text": null }, { "code": null, "e": 3771, "s": 3763, "text": "Output:" }, { "code": null, "e": 3892, "s": 3771, "text": "Compressed String :x?sOM?.N?/r?\n Size 13\nOriginal String :GeeksforGeeksGeeksforGeeksGeeksforGeeksGeeksforGeeks\n Size 52\n" }, { "code": null, "e": 3991, "s": 3892, "text": "Example 3: To demonstrate the use of deflate(byte[] b, int offset, int length, int flush) function" }, { "code": "// Java program to demonstrate the use of// deflate(byte[] b, int offset, int length, int flush) function import java.util.zip.*;import java.io.UnsupportedEncodingException; class GFG { public static void main(String args[]) throws UnsupportedEncodingException { // deflater Deflater d = new Deflater(); // get the text String pattern = \"GeeksforGeeks\", text = \"\"; // generate the text for (int i = 0; i < 4; i++) text += pattern; // set the input for deflator d.setInput(text.getBytes(\"UTF-8\")); // finish d.finish(); // output bytes byte output[] = new byte[1024]; // compress the data, with given offset and // set maximum size of compressed string // and specified Flush int size = d.deflate(output, 2, 13, Deflater.FULL_FLUSH); // compressed String System.out.println(\"Compressed String :\" + new String(output) + \"\\n Size \" + size); // original String System.out.println(\"Original String :\" + text + \"\\n Size \" + text.length()); // end d.end(); }}", "e": 5223, "s": 3991, "text": null }, { "code": null, "e": 5231, "s": 5223, "text": "Output:" }, { "code": null, "e": 5352, "s": 5231, "text": "Compressed String :x?sOM?.N?/r?\n Size 13\nOriginal String :GeeksforGeeksGeeksforGeeksGeeksforGeeksGeeksforGeeks\n Size 52\n" }, { "code": null, "e": 5363, "s": 5352, "text": "Reference:" }, { "code": null, "e": 5449, "s": 5363, "text": "https://docs.oracle.com/javase/9/docs/api/java/util/zip/Deflater.html#deflate-byte:A-" }, { "code": null, "e": 5543, "s": 5449, "text": "https://docs.oracle.com/javase/9/docs/api/java/util/zip/Deflater.html#deflate-byte:A-int-int-" }, { "code": null, "e": 5641, "s": 5543, "text": "https://docs.oracle.com/javase/9/docs/api/java/util/zip/Deflater.html#deflate-byte:A-int-int-int-" }, { "code": null, "e": 5655, "s": 5641, "text": "Java-Deflater" }, { "code": null, "e": 5670, "s": 5655, "text": "Java-Functions" }, { "code": null, "e": 5692, "s": 5670, "text": "Java-util-zip package" }, { "code": null, "e": 5697, "s": 5692, "text": "Java" }, { "code": null, "e": 5702, "s": 5697, "text": "Java" }, { "code": null, "e": 5800, "s": 5702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5851, "s": 5800, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 5882, "s": 5851, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5901, "s": 5882, "text": "Interfaces in Java" }, { "code": null, "e": 5931, "s": 5901, "text": "HashMap in Java with Examples" }, { "code": null, "e": 5949, "s": 5931, "text": "ArrayList in Java" }, { "code": null, "e": 5964, "s": 5949, "text": "Stream In Java" }, { "code": null, "e": 5984, "s": 5964, "text": "Collections in Java" }, { "code": null, "e": 6016, "s": 5984, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 6040, "s": 6016, "text": "Singleton Class in Java" } ]
Taylor’s Theorem and Taylor series
03 May, 2020 Taylor’s theorem is used for the expansion of the infinite series such as etc. so that we can approximate the values of these functions or polynomials. Taylor’s theorem is used for approximation of k-time differentiable function. Statement:Let the (n-1)th derivative of i.e. be continuous in the nth derivative exist in and be a given positive integer. Then there exists at least one number lying between 0 and 1 such that:..... where and Putting x=a+h or h=x-a we write equation as:.....Taylor’s remainders Rn after n terms due to:1. Cauchy: we just put p=1 in the Taylor’s theorem to get 2. Lagrange: p=n gives Taylor’s formula :Using Lagrange’s remainder we get the Taylor’s formula:..... where As n →∞ if R→0 then the last term of the formula becomesTherefore the Taylor’s formula further reduces toThis formula is now used to give the infinite series expansion of f(x) about point a. Example:Obtain the Taylor’s series expansion ofabout the point x= -1. Explanation:According to the formula we have a= -1 here and f(x) is provided to us. First of all we need to calculate f(a) and then we calculate derivatives of f(x) at given point until it becomes zero.Now we stop here as the next derivative will be zero. f^n(x) =0 for n>5 Thus the Taylor series expansion of f(x) about x= -1 is:..... Substituting the values as calculated by us we get Engineering Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 May, 2020" }, { "code": null, "e": 283, "s": 52, "text": "Taylor’s theorem is used for the expansion of the infinite series such as etc. so that we can approximate the values of these functions or polynomials. Taylor’s theorem is used for approximation of k-time differentiable function." }, { "code": null, "e": 487, "s": 283, "text": "Statement:Let the (n-1)th derivative of i.e. be continuous in the nth derivative exist in and be a given positive integer. Then there exists at least one number lying between 0 and 1 such that:....." }, { "code": null, "e": 673, "s": 487, "text": "where and Putting x=a+h or h=x-a we write equation as:.....Taylor’s remainders Rn after n terms due to:1. Cauchy: we just put p=1 in the Taylor’s theorem to get 2. Lagrange: p=n gives " }, { "code": null, "e": 949, "s": 673, "text": "Taylor’s formula :Using Lagrange’s remainder we get the Taylor’s formula:..... where As n →∞ if R→0 then the last term of the formula becomesTherefore the Taylor’s formula further reduces toThis formula is now used to give the infinite series expansion of f(x) about point a." }, { "code": null, "e": 1019, "s": 949, "text": "Example:Obtain the Taylor’s series expansion ofabout the point x= -1." }, { "code": null, "e": 1282, "s": 1019, "text": "Explanation:According to the formula we have a= -1 here and f(x) is provided to us. First of all we need to calculate f(a) and then we calculate derivatives of f(x) at given point until it becomes zero.Now we stop here as the next derivative will be zero. f^n(x)" }, { "code": null, "e": 1294, "s": 1282, "text": "=0 for n>5 " }, { "code": null, "e": 1356, "s": 1294, "text": "Thus the Taylor series expansion of f(x) about x= -1 is:....." }, { "code": null, "e": 1407, "s": 1356, "text": "Substituting the values as calculated by us we get" }, { "code": null, "e": 1431, "s": 1407, "text": "Engineering Mathematics" } ]
VueJS - Routing
VueJS does not have a built-in router feauture. We need to follow some additional steps to install it. The latest version of vue-router is available at https://unpkg.com/vue-router/dist/vue-router.js Unpkg.com provides npm-based cdn links. The above link is always updated to the recent version. We can download and host it, and use it with a script tag along with vue.js as follows − <script src = "/path/to/vue.js"></script> <script src = "/path/to/vue-router.js"></script> Run the following command to install the vue-router. npm install vue-router We can clone the repository from GitHub as follows − git clone https://github.com/vuejs/vue-router.git node_modules/vue-router cd node_modules/vue-router npm install npm run build Let us start with a simple example using vue-router.js. Example <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> <script type = "text/javascript" src = "js/vue-router.js"></script> </head> <body> <div id = "app"> <h1>Routing Example</h1> <p> <router-link to = "/route1">Router Link 1</router-link> <router-link to = "/route2">Router Link 2</router-link> </p> <!-- route outlet --> <!-- component matched by the route will render here --> <router-view></router-view> </div> <script type = "text/javascript"> const Route1 = { template: '<div style = "border-radius:20px;background-color:cyan;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;">This is router 1</div>' } const Route2 = { template: '<div style = "border-radius:20px;background-color:green;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;">This is router 2</div>' } const routes = [ { path: '/route1', component: Route1 }, { path: '/route2', component: Route2 } ]; const router = new VueRouter({ routes // short for `routes: routes` }); var vm = new Vue({ el: '#app', router }); </script> </body> </html> Output To start with routing, we need to add the vue-router.js file. Take the code from https://unpkg.com/vue-router/dist/vue-router.js and save it in the file vue-router.js. The script is added after vue.js as follows − <script type = "text/javascript" src = "js/vue.js"></script> <script type = "text/javascript" src = "js/vue-router.js"></script> In the body section, there is a router link defined as follows − <p> <router-link to = "/route1">Router Link 1</router-link> <router-link to = "/route2">Router Link 2</router-link> </p> <router-link> is a component used to navigate to the HTML content to be displayed to the user. The to property is the destination, i.e the source file where the contents to be displayed will be picked. In the above piece of code, we have created two router links. Take a look at the script section where the router is initialized. There are two constants created as follows − const Route1 = { template: '<div style = "border-radius:20px;background-color:cyan;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;">This is router 1</div>' }; const Route2 = { template: '<div style = "border-radius:20px;background-color:green;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;">This is router 2</div>' } They have templates, which needs to be shown when the router link is clicked. Next, is the routes const, which defines the path to be displayed in the URL. const routes = [ { path: '/route1', component: Route1 }, { path: '/route2', component: Route2 } ]; Routes define the path and the component. The path i.e. /route1 will be displayed in the URL when the user clicks on the router link. Component takes the templates names to be displayed. The path from the routes need to match with the router link to the property. For example, <router-link to = ”path here”></router-link> Next, the instance is created to VueRouter using the following piece of code. const router = new VueRouter({ routes // short for `routes: routes` }); The VueRouter constructor takes the routes as the param. The router object is assigned to the main vue instance using the following piece of code. var vm = new Vue({ el: '#app', router }); Execute the example and see the display in the browser. On inspecting and checking the router link, we will find that it adds class to the active element as shown in the following screenshot. The class added is class = “router-link-exact-active router-link-active”. The active link gets the class as shown in the above screenshot. Another thing to notice is, the <router-link> gets rendered as a tag. Let us see some more properties to be passed to <router-link>. This is the destination path given to the <router-link>. When clicked, the value of to will be passed to router.push() internally. The value needs to be a string or a location object. When using an object, we need to bind it as shown in e.g. 2. e.g. 1: <router-link to = "/route1">Router Link 1</router-link> renders as <a href = ”#/route”>Router Link </a> e.g. 2: <router-link v-bind:to = "{path:'/route1'}">Router Link 1</router-link> e.g. 3: <router-link v-bind:to = "{path:'/route1', query: { name: 'Tery' }}">Router Link 1</router-link>//router link with query string. Following is the output of e.g. 3. In the URL path, name = Tery is a part of the query string. E.g.: http://localhost/vueexamples/vue_router.html#/route1?name = Tery Adding replace to the router link will call the router.replace() instead of router.push(). With replace, the navigation history is not stored. Example <router-link v-bind:to = "{path:'/route1', query: { name: 'Tery' }}" replace>Router Link 1</router-link> Adding append to the <router-link><router-link> will make the path relative. If we want to go from the router link with path /route1 to router link path /route2, it will show the path in the browser as /route1/route2. Example <router-link v-bind:to = "{ path: '/route1'}" append>Router Link 1</router-link> At present <router-link> renders as a tag. In case, we want to render it as some other tag, we need to specifty the same using tag = ”tagname”; Example <p> <router-link v-bind:to = "{ path: '/route1'}" tag = "span">Router Link 1</router-link> <router-link v-bind:to = "{ path: '/route2'}" tag = "span">Router Link 2</router-link> </p> We have specified the tag as span and this is what is displayed in the browser. The tag displayed now is a span tag. We will still see the click going as we click on the router link for navigation. By default, the active class added when the router link is active is router-link-active. We can overwrite the class by setting the same as shown in the following code. <style> ._active{ background-color : red; } </style> <p> <router-link v-bind:to = "{ path: '/route1'}" active-class = "_active">Router Link 1</router-link> <router-link v-bind:to = "{ path: '/route2'}" tag = "span">Router Link 2</router-link> </p> The class used is active_class = ”_active”. This is the output displayed in the browser. The default exactactive class applied is router-link-exact-active. We can overwrite it using exact-active-class. Example <p> <router-link v-bind:to = "{ path: '/route1'}" exact-active-class = "_active">Router Link 1</router-link> <router-link v-bind:to = "{ path: '/route2'}" tag = "span">Router Link 2</router-link> </p> This is what is displayed in the browser. At present, the default event for router-link is click event. We can change the same using the event property. Example <router-link v-bind:to = "{ path: '/route1'}" event = "mouseover">Router Link 1</router-link> Now, when we mouseover the router link, it will navigate as shown in the following browser. Mouseover on the Router link 1 and we will see the navigation changing.
[ { "code": null, "e": 2173, "s": 2070, "text": "VueJS does not have a built-in router feauture. We need to follow some additional steps to install it." }, { "code": null, "e": 2271, "s": 2173, "text": "The latest version of vue-router is available at https://unpkg.com/vue-router/dist/vue-router.js" }, { "code": null, "e": 2456, "s": 2271, "text": "Unpkg.com provides npm-based cdn links. The above link is always updated to the recent version. We can download and host it, and use it with a script tag along with vue.js as follows −" }, { "code": null, "e": 2547, "s": 2456, "text": "<script src = \"/path/to/vue.js\"></script>\n<script src = \"/path/to/vue-router.js\"></script>" }, { "code": null, "e": 2600, "s": 2547, "text": "Run the following command to install the vue-router." }, { "code": null, "e": 2624, "s": 2600, "text": "npm install vue-router" }, { "code": null, "e": 2677, "s": 2624, "text": "We can clone the repository from GitHub as follows −" }, { "code": null, "e": 2804, "s": 2677, "text": "git clone https://github.com/vuejs/vue-router.git node_modules/vue-router\ncd node_modules/vue-router\nnpm install\nnpm run build" }, { "code": null, "e": 2860, "s": 2804, "text": "Let us start with a simple example using vue-router.js." }, { "code": null, "e": 2868, "s": 2860, "text": "Example" }, { "code": null, "e": 4221, "s": 2868, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n <script type = \"text/javascript\" src = \"js/vue-router.js\"></script>\n </head>\n <body>\n <div id = \"app\">\n <h1>Routing Example</h1>\n <p>\n <router-link to = \"/route1\">Router Link 1</router-link>\n <router-link to = \"/route2\">Router Link 2</router-link>\n </p>\n <!-- route outlet -->\n <!-- component matched by the route will render here -->\n <router-view></router-view>\n </div>\n <script type = \"text/javascript\">\n const Route1 = { template: '<div style = \"border-radius:20px;background-color:cyan;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;\">This is router 1</div>' }\n const Route2 = { template: '<div style = \"border-radius:20px;background-color:green;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;\">This is router 2</div>' }\n const routes = [\n { path: '/route1', component: Route1 },\n { path: '/route2', component: Route2 }\n ];\n const router = new VueRouter({\n routes // short for `routes: routes`\n });\n var vm = new Vue({\n el: '#app',\n router\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 4228, "s": 4221, "text": "Output" }, { "code": null, "e": 4396, "s": 4228, "text": "To start with routing, we need to add the vue-router.js file. Take the code from https://unpkg.com/vue-router/dist/vue-router.js and save it in the file vue-router.js." }, { "code": null, "e": 4442, "s": 4396, "text": "The script is added after vue.js as follows −" }, { "code": null, "e": 4571, "s": 4442, "text": "<script type = \"text/javascript\" src = \"js/vue.js\"></script>\n<script type = \"text/javascript\" src = \"js/vue-router.js\"></script>" }, { "code": null, "e": 4636, "s": 4571, "text": "In the body section, there is a router link defined as follows −" }, { "code": null, "e": 4768, "s": 4636, "text": "<p>\n <router-link to = \"/route1\">Router Link 1</router-link>\n <router-link to = \"/route2\">Router Link 2</router-link>\n</p>" }, { "code": null, "e": 4970, "s": 4768, "text": "<router-link> is a component used to navigate to the HTML content to be displayed to the user. The to property is the destination, i.e the source file where the contents to be displayed will be picked." }, { "code": null, "e": 5032, "s": 4970, "text": "In the above piece of code, we have created two router links." }, { "code": null, "e": 5144, "s": 5032, "text": "Take a look at the script section where the router is initialized. There are two constants created as follows −" }, { "code": null, "e": 5497, "s": 5144, "text": "const Route1 = { template: '<div style = \"border-radius:20px;background-color:cyan;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;\">This is router 1</div>' };\nconst Route2 = { template: '<div style = \"border-radius:20px;background-color:green;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;\">This is router 2</div>' }" }, { "code": null, "e": 5575, "s": 5497, "text": "They have templates, which needs to be shown when the router link is clicked." }, { "code": null, "e": 5653, "s": 5575, "text": "Next, is the routes const, which defines the path to be displayed in the URL." }, { "code": null, "e": 5758, "s": 5653, "text": "const routes = [\n { path: '/route1', component: Route1 },\n { path: '/route2', component: Route2 }\n];" }, { "code": null, "e": 5892, "s": 5758, "text": "Routes define the path and the component. The path i.e. /route1 will be displayed in the URL when the user clicks on the router link." }, { "code": null, "e": 6022, "s": 5892, "text": "Component takes the templates names to be displayed. The path from the routes need to match with the router link to the property." }, { "code": null, "e": 6081, "s": 6022, "text": "For example, <router-link to = ”path here”></router-link>" }, { "code": null, "e": 6159, "s": 6081, "text": "Next, the instance is created to VueRouter using the following piece of code." }, { "code": null, "e": 6234, "s": 6159, "text": "const router = new VueRouter({\n routes // short for `routes: routes`\n});" }, { "code": null, "e": 6381, "s": 6234, "text": "The VueRouter constructor takes the routes as the param. The router object is assigned to the main vue instance using the following piece of code." }, { "code": null, "e": 6429, "s": 6381, "text": "var vm = new Vue({\n el: '#app',\n router\n});" }, { "code": null, "e": 6621, "s": 6429, "text": "Execute the example and see the display in the browser. On inspecting and checking the router link, we will find that it adds class to the active element as shown in the following screenshot." }, { "code": null, "e": 6830, "s": 6621, "text": "The class added is class = “router-link-exact-active router-link-active”. The active link gets the class as shown in the above screenshot. Another thing to notice is, the <router-link> gets rendered as a tag." }, { "code": null, "e": 6893, "s": 6830, "text": "Let us see some more properties to be passed to <router-link>." }, { "code": null, "e": 7138, "s": 6893, "text": "This is the destination path given to the <router-link>. When clicked, the value of to will be passed to router.push() internally. The value needs to be a string or a location object. When using an object, we need to bind it as shown in e.g. 2." }, { "code": null, "e": 7472, "s": 7138, "text": "e.g. 1: <router-link to = \"/route1\">Router Link 1</router-link>\nrenders as\n<a href = ”#/route”>Router Link </a>\ne.g. 2: <router-link v-bind:to = \"{path:'/route1'}\">Router Link 1</router-link>\ne.g. 3: <router-link v-bind:to =\n \"{path:'/route1', query: { name: 'Tery' }}\">Router Link 1</router-link>//router link with query string." }, { "code": null, "e": 7507, "s": 7472, "text": "Following is the output of e.g. 3." }, { "code": null, "e": 7638, "s": 7507, "text": "In the URL path, name = Tery is a part of the query string. E.g.: http://localhost/vueexamples/vue_router.html#/route1?name = Tery" }, { "code": null, "e": 7781, "s": 7638, "text": "Adding replace to the router link will call the router.replace() instead of router.push(). With replace, the navigation history is not stored." }, { "code": null, "e": 7789, "s": 7781, "text": "Example" }, { "code": null, "e": 7896, "s": 7789, "text": "<router-link v-bind:to = \"{path:'/route1', query: { name: 'Tery' }}\" replace>Router Link 1</router-link>" }, { "code": null, "e": 7973, "s": 7896, "text": "Adding append to the <router-link><router-link> will make the path relative." }, { "code": null, "e": 8114, "s": 7973, "text": "If we want to go from the router link with path /route1 to router link path /route2, it will show the path in the browser as /route1/route2." }, { "code": null, "e": 8122, "s": 8114, "text": "Example" }, { "code": null, "e": 8203, "s": 8122, "text": "<router-link v-bind:to = \"{ path: '/route1'}\" append>Router Link 1</router-link>" }, { "code": null, "e": 8347, "s": 8203, "text": "At present <router-link> renders as a tag. In case, we want to render it as some other tag, we need to specifty the same using tag = ”tagname”;" }, { "code": null, "e": 8355, "s": 8347, "text": "Example" }, { "code": null, "e": 8544, "s": 8355, "text": "<p>\n <router-link v-bind:to = \"{ path: '/route1'}\" tag = \"span\">Router Link 1</router-link>\n <router-link v-bind:to = \"{ path: '/route2'}\" tag = \"span\">Router Link 2</router-link>\n</p>" }, { "code": null, "e": 8624, "s": 8544, "text": "We have specified the tag as span and this is what is displayed in the browser." }, { "code": null, "e": 8742, "s": 8624, "text": "The tag displayed now is a span tag. We will still see the click going as we click on the router link for navigation." }, { "code": null, "e": 8910, "s": 8742, "text": "By default, the active class added when the router link is active is router-link-active. We can overwrite the class by setting the same as shown in the following code." }, { "code": null, "e": 9176, "s": 8910, "text": "<style>\n ._active{\n background-color : red;\n }\n</style>\n<p>\n <router-link v-bind:to = \"{ path: '/route1'}\" active-class = \"_active\">Router Link 1</router-link>\n <router-link v-bind:to = \"{ path: '/route2'}\" tag = \"span\">Router Link 2</router-link>\n</p>" }, { "code": null, "e": 9265, "s": 9176, "text": "The class used is active_class = ”_active”. This is the output displayed in the browser." }, { "code": null, "e": 9378, "s": 9265, "text": "The default exactactive class applied is router-link-exact-active. We can overwrite it using exact-active-class." }, { "code": null, "e": 9386, "s": 9378, "text": "Example" }, { "code": null, "e": 9593, "s": 9386, "text": "<p>\n <router-link v-bind:to = \"{ path: '/route1'}\" exact-active-class = \"_active\">Router Link 1</router-link>\n <router-link v-bind:to = \"{ path: '/route2'}\" tag = \"span\">Router Link 2</router-link>\n</p>" }, { "code": null, "e": 9635, "s": 9593, "text": "This is what is displayed in the browser." }, { "code": null, "e": 9746, "s": 9635, "text": "At present, the default event for router-link is click event. We can change the same using the event property." }, { "code": null, "e": 9754, "s": 9746, "text": "Example" }, { "code": null, "e": 9848, "s": 9754, "text": "<router-link v-bind:to = \"{ path: '/route1'}\" event = \"mouseover\">Router Link 1</router-link>" } ]
Polynomial Regression in Julia - GeeksforGeeks
01 Nov, 2020 In statistics, polynomial regression is a form of regression analysis in which the relationship between the independent variable x and the dependent variable y is modeled as an nth degree polynomial in x. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y |x). Polynomial regression is one example of regression analysis using basis functions to model a functional relationship between two quantities. Polynomial provides the best approximation of the relationship between the dependent and independent variables. A broad range of functions can be fit under it. Polynomial basically fits a wide range of curvature. Polynomial Regression in Julia can be implemented by using Polynomials.jl package. Polynomials.jl is a Julia package that provides basic arithmetic, integration, differentiation, evaluation, and root finding over dense univariate polynomials. To install the package, run pkg> add Polynomials Once the package installed, you can load the package using using Polynomials Polynomial: Standard basis polynomials, a(x) = a0 + a1 x + a2 x2 + ... + an xn, n ∈ N ImmutablePolynomial: Standard basis polynomials backed by a Tuple type for faster evaluation of values SparsePolynomial:⁠ Standard basis polynomial backed by a dictionary to hold sparse high-degree polynomials LaurentPolynomial:⁠ Laurent polynomials, a(x) = am xm + ... + an xn m ≤ n, m,n ∈ Z backed by an offset array; for example, if m<0 and n>0, a(x) = am xm + ... + a−1 x−1 + a0 + a1 x + ... + an xn ChebyshevT:⁠ Chebyshev polynomials of the first kind Syntax: julia> using Polynomials Now, let’s see how can we use Polynomial.jl to achieve arithmetic, integration, differentiation, evaluation, and root finding over dense univariate polynomials. Construct a polynomial from an array of its coefficients, lowest order first. Construct a polynomial from its roots by entering the roots as the parameters of the function of function fromroots() in the form of an array Evaluate the polynomial p at x by entering the coefficients as the parameters of function polynomial() in the form of an array The usual arithmetic operators are overloaded to work on polynomials and combinations of polynomials and scalars. The following arithmetic operators are supported on all primitive numeric types: Integrate the polynomial p term by term, optionally adding a constant term k. The degree of the resulting polynomial is one higher than the degree of p (for a nonzero polynomial). Differentiate the polynomial p term by term. The degree of the resulting polynomial is one lower than the degree of p. Return the roots (zeros) of p, with multiplicity. The number of roots returned is equal to the degree of p. By design, this is not type-stable, the returned roots may be real or complex. Fit a polynomial (of degree deg or less) to x and y using a least-squares approximation. Julia using Plots, Polynomialsxs = range(0, 10, length = 10)ys = @.exp(-xs)f = fit(xs, ys) # degree = length(xs) - 1f2 = fit(xs, ys, 2) # degree = 2 scatter(xs, ys, markerstrokewidth = 0, label = "Data")plot!(f, extrema(xs)..., label = "Fit")plot!(f2, extrema(xs)..., label = "Quadratic Fit") Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Get array dimensions and size of a dimension in Julia - size() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Searching in Array for a given element in Julia Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods Exception handling in Julia Get number of elements of array in Julia - length() Method Find maximum element along with its index in Julia - findmax() Method Working with Date and Time in Julia Getting last element of an array in Julia - last() Method Getting the maximum value from a list in Julia - max() Method
[ { "code": null, "e": 24153, "s": 24125, "text": "\n01 Nov, 2020" }, { "code": null, "e": 24636, "s": 24153, "text": "In statistics, polynomial regression is a form of regression analysis in which the relationship between the independent variable x and the dependent variable y is modeled as an nth degree polynomial in x. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y |x). Polynomial regression is one example of regression analysis using basis functions to model a functional relationship between two quantities." }, { "code": null, "e": 24748, "s": 24636, "text": "Polynomial provides the best approximation of the relationship between the dependent and independent variables." }, { "code": null, "e": 24796, "s": 24748, "text": "A broad range of functions can be fit under it." }, { "code": null, "e": 24849, "s": 24796, "text": "Polynomial basically fits a wide range of curvature." }, { "code": null, "e": 25092, "s": 24849, "text": "Polynomial Regression in Julia can be implemented by using Polynomials.jl package. Polynomials.jl is a Julia package that provides basic arithmetic, integration, differentiation, evaluation, and root finding over dense univariate polynomials." }, { "code": null, "e": 25120, "s": 25092, "text": "To install the package, run" }, { "code": null, "e": 25141, "s": 25120, "text": "pkg> add Polynomials" }, { "code": null, "e": 25200, "s": 25141, "text": "Once the package installed, you can load the package using" }, { "code": null, "e": 25218, "s": 25200, "text": "using Polynomials" }, { "code": null, "e": 25304, "s": 25218, "text": "Polynomial: Standard basis polynomials, a(x) = a0 + a1 x + a2 x2 + ... + an xn, n ∈ N" }, { "code": null, "e": 25407, "s": 25304, "text": "ImmutablePolynomial: Standard basis polynomials backed by a Tuple type for faster evaluation of values" }, { "code": null, "e": 25514, "s": 25407, "text": "SparsePolynomial:⁠ Standard basis polynomial backed by a dictionary to hold sparse high-degree polynomials" }, { "code": null, "e": 25708, "s": 25514, "text": "LaurentPolynomial:⁠ Laurent polynomials, a(x) = am xm + ... + an xn m ≤ n, m,n ∈ Z backed by an offset array; for example, if m<0 and n>0, a(x) = am xm + ... + a−1 x−1 + a0 + a1 x + ... + an xn" }, { "code": null, "e": 25761, "s": 25708, "text": "ChebyshevT:⁠ Chebyshev polynomials of the first kind" }, { "code": null, "e": 25769, "s": 25761, "text": "Syntax:" }, { "code": null, "e": 25794, "s": 25769, "text": "julia> using Polynomials" }, { "code": null, "e": 25955, "s": 25794, "text": "Now, let’s see how can we use Polynomial.jl to achieve arithmetic, integration, differentiation, evaluation, and root finding over dense univariate polynomials." }, { "code": null, "e": 26033, "s": 25955, "text": "Construct a polynomial from an array of its coefficients, lowest order first." }, { "code": null, "e": 26175, "s": 26033, "text": "Construct a polynomial from its roots by entering the roots as the parameters of the function of function fromroots() in the form of an array" }, { "code": null, "e": 26302, "s": 26175, "text": "Evaluate the polynomial p at x by entering the coefficients as the parameters of function polynomial() in the form of an array" }, { "code": null, "e": 26416, "s": 26302, "text": "The usual arithmetic operators are overloaded to work on polynomials and combinations of polynomials and scalars." }, { "code": null, "e": 26497, "s": 26416, "text": "The following arithmetic operators are supported on all primitive numeric types:" }, { "code": null, "e": 26677, "s": 26497, "text": "Integrate the polynomial p term by term, optionally adding a constant term k. The degree of the resulting polynomial is one higher than the degree of p (for a nonzero polynomial)." }, { "code": null, "e": 26796, "s": 26677, "text": "Differentiate the polynomial p term by term. The degree of the resulting polynomial is one lower than the degree of p." }, { "code": null, "e": 26983, "s": 26796, "text": "Return the roots (zeros) of p, with multiplicity. The number of roots returned is equal to the degree of p. By design, this is not type-stable, the returned roots may be real or complex." }, { "code": null, "e": 27072, "s": 26983, "text": "Fit a polynomial (of degree deg or less) to x and y using a least-squares approximation." }, { "code": null, "e": 27078, "s": 27072, "text": "Julia" }, { "code": "using Plots, Polynomialsxs = range(0, 10, length = 10)ys = @.exp(-xs)f = fit(xs, ys) # degree = length(xs) - 1f2 = fit(xs, ys, 2) # degree = 2 scatter(xs, ys, markerstrokewidth = 0, label = \"Data\")plot!(f, extrema(xs)..., label = \"Fit\")plot!(f2, extrema(xs)..., label = \"Quadratic Fit\")", "e": 27366, "s": 27078, "text": null }, { "code": null, "e": 27372, "s": 27366, "text": "Julia" }, { "code": null, "e": 27470, "s": 27372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27479, "s": 27470, "text": "Comments" }, { "code": null, "e": 27492, "s": 27479, "text": "Old Comments" }, { "code": null, "e": 27562, "s": 27492, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 27635, "s": 27562, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 27683, "s": 27635, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 27764, "s": 27683, "text": "Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods" }, { "code": null, "e": 27792, "s": 27764, "text": "Exception handling in Julia" }, { "code": null, "e": 27851, "s": 27792, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 27921, "s": 27851, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 27957, "s": 27921, "text": "Working with Date and Time in Julia" }, { "code": null, "e": 28015, "s": 27957, "text": "Getting last element of an array in Julia - last() Method" } ]
Normal Distribution in R - GeeksforGeeks
13 Apr, 2020 Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics because of its advantages in real case scenarios. For example, the height of the population, shoe size, IQ level, rolling a dice, and many more. It is generally observed that data distribution is normal when there is a random collection of data from independent sources. The graph produced after plotting the value of the variable on x-axis and count of the value on y-axis is bell-shaped curve graph. The graph signifies that the peak point is the mean of the data set and half of the values of data set lie on the left side of the mean and other half lies on the right part of the mean telling about the distribution of the values. The graph is symmetric distribution. In R, there are 4 built-in functions to generate normal distribution: dnorm()dnorm(x, mean, sd) dnorm(x, mean, sd) pnorm()pnorm(x, mean, sd) pnorm(x, mean, sd) qnorm()qnorm(p, mean, sd) qnorm(p, mean, sd) rnorm()rnorm(n, mean, sd) rnorm(n, mean, sd) where, – x represents the data set of values– mean(x) represents the mean of data set x. It’s default value is 0. – sd(x) represents the standard deviation of data set x. It’s default value is 1. – n is the number of observations.– p is vector of probabilities dnorm() function in R programming measures density function of distribution. In statistics, it is measured by below formula- where, is mean and is standard deviation. Syntax : dnorm(x, mean, sd) Example: # creating a sequence of values # between -15 to 15 with a difference of 0.1x = seq(-15, 15, by=0.1) y = dnorm(x, mean(x), sd(x)) # output to be present as PNG filepng(file="dnormExample.png") # Plot the graph.plot(x, y) # saving the filedev.off() Output: pnorm() function is the cumulative distribution function which measures the probability that a random number X takes a value less than or equal to x i.e., in statistics it is given by- Syntax: pnorm(x, mean, sd) Example: # creating a sequence of values# between -10 to 10 with a difference of 0.1x <- seq(-10, 10, by=0.1) y <- pnorm(x, mean = 2.5, sd = 2) # output to be present as PNG filepng(file="pnormExample.png") # Plot the graph.plot(x, y) # saving the filedev.off() Output : qnorm() function is the inverse of pnorm() function. It takes the probability value and gives output which corresponds to the probability value. It is useful in finding the percentiles of a normal distribution. Syntax: qnorm(p, mean, sd) Example: # Create a sequence of probability values # incrementing by 0.02.x <- seq(0, 1, by = 0.02) y <- qnorm(x, mean(x), sd(x)) # output to be present as PNG filepng(file = "qnormExample.png") # Plot the graph.plot(x, y) # Save the file.dev.off() Output: rnorm() function in R programming is used to generate a vector of random numbers which are normally distributed. Syntax: rnorm(x, mean, sd) Example: # Create a vector of 1000 random numbers# with mean=90 and sd=5x <- rnorm(10000, mean=90, sd=5) # output to be present as PNG filepng(file = "rnormExample.png") # Create the histogram with 50 barshist(x, breaks=50) # Save the file.dev.off() Output : data-science Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) Convert Factor to Numeric and Numeric to Factor in R Programming How to Change Axis Scales in R Plots? Group by function in R using Dplyr
[ { "code": null, "e": 28679, "s": 28651, "text": "\n13 Apr, 2020" }, { "code": null, "e": 29021, "s": 28679, "text": "Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics because of its advantages in real case scenarios. For example, the height of the population, shoe size, IQ level, rolling a dice, and many more." }, { "code": null, "e": 29547, "s": 29021, "text": "It is generally observed that data distribution is normal when there is a random collection of data from independent sources. The graph produced after plotting the value of the variable on x-axis and count of the value on y-axis is bell-shaped curve graph. The graph signifies that the peak point is the mean of the data set and half of the values of data set lie on the left side of the mean and other half lies on the right part of the mean telling about the distribution of the values. The graph is symmetric distribution." }, { "code": null, "e": 29617, "s": 29547, "text": "In R, there are 4 built-in functions to generate normal distribution:" }, { "code": null, "e": 29643, "s": 29617, "text": "dnorm()dnorm(x, mean, sd)" }, { "code": null, "e": 29662, "s": 29643, "text": "dnorm(x, mean, sd)" }, { "code": null, "e": 29688, "s": 29662, "text": "pnorm()pnorm(x, mean, sd)" }, { "code": null, "e": 29707, "s": 29688, "text": "pnorm(x, mean, sd)" }, { "code": null, "e": 29733, "s": 29707, "text": "qnorm()qnorm(p, mean, sd)" }, { "code": null, "e": 29752, "s": 29733, "text": "qnorm(p, mean, sd)" }, { "code": null, "e": 29778, "s": 29752, "text": "rnorm()rnorm(n, mean, sd)" }, { "code": null, "e": 29797, "s": 29778, "text": "rnorm(n, mean, sd)" }, { "code": null, "e": 29804, "s": 29797, "text": "where," }, { "code": null, "e": 29911, "s": 29804, "text": "– x represents the data set of values– mean(x) represents the mean of data set x. It’s default value is 0." }, { "code": null, "e": 29996, "s": 29914, "text": "– sd(x) represents the standard deviation of data set x. It’s default value is 1." }, { "code": null, "e": 30068, "s": 30003, "text": "– n is the number of observations.– p is vector of probabilities" }, { "code": null, "e": 30193, "s": 30068, "text": "dnorm() function in R programming measures density function of distribution. In statistics, it is measured by below formula-" }, { "code": null, "e": 30237, "s": 30193, "text": "where, is mean and is standard deviation." }, { "code": null, "e": 30246, "s": 30237, "text": "Syntax :" }, { "code": null, "e": 30265, "s": 30246, "text": "dnorm(x, mean, sd)" }, { "code": null, "e": 30274, "s": 30265, "text": "Example:" }, { "code": "# creating a sequence of values # between -15 to 15 with a difference of 0.1x = seq(-15, 15, by=0.1) y = dnorm(x, mean(x), sd(x)) # output to be present as PNG filepng(file=\"dnormExample.png\") # Plot the graph.plot(x, y) # saving the filedev.off() ", "e": 30532, "s": 30274, "text": null }, { "code": null, "e": 30540, "s": 30532, "text": "Output:" }, { "code": null, "e": 30725, "s": 30540, "text": "pnorm() function is the cumulative distribution function which measures the probability that a random number X takes a value less than or equal to x i.e., in statistics it is given by-" }, { "code": null, "e": 30733, "s": 30725, "text": "Syntax:" }, { "code": null, "e": 30752, "s": 30733, "text": "pnorm(x, mean, sd)" }, { "code": null, "e": 30761, "s": 30752, "text": "Example:" }, { "code": "# creating a sequence of values# between -10 to 10 with a difference of 0.1x <- seq(-10, 10, by=0.1) y <- pnorm(x, mean = 2.5, sd = 2) # output to be present as PNG filepng(file=\"pnormExample.png\") # Plot the graph.plot(x, y) # saving the filedev.off() ", "e": 31019, "s": 30761, "text": null }, { "code": null, "e": 31028, "s": 31019, "text": "Output :" }, { "code": null, "e": 31239, "s": 31028, "text": "qnorm() function is the inverse of pnorm() function. It takes the probability value and gives output which corresponds to the probability value. It is useful in finding the percentiles of a normal distribution." }, { "code": null, "e": 31247, "s": 31239, "text": "Syntax:" }, { "code": null, "e": 31266, "s": 31247, "text": "qnorm(p, mean, sd)" }, { "code": null, "e": 31275, "s": 31266, "text": "Example:" }, { "code": "# Create a sequence of probability values # incrementing by 0.02.x <- seq(0, 1, by = 0.02) y <- qnorm(x, mean(x), sd(x)) # output to be present as PNG filepng(file = \"qnormExample.png\") # Plot the graph.plot(x, y) # Save the file.dev.off()", "e": 31519, "s": 31275, "text": null }, { "code": null, "e": 31527, "s": 31519, "text": "Output:" }, { "code": null, "e": 31640, "s": 31527, "text": "rnorm() function in R programming is used to generate a vector of random numbers which are normally distributed." }, { "code": null, "e": 31648, "s": 31640, "text": "Syntax:" }, { "code": null, "e": 31667, "s": 31648, "text": "rnorm(x, mean, sd)" }, { "code": null, "e": 31676, "s": 31667, "text": "Example:" }, { "code": "# Create a vector of 1000 random numbers# with mean=90 and sd=5x <- rnorm(10000, mean=90, sd=5) # output to be present as PNG filepng(file = \"rnormExample.png\") # Create the histogram with 50 barshist(x, breaks=50) # Save the file.dev.off()", "e": 31920, "s": 31676, "text": null }, { "code": null, "e": 31929, "s": 31920, "text": "Output :" }, { "code": null, "e": 31942, "s": 31929, "text": "data-science" }, { "code": null, "e": 31949, "s": 31942, "text": "Picked" }, { "code": null, "e": 31960, "s": 31949, "text": "R Language" }, { "code": null, "e": 32058, "s": 31960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32067, "s": 32058, "text": "Comments" }, { "code": null, "e": 32080, "s": 32067, "text": "Old Comments" }, { "code": null, "e": 32125, "s": 32080, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 32183, "s": 32125, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 32246, "s": 32183, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 32290, "s": 32246, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 32342, "s": 32290, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 32394, "s": 32342, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 32426, "s": 32394, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 32491, "s": 32426, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 32529, "s": 32491, "text": "How to Change Axis Scales in R Plots?" } ]
Java - How to Use Comparator?
Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines precisely what sorted order means. The Comparator interface defines two methods: compare( ) and equals( ). The compare( ) method, shown here, compares two elements for order − int compare(Object obj1, Object obj2) obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned. By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison. The equals( ) method, shown here, tests whether an object equals the invoking comparator − boolean equals(Object obj) obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals( ) is unnecessary, and most simple comparators will not do so. import java.util.*; class Dog implements Comparator<Dog>, Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } public String getDogName() { return name; } public int getDogAge() { return age; } // Overriding the compareTo method public int compareTo(Dog d) { return (this.name).compareTo(d.name); } // Overriding the compare method to sort the age public int compare(Dog d, Dog d1) { return d.age - d1.age; } } public class Example { public static void main(String args[]) { // Takes a list o Dog objects List<Dog> list = new ArrayList<Dog>(); list.add(new Dog("Shaggy", 3)); list.add(new Dog("Lacy", 2)); list.add(new Dog("Roger", 10)); list.add(new Dog("Tommy", 4)); list.add(new Dog("Tammy", 1)); Collections.sort(list); // Sorts the array list for(Dog a: list) // printing the sorted list of names System.out.print(a.getDogName() + ", "); // Sorts the array list using comparator Collections.sort(list, new Dog()); System.out.println(" "); for(Dog a: list) // printing the sorted list of ages System.out.print(a.getDogName() +" : "+ a.getDogAge() + ", "); } } This will produce the following result − Lacy, Roger, Shaggy, Tammy, Tommy, Tammy : 1, Lacy : 2, Shaggy : 3, Tommy : 4, Roger : 10, Note − Sorting of the Arrays class is as the same as the Collections. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2512, "s": 2377, "text": "Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines precisely what sorted order means." }, { "code": null, "e": 2653, "s": 2512, "text": "The Comparator interface defines two methods: compare( ) and equals( ). The compare( ) method, shown here, compares two elements for order −" }, { "code": null, "e": 2692, "s": 2653, "text": "int compare(Object obj1, Object obj2)\n" }, { "code": null, "e": 2888, "s": 2692, "text": "obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned." }, { "code": null, "e": 3074, "s": 2888, "text": "By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison." }, { "code": null, "e": 3165, "s": 3074, "text": "The equals( ) method, shown here, tests whether an object equals the invoking comparator −" }, { "code": null, "e": 3193, "s": 3165, "text": "boolean equals(Object obj)\n" }, { "code": null, "e": 3377, "s": 3193, "text": "obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false." }, { "code": null, "e": 3458, "s": 3377, "text": "Overriding equals( ) is unnecessary, and most simple comparators will not do so." }, { "code": null, "e": 4791, "s": 3458, "text": "import java.util.*;\n\nclass Dog implements Comparator<Dog>, Comparable<Dog> {\n private String name;\n private int age;\n Dog() {\n }\n\n Dog(String n, int a) {\n name = n;\n age = a;\n }\n\n public String getDogName() {\n return name;\n }\n\n public int getDogAge() {\n return age;\n }\n\n // Overriding the compareTo method\n public int compareTo(Dog d) {\n return (this.name).compareTo(d.name);\n }\n\n // Overriding the compare method to sort the age \n public int compare(Dog d, Dog d1) {\n return d.age - d1.age;\n }\n}\n\npublic class Example {\n\n public static void main(String args[]) {\n // Takes a list o Dog objects\n List<Dog> list = new ArrayList<Dog>();\n\n list.add(new Dog(\"Shaggy\", 3));\n list.add(new Dog(\"Lacy\", 2));\n list.add(new Dog(\"Roger\", 10));\n list.add(new Dog(\"Tommy\", 4));\n list.add(new Dog(\"Tammy\", 1));\n Collections.sort(list); // Sorts the array list\n\n for(Dog a: list) // printing the sorted list of names\n System.out.print(a.getDogName() + \", \");\n\n // Sorts the array list using comparator\n Collections.sort(list, new Dog());\n System.out.println(\" \");\n \n for(Dog a: list) // printing the sorted list of ages\n System.out.print(a.getDogName() +\" : \"+ a.getDogAge() + \", \");\n }\n}" }, { "code": null, "e": 4832, "s": 4791, "text": "This will produce the following result −" }, { "code": null, "e": 4929, "s": 4832, "text": "Lacy, Roger, Shaggy, Tammy, Tommy,\nTammy : 1, Lacy : 2, Shaggy : 3, Tommy : 4, Roger : 10,\n" }, { "code": null, "e": 4999, "s": 4929, "text": "Note − Sorting of the Arrays class is as the same as the Collections." }, { "code": null, "e": 5032, "s": 4999, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5048, "s": 5032, "text": " Malhar Lathkar" }, { "code": null, "e": 5081, "s": 5048, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5097, "s": 5081, "text": " Malhar Lathkar" }, { "code": null, "e": 5132, "s": 5097, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5146, "s": 5132, "text": " Anadi Sharma" }, { "code": null, "e": 5180, "s": 5146, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5194, "s": 5180, "text": " Tushar Kale" }, { "code": null, "e": 5231, "s": 5194, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5246, "s": 5231, "text": " Monica Mittal" }, { "code": null, "e": 5279, "s": 5246, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5298, "s": 5279, "text": " Arnab Chakraborty" }, { "code": null, "e": 5305, "s": 5298, "text": " Print" }, { "code": null, "e": 5316, "s": 5305, "text": " Add Notes" } ]
How to catch all the exceptions in C++?
Exceptions are the problems which arise at the time of execution of program. It is an event which is thrown at runtime. It protects the code and run the program even after throwing an exception. Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions. Here is an example of catching all the exceptions in C++ language, Live Demo #include <iostream> using namespace std; void func(int a) { try { if(a==0) throw 23.33; if(a==1) throw 's'; } catch(...) { cout << "Caught Exception!\n"; } } int main() { func(0); func(1); return 0; } Here is the output Caught Exception! Caught Exception!
[ { "code": null, "e": 1358, "s": 1062, "text": "Exceptions are the problems which arise at the time of execution of program. It is an event which is thrown at runtime. It protects the code and run the program even after throwing an exception. Exception handling is used to handle the exceptions. We can use try catch block to protect the code." }, { "code": null, "e": 1460, "s": 1358, "text": "Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions." }, { "code": null, "e": 1527, "s": 1460, "text": "Here is an example of catching all the exceptions in C++ language," }, { "code": null, "e": 1538, "s": 1527, "text": " Live Demo" }, { "code": null, "e": 1776, "s": 1538, "text": "#include <iostream>\nusing namespace std;\n\nvoid func(int a) {\n try {\n if(a==0) throw 23.33;\n if(a==1) throw 's';\n } catch(...) {\n cout << \"Caught Exception!\\n\";\n }\n}\nint main() {\n func(0);\n func(1);\n return 0;\n}" }, { "code": null, "e": 1795, "s": 1776, "text": "Here is the output" }, { "code": null, "e": 1831, "s": 1795, "text": "Caught Exception!\nCaught Exception!" } ]
unordered_set rehash() function in C++ STL - GeeksforGeeks
28 Sep, 2018 The unordered_set::rehash() is a built-in function in C++ STL which is used to set the number of buckets in the container of unordered_set to given size or more. If size is greater than the current size of the container, then rehash is called. If it is lower than the current size, then the function has no effect on bucket count of hash. Syntax: unordered_set_name.rehash(size_type n) Parameter: The function accepts a mandatory parameter n which specifies the minimum number of buckets for the container. Return Value: This function doesn’t returns anything. Below programs illustrate the unordered_set::rehash() function: Program 1: // C++ program to illustrate the// unordered_set::rehash()#include <iostream>#include <string>#include <unordered_set> using namespace std; int main(){ // declaration unordered_set<string> us; // rehashed us.rehash(9); // insert elements us.insert("geeks"); us.insert("for"); us.insert("geeks"); us.insert("users"); for (auto it = us.begin(); it != us.end(); it++) { cout << *it << " "; } cout << "\nThe bucket count is " << us.bucket_count(); return 0;} users for geeks The bucket count is 11 Program 2: // C++ program to illustrate the// unordered_set::rehash()#include <iostream>#include <string>#include <unordered_set> using namespace std; int main(){ // declaration unordered_set<string> us; // rehash the unordered_set us.rehash(20); // insert strings us.insert("geeks"); us.insert("for"); us.insert("geeks"); us.insert("users"); us.insert("are"); us.insert("experts"); us.insert("in"); us.insert("DS"); // prints the elements for (auto it = us.begin(); it != us.end(); it++) { cout << *it << " "; } cout << "\nThe bucket count is " << us.bucket_count(); return 0;} DS in experts are users for geeks The bucket count is 23 CPP-Functions cpp-unordered_set cpp-unordered_set-functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Multidimensional Arrays in C / C++ Socket Programming in C/C++ C++ Classes and Objects Operator Overloading in C++ Bitwise Operators in C/C++ Virtual Function in C++ Iterators in C++ STL Constructors in C++ Copy Constructor in C++
[ { "code": null, "e": 24519, "s": 24491, "text": "\n28 Sep, 2018" }, { "code": null, "e": 24858, "s": 24519, "text": "The unordered_set::rehash() is a built-in function in C++ STL which is used to set the number of buckets in the container of unordered_set to given size or more. If size is greater than the current size of the container, then rehash is called. If it is lower than the current size, then the function has no effect on bucket count of hash." }, { "code": null, "e": 24866, "s": 24858, "text": "Syntax:" }, { "code": null, "e": 24905, "s": 24866, "text": "unordered_set_name.rehash(size_type n)" }, { "code": null, "e": 25026, "s": 24905, "text": "Parameter: The function accepts a mandatory parameter n which specifies the minimum number of buckets for the container." }, { "code": null, "e": 25080, "s": 25026, "text": "Return Value: This function doesn’t returns anything." }, { "code": null, "e": 25144, "s": 25080, "text": "Below programs illustrate the unordered_set::rehash() function:" }, { "code": null, "e": 25155, "s": 25144, "text": "Program 1:" }, { "code": "// C++ program to illustrate the// unordered_set::rehash()#include <iostream>#include <string>#include <unordered_set> using namespace std; int main(){ // declaration unordered_set<string> us; // rehashed us.rehash(9); // insert elements us.insert(\"geeks\"); us.insert(\"for\"); us.insert(\"geeks\"); us.insert(\"users\"); for (auto it = us.begin(); it != us.end(); it++) { cout << *it << \" \"; } cout << \"\\nThe bucket count is \" << us.bucket_count(); return 0;}", "e": 25676, "s": 25155, "text": null }, { "code": null, "e": 25717, "s": 25676, "text": "users for geeks \nThe bucket count is 11\n" }, { "code": null, "e": 25728, "s": 25717, "text": "Program 2:" }, { "code": "// C++ program to illustrate the// unordered_set::rehash()#include <iostream>#include <string>#include <unordered_set> using namespace std; int main(){ // declaration unordered_set<string> us; // rehash the unordered_set us.rehash(20); // insert strings us.insert(\"geeks\"); us.insert(\"for\"); us.insert(\"geeks\"); us.insert(\"users\"); us.insert(\"are\"); us.insert(\"experts\"); us.insert(\"in\"); us.insert(\"DS\"); // prints the elements for (auto it = us.begin(); it != us.end(); it++) { cout << *it << \" \"; } cout << \"\\nThe bucket count is \" << us.bucket_count(); return 0;}", "e": 26377, "s": 25728, "text": null }, { "code": null, "e": 26436, "s": 26377, "text": "DS in experts are users for geeks \nThe bucket count is 23\n" }, { "code": null, "e": 26450, "s": 26436, "text": "CPP-Functions" }, { "code": null, "e": 26468, "s": 26450, "text": "cpp-unordered_set" }, { "code": null, "e": 26496, "s": 26468, "text": "cpp-unordered_set-functions" }, { "code": null, "e": 26500, "s": 26496, "text": "C++" }, { "code": null, "e": 26504, "s": 26500, "text": "CPP" }, { "code": null, "e": 26602, "s": 26504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26611, "s": 26602, "text": "Comments" }, { "code": null, "e": 26624, "s": 26611, "text": "Old Comments" }, { "code": null, "e": 26643, "s": 26624, "text": "Inheritance in C++" }, { "code": null, "e": 26678, "s": 26643, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26706, "s": 26678, "text": "Socket Programming in C/C++" }, { "code": null, "e": 26730, "s": 26706, "text": "C++ Classes and Objects" }, { "code": null, "e": 26758, "s": 26730, "text": "Operator Overloading in C++" }, { "code": null, "e": 26785, "s": 26758, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 26809, "s": 26785, "text": "Virtual Function in C++" }, { "code": null, "e": 26830, "s": 26809, "text": "Iterators in C++ STL" }, { "code": null, "e": 26850, "s": 26830, "text": "Constructors in C++" } ]
CSS - Roll In Effect
An Element can move in a particular direction by turning over and over on an axis. @keyframes rollIn { 0% { opacity: 0; transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; transform: translateX(0px) rotate(0deg); } } Transform − Transform applies to 2d and 3d transformation to an element. Transform − Transform applies to 2d and 3d transformation to an element. Opacity − Opacity applies to an element to make translucence. Opacity − Opacity applies to an element to make translucence. <html> <head> <style> .animated { background-image: url(/css/images/logo.png); background-repeat: no-repeat; background-position: left top; padding-top:95px; margin-bottom:60px; -webkit-animation-duration: 10s; animation-duration: 10s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes rollIn { 0% { opacity: 0; -webkit-transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; -webkit-transform: translateX(0px) rotate(0deg); } } @keyframes rollIn { 0% { opacity: 0; transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; transform: translateX(0px) rotate(0deg); } } .rollIn { -webkit-animation-name: rollIn; animation-name: rollIn; } </style> </head> <body> <div id = "animated-example" class = "animated rollIn"></div> <button onclick = "myFunction()">Reload page</button> <script> function myFunction() { location.reload(); } </script> </body> </html> It will produce the following result − Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Selected Reading UPSC IAS Exams Notes Developer's Best Practices Questions and Answers Effective Resume Writing HR Interview Questions Computer Glossary Who is Who Print Add Notes Bookmark this page
[ { "code": null, "e": 2709, "s": 2626, "text": "An Element can move in a particular direction by turning over and over on an axis." }, { "code": null, "e": 2866, "s": 2709, "text": "@keyframes rollIn {\n 0% { opacity: 0; transform: translateX(-100%) rotate(-120deg); }\n 100% { opacity: 1; transform: translateX(0px) rotate(0deg); } \n} " }, { "code": null, "e": 2939, "s": 2866, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 3012, "s": 2939, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 3074, "s": 3012, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 3136, "s": 3074, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 4595, "s": 3136, "text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n @-webkit-keyframes rollIn {\n 0% { \n opacity: 0; \n -webkit-transform: translateX(-100%) rotate(-120deg); \n }\n 100% { \n opacity: 1; \n -webkit-transform: translateX(0px) rotate(0deg); \n }\n }\n \n @keyframes rollIn {\n 0% { \n opacity: 0; \n transform: translateX(-100%) rotate(-120deg); \n }\n 100% { \n opacity: 1; \n transform: translateX(0px) rotate(0deg); \n }\n }\n .rollIn {\n -webkit-animation-name: rollIn;\n animation-name: rollIn;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated rollIn\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 4634, "s": 4595, "text": "It will produce the following result −" }, { "code": null, "e": 5281, "s": 4634, "text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n" }, { "code": null, "e": 5301, "s": 5281, "text": " Academic Tutorials" }, { "code": null, "e": 5324, "s": 5301, "text": " Big Data & Analytics " }, { "code": null, "e": 5347, "s": 5324, "text": " Computer Programming " }, { "code": null, "e": 5366, "s": 5347, "text": " Computer Science " }, { "code": null, "e": 5378, "s": 5366, "text": " Databases " }, { "code": null, "e": 5387, "s": 5378, "text": " DevOps " }, { "code": null, "e": 5407, "s": 5387, "text": " Digital Marketing " }, { "code": null, "e": 5431, "s": 5407, "text": " Engineering Tutorials " }, { "code": null, "e": 5448, "s": 5431, "text": " Exams Syllabus " }, { "code": null, "e": 5467, "s": 5448, "text": " Famous Monuments " }, { "code": null, "e": 5489, "s": 5467, "text": " GATE Exams Tutorials" }, { "code": null, "e": 5511, "s": 5489, "text": " Latest Technologies " }, { "code": null, "e": 5530, "s": 5511, "text": " Machine Learning " }, { "code": null, "e": 5554, "s": 5530, "text": " Mainframe Development " }, { "code": null, "e": 5577, "s": 5554, "text": " Management Tutorials " }, { "code": null, "e": 5600, "s": 5577, "text": " Mathematics Tutorials" }, { "code": null, "e": 5625, "s": 5600, "text": " Microsoft Technologies " }, { "code": null, "e": 5642, "s": 5625, "text": " Misc tutorials " }, { "code": null, "e": 5663, "s": 5642, "text": " Mobile Development " }, { "code": null, "e": 5683, "s": 5663, "text": " Java Technologies " }, { "code": null, "e": 5705, "s": 5683, "text": " Python Technologies " }, { "code": null, "e": 5721, "s": 5705, "text": " SAP Tutorials " }, { "code": null, "e": 5742, "s": 5721, "text": "Programming Scripts " }, { "code": null, "e": 5761, "s": 5742, "text": " Selected Reading " }, { "code": null, "e": 5780, "s": 5761, "text": " Software Quality " }, { "code": null, "e": 5794, "s": 5780, "text": " Soft Skills " }, { "code": null, "e": 5814, "s": 5794, "text": " Telecom Tutorials " }, { "code": null, "e": 5831, "s": 5814, "text": " UPSC IAS Exams " }, { "code": null, "e": 5849, "s": 5831, "text": " Web Development " }, { "code": null, "e": 5868, "s": 5849, "text": " Sports Tutorials " }, { "code": null, "e": 5887, "s": 5868, "text": " XML Technologies " }, { "code": null, "e": 5903, "s": 5887, "text": " Multi-Language" }, { "code": null, "e": 5924, "s": 5903, "text": " Interview Questions" }, { "code": null, "e": 5941, "s": 5924, "text": "Selected Reading" }, { "code": null, "e": 5962, "s": 5941, "text": "UPSC IAS Exams Notes" }, { "code": null, "e": 5989, "s": 5962, "text": "Developer's Best Practices" }, { "code": null, "e": 6011, "s": 5989, "text": "Questions and Answers" }, { "code": null, "e": 6036, "s": 6011, "text": "Effective Resume Writing" }, { "code": null, "e": 6059, "s": 6036, "text": "HR Interview Questions" }, { "code": null, "e": 6077, "s": 6059, "text": "Computer Glossary" }, { "code": null, "e": 6088, "s": 6077, "text": "Who is Who" }, { "code": null, "e": 6095, "s": 6088, "text": " Print" }, { "code": null, "e": 6106, "s": 6095, "text": " Add Notes" } ]
random header in C++ | Set 1(Generators) - GeeksforGeeks
20 Apr, 2022 This header introduces random number generation facilities. This library allows to produce random numbers using combinations of generators and distributions. Generators: Objects that generate uniformly distributed numbers. Distributions: Objects that transform sequences of numbers generated by a generator into sequences of numbers that follow a specific random variable distribution, such as uniform, Normal or Binomial. Generators I. Pseudo-random number engines: They use an algorithm to generate random numbers based on an initial seed. These are: 1. linear_congruential_engine: It is the simplest engine in the STL library that generates random unsigned integer numbers. It follows: x = (a.x +c) mod m Where x= current state value a = multiplier parameter ; if m is not zero, this parameter should be lower than m. c = increment parameter ; if m is not zero, this parameter should be lower than m. m = modulus parameter operator(): It generates random number. min: It gives the minimum value returned by member operator(). max: It gives the maximum value returned by member operator(). C++ // C++ program to illustrate// the use of operator(), max and min// in linear_congruential_engine#include <iostream>#include <chrono>#include <random>using namespace std; // driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // minstd_rand0 is a standard // linear_congruential_engine minstd_rand0 generator (seed); // generates the random number cout << generator() << " is a random number between "; //use of min and max functions cout << generator.min() << " and " << generator.max(); return 0;} Output: 211182246 is a random number between 1 and 2147483646 2. mersenne_twister_engine: It is a random number engine based on Mersenne Twister algorithm. It produces high quality unsigned integer random numbers in the interval [0, (2^w)-1].where ‘w’ is word size: Number of bits of each word in the state sequence. operator(): It generates the random number. min: It returns the minimum value returned by member operator(), which for mersenne_twister_engine is always zero. max: It returns the maximum value returned by member operator(), which for mersenne_twister_engine is 2w-1 (where w is the word size). C++ // C++ program to illustrate the use of// operator(), min and max// in mersenne_twister_engine#include <iostream>#include <chrono>#include <random>using namespace std; // Driver programint main (){ // finds the time between the system clock // (present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // mt19937 is a standard mersenne_twister_engine mt19937 generator (seed); // use of operator() cout << generator() << " is a random number between "; // use of max and min cout << generator.min() << " and " << generator.max(); return 0;} Output: 3348201622 is a random number between 0 and 4294967295 3. subtract_with_carry_engine: It is a pseudo-random number generator engine that produces unsigned integer numbers.The algorithm used is a lagged fibonacci generator, with a state sequence of r integer elements, plus one carry value. operator(): It generates the random number. max: It returns the maximum value returned by member operator(), which is (2^w)-1 for subtract_with_carry_engine , where ‘w’ is the word size. min: It returns the minimum value returned by member operator(), which is always zero for subtract_with_carry_engine. C++ // C++ program to illustrate the use of// operator(), min and max// in subtract_with_carry_engine#include <iostream>#include <chrono>#include <random>using namespace std; // Driver programint main (){ // finds the time between the system clock // (present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); subtract_with_carry_engine<unsigned, 24, 10, 24> generator (seed); // use of operator() cout << generator() << " is a random number between "; // use of min and max cout << generator.min() << " and " << generator.max(); return 0;} Output: 8606455 is a random number between 0 and 16777215 II. Random number generator: It is a random number generator that produces non-deterministic random numbers. random_device: It is the true random number generator. operator(): It returns a new random number. min: It returns the minimum value returned by member operator(), which for random_device is always zero. max: It returns the maximum value returned by member operator(). C++ // C++ program to illustrate the use of// operator(), min and max// in random_device#include <iostream>#include <random>using namespace std; //Driver programint main (){ random_device example; cout << "default random_device characteristics:" << endl; // use of min cout << "minimum: " << example.min() << endl; // use of max cout << "maximum: " << example.max() << endl; // use of entropy cout << "entropy: " << example.entropy() << endl; // use of operator() cout << "a random number: " << example() << endl; return 0;} Output: default random_device characteristics: minimum: 0 maximum: 4294967295 entropy: 0 a random number: 3705944883 III. Pseudo-random number engines (instantiations): These are the particular instantiations of generator engines and adaptors: 1. default_random_engine: This is a random number engine class that generates pseudo-random numbers. min: It returns the minimum value given by operator(). max: It returns the maximum value given by operator(). operator(): It returns a new random number.The function changes the internal state by one, which modifies the state value according to the given algorithm: x= (a.x + c)mod m Where x= current state value a and c = respective class template parameters m = class template parameter C++ // C++ program to illustrate the use of // operator(), min and max// in default_random_engine #include <iostream>#include <chrono>#include <random>using namespace std; // Driver program int main (){ // finds the time between the system clock // (present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // minstd_rand0 is a standard linear_congruential_engine minstd_rand0 generator (seed); // generates the random number cout << generator() << " is a random number between "; // Use of min and max cout << generator.min() << " and " << generator.max(); return 0;} Output: 201066682 is a random number between 1 and 2147483646 2. minstd_rand: It generates pseudo random numbers; it is similar to linear congruential generator operator(): It returns a new random number. The function changes the internal state by one, which modifies the state value according to the following algorithm: x = (a.x + c) mod m where x= current state value a ,c and m=class template parameter min: It returns the minimum value given by member operator(). max: It returns the maximum value given by member operator(), which for linear_congruential_engine is (modulus-1). C++ // C++ program to illustrate// the use of operator(), max and min// in minstd_rand#include <iostream>#include <chrono>#include <random>using namespace std; //Driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // minstd_rand0 is a standard //linear_congruential_engine minstd_rand0 generator (seed); // use of operator() cout << generator() << " is a random number between "; //use of max and min cout << generator.min() << " and " << generator.max(); return 0;} Output: 489592737 is a random number between 1 and 2147483646 3. mt19937: It is Mersenne Twister 19937 generator.It is a pseudo-random generator of 32-bit numbers with a state size of 19937 bits. operator(): It generates a random number. The function changes the internal state by one using a transition algorithm that produces a twist on the selected element. max: It returns the maximum value given by operator(). min: It returns the minimum value given by operator(). C++ // C++ program to illustrate the // use of operator(),min and max // in mt19937#include <iostream>#include <chrono>#include <random>using namespace std; // Driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // mt19937 is a standard //mersenne_twister_engine mt19937 generator (seed); //use of operator() cout << generator() << " is a random number between "; //use of max and min cout << generator.min() << " and " << generator.max(); return 0;} Output: 1445431990 is a random number between 0 and 4294967295 4. ranlux24_base: It is Ranlux 24 base generator. It’s a subtract-with-carry pseudo-random generator of 24-bit numbers, generally used as the base engine for the ranlux24 generator. operator(): It returns a new random number.The function changes the internal state by calling its transition algorithm which applies a subtract-with-carry operation on the element. max: It returns the maximum value given by operator(). min: It returns the minimum value given by operator(). C++ // C++ program to illustrate // the use of operator(),min and max// in ranlux24_base#include <iostream>#include <chrono>#include <random>using namespace std; //Driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); subtract_with_carry_engine<unsigned,24,10,24> generator (seed); //use of operator() cout << generator() << " is a random number between "; //use of max and min cout << generator.min() << " and " << generator.max(); return 0;} Output: 7275352 is a random number between 0 and 16777215 Similar format is applicable for the other examples. IV. Engine Adaptors 1. discard_block_engine: It is an engine adaptor class template that adapts a pseudo-random number generator Engine type by using only ‘r’ elements of each block of ‘p’ elements from the sequence it produces, discarding the rest.The adaptor keeps an internal count of how many elements have been produced in the current block. The standard generators ranlux24 and ranlux48 adapt a subtract_with_carry_engine using this adaptor. operator(): It returns a new random number. max: It returns the maximum value given by operator(). min: It returns the minimum value given by operator(). C++ // C++ program to illustrate// the use of operator(),min and max// in the discard_block_engine#include <iostream>#include <chrono>#include <random>using namespace std; //Driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // ranlux24 is a standard instantiation //of discard_block_engine: ranlux24 generator (seed); //use of operator() cout << generator() << " is a random number between "; //use of max and min cout << generator.min() << " and " << generator.max(); return 0;} Output: 8132325 is a random number between 0 and 16777215 2. independent_bits_engine: It is an engine adaptor class template that adapts a pseudo-random number generator Engine type to produce random numbers with a specific number of bits (w). operator(): It returns a new random number.The engine’s transition algorithm invokes the base engines’s operator() member as many times as needed to obtain enough significant bits to construct a random value. max: It returns the maximum value given by operator(). min: It returns the minimum value given by operator(). C++ // C++ program to illustrate// the use of operator(),min and max// in independent_bits_engine#include <iostream>#include <chrono> // It imports the symbol names in // std namespace and possibly in Global namespace.#include <cstdint>#include <random>using namespace std; //Driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); //use of independent_bits_engine independent_bits_engine<mt19937,64,uint_fast64_t> generator (seed); //use of operator() cout << generator() << " is a random number between "; //use of max and min cout << generator.min() << " and " << generator.max(); return 0;} Output: 13551674127875514537 is a random number between 0 and 184467 3. shuffle_order_engine: It is an engine adaptor class template that adapts a pseudo-random number generator Engine type so that the numbers are delivered in a different sequence.The object keeps a buffer of k generated numbers internally, and when requested, returns a randomly selected number within the buffer, replacing it with a value obtained from its base engine. operator(): It returns a new random number.The engine’s transition algorithm picks a value in the internal table (which is returned by the function) and replaces it with a new value obtained from its base engine. max: It returns the maximum value given by operator(). min: It returns the minimum value given by operator(). C++ // C++ program to illustrate// the use of operator(),min and max// in shuffle_order_engine#include <iostream>#include <chrono>#include <random>using namespace std; int main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // ranlux24 is a standard instantiation // of discard_block_engine: ranlux24 generator (seed); //use of operator() cout << generator() << " is a random number between "; //use of max and min cout << generator.min() << " and " << generator.max(); return 0;} Output: 9213395 is a random number between 0 and 16777215 sumitgumber28 akshaysingh98088 C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Map in C++ Standard Template Library (STL) Constructors in C++ C++ Classes and Objects Socket Programming in C/C++ Bitwise Operators in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Copy Constructor in C++ Virtual Function in C++
[ { "code": null, "e": 24191, "s": 24163, "text": "\n20 Apr, 2022" }, { "code": null, "e": 24349, "s": 24191, "text": "This header introduces random number generation facilities. This library allows to produce random numbers using combinations of generators and distributions." }, { "code": null, "e": 24414, "s": 24349, "text": "Generators: Objects that generate uniformly distributed numbers." }, { "code": null, "e": 24614, "s": 24414, "text": "Distributions: Objects that transform sequences of numbers generated by a generator into sequences of numbers that follow a specific random variable distribution, such as uniform, Normal or Binomial." }, { "code": null, "e": 24625, "s": 24614, "text": "Generators" }, { "code": null, "e": 24744, "s": 24625, "text": "I. Pseudo-random number engines: They use an algorithm to generate random numbers based on an initial seed. These are:" }, { "code": null, "e": 24881, "s": 24744, "text": "1. linear_congruential_engine: It is the simplest engine in the STL library that generates random unsigned integer numbers. It follows: " }, { "code": null, "e": 25185, "s": 24881, "text": " x = (a.x +c) mod m \nWhere x= current state value \n a = multiplier parameter ; if m is not zero, \n this parameter should be lower than m.\n c = increment parameter ; if m is not zero, \n this parameter should be lower than m.\n m = modulus parameter " }, { "code": null, "e": 25225, "s": 25185, "text": "operator(): It generates random number." }, { "code": null, "e": 25288, "s": 25225, "text": "min: It gives the minimum value returned by member operator()." }, { "code": null, "e": 25351, "s": 25288, "text": "max: It gives the maximum value returned by member operator()." }, { "code": null, "e": 25355, "s": 25351, "text": "C++" }, { "code": "// C++ program to illustrate// the use of operator(), max and min// in linear_congruential_engine#include <iostream>#include <chrono>#include <random>using namespace std; // driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // minstd_rand0 is a standard // linear_congruential_engine minstd_rand0 generator (seed); // generates the random number cout << generator() << \" is a random number between \"; //use of min and max functions cout << generator.min() << \" and \" << generator.max(); return 0;}", "e": 26034, "s": 25355, "text": null }, { "code": null, "e": 26042, "s": 26034, "text": "Output:" }, { "code": null, "e": 26096, "s": 26042, "text": "211182246 is a random number between 1 and 2147483646" }, { "code": null, "e": 26352, "s": 26096, "text": "2. mersenne_twister_engine: It is a random number engine based on Mersenne Twister algorithm. It produces high quality unsigned integer random numbers in the interval [0, (2^w)-1].where ‘w’ is word size: Number of bits of each word in the state sequence. " }, { "code": null, "e": 26396, "s": 26352, "text": "operator(): It generates the random number." }, { "code": null, "e": 26511, "s": 26396, "text": "min: It returns the minimum value returned by member operator(), which for mersenne_twister_engine is always zero." }, { "code": null, "e": 26646, "s": 26511, "text": "max: It returns the maximum value returned by member operator(), which for mersenne_twister_engine is 2w-1 (where w is the word size)." }, { "code": null, "e": 26650, "s": 26646, "text": "C++" }, { "code": "// C++ program to illustrate the use of// operator(), min and max// in mersenne_twister_engine#include <iostream>#include <chrono>#include <random>using namespace std; // Driver programint main (){ // finds the time between the system clock // (present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // mt19937 is a standard mersenne_twister_engine mt19937 generator (seed); // use of operator() cout << generator() << \" is a random number between \"; // use of max and min cout << generator.min() << \" and \" << generator.max(); return 0;}", "e": 27293, "s": 26650, "text": null }, { "code": null, "e": 27301, "s": 27293, "text": "Output:" }, { "code": null, "e": 27356, "s": 27301, "text": "3348201622 is a random number between 0 and 4294967295" }, { "code": null, "e": 27591, "s": 27356, "text": "3. subtract_with_carry_engine: It is a pseudo-random number generator engine that produces unsigned integer numbers.The algorithm used is a lagged fibonacci generator, with a state sequence of r integer elements, plus one carry value." }, { "code": null, "e": 27635, "s": 27591, "text": "operator(): It generates the random number." }, { "code": null, "e": 27778, "s": 27635, "text": "max: It returns the maximum value returned by member operator(), which is (2^w)-1 for subtract_with_carry_engine , where ‘w’ is the word size." }, { "code": null, "e": 27896, "s": 27778, "text": "min: It returns the minimum value returned by member operator(), which is always zero for subtract_with_carry_engine." }, { "code": null, "e": 27900, "s": 27896, "text": "C++" }, { "code": "// C++ program to illustrate the use of// operator(), min and max// in subtract_with_carry_engine#include <iostream>#include <chrono>#include <random>using namespace std; // Driver programint main (){ // finds the time between the system clock // (present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); subtract_with_carry_engine<unsigned, 24, 10, 24> generator (seed); // use of operator() cout << generator() << \" is a random number between \"; // use of min and max cout << generator.min() << \" and \" << generator.max(); return 0;}", "e": 28531, "s": 27900, "text": null }, { "code": null, "e": 28539, "s": 28531, "text": "Output:" }, { "code": null, "e": 28589, "s": 28539, "text": "8606455 is a random number between 0 and 16777215" }, { "code": null, "e": 28698, "s": 28589, "text": "II. Random number generator: It is a random number generator that produces non-deterministic random numbers." }, { "code": null, "e": 28753, "s": 28698, "text": "random_device: It is the true random number generator." }, { "code": null, "e": 28797, "s": 28753, "text": "operator(): It returns a new random number." }, { "code": null, "e": 28902, "s": 28797, "text": "min: It returns the minimum value returned by member operator(), which for random_device is always zero." }, { "code": null, "e": 28967, "s": 28902, "text": "max: It returns the maximum value returned by member operator()." }, { "code": null, "e": 28971, "s": 28967, "text": "C++" }, { "code": "// C++ program to illustrate the use of// operator(), min and max// in random_device#include <iostream>#include <random>using namespace std; //Driver programint main (){ random_device example; cout << \"default random_device characteristics:\" << endl; // use of min cout << \"minimum: \" << example.min() << endl; // use of max cout << \"maximum: \" << example.max() << endl; // use of entropy cout << \"entropy: \" << example.entropy() << endl; // use of operator() cout << \"a random number: \" << example() << endl; return 0;}", "e": 29555, "s": 28971, "text": null }, { "code": null, "e": 29563, "s": 29555, "text": "Output:" }, { "code": null, "e": 29672, "s": 29563, "text": "default random_device characteristics:\nminimum: 0\nmaximum: 4294967295\nentropy: 0\na random number: 3705944883" }, { "code": null, "e": 29799, "s": 29672, "text": "III. Pseudo-random number engines (instantiations): These are the particular instantiations of generator engines and adaptors:" }, { "code": null, "e": 29900, "s": 29799, "text": "1. default_random_engine: This is a random number engine class that generates pseudo-random numbers." }, { "code": null, "e": 29955, "s": 29900, "text": "min: It returns the minimum value given by operator()." }, { "code": null, "e": 30010, "s": 29955, "text": "max: It returns the maximum value given by operator()." }, { "code": null, "e": 30166, "s": 30010, "text": "operator(): It returns a new random number.The function changes the internal state by one, which modifies the state value according to the given algorithm:" }, { "code": null, "e": 30294, "s": 30166, "text": " x= (a.x + c)mod m\n Where x= current state value\n a and c = respective class template parameters\n m = class template parameter " }, { "code": null, "e": 30298, "s": 30294, "text": "C++" }, { "code": "// C++ program to illustrate the use of // operator(), min and max// in default_random_engine #include <iostream>#include <chrono>#include <random>using namespace std; // Driver program int main (){ // finds the time between the system clock // (present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // minstd_rand0 is a standard linear_congruential_engine minstd_rand0 generator (seed); // generates the random number cout << generator() << \" is a random number between \"; // Use of min and max cout << generator.min() << \" and \" << generator.max(); return 0;}", "e": 30979, "s": 30298, "text": null }, { "code": null, "e": 30987, "s": 30979, "text": "Output:" }, { "code": null, "e": 31041, "s": 30987, "text": "201066682 is a random number between 1 and 2147483646" }, { "code": null, "e": 31140, "s": 31041, "text": "2. minstd_rand: It generates pseudo random numbers; it is similar to linear congruential generator" }, { "code": null, "e": 31301, "s": 31140, "text": "operator(): It returns a new random number. The function changes the internal state by one, which modifies the state value according to the following algorithm:" }, { "code": null, "e": 31386, "s": 31301, "text": "x = (a.x + c) mod m\nwhere x= current state value\na ,c and m=class template parameter" }, { "code": null, "e": 31448, "s": 31386, "text": "min: It returns the minimum value given by member operator()." }, { "code": null, "e": 31563, "s": 31448, "text": "max: It returns the maximum value given by member operator(), which for linear_congruential_engine is (modulus-1)." }, { "code": null, "e": 31567, "s": 31563, "text": "C++" }, { "code": "// C++ program to illustrate// the use of operator(), max and min// in minstd_rand#include <iostream>#include <chrono>#include <random>using namespace std; //Driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // minstd_rand0 is a standard //linear_congruential_engine minstd_rand0 generator (seed); // use of operator() cout << generator() << \" is a random number between \"; //use of max and min cout << generator.min() << \" and \" << generator.max(); return 0;}", "e": 32197, "s": 31567, "text": null }, { "code": null, "e": 32205, "s": 32197, "text": "Output:" }, { "code": null, "e": 32259, "s": 32205, "text": "489592737 is a random number between 1 and 2147483646" }, { "code": null, "e": 32393, "s": 32259, "text": "3. mt19937: It is Mersenne Twister 19937 generator.It is a pseudo-random generator of 32-bit numbers with a state size of 19937 bits." }, { "code": null, "e": 32558, "s": 32393, "text": "operator(): It generates a random number. The function changes the internal state by one using a transition algorithm that produces a twist on the selected element." }, { "code": null, "e": 32613, "s": 32558, "text": "max: It returns the maximum value given by operator()." }, { "code": null, "e": 32669, "s": 32613, "text": "min: It returns the minimum value given by operator(). " }, { "code": null, "e": 32673, "s": 32669, "text": "C++" }, { "code": "// C++ program to illustrate the // use of operator(),min and max // in mt19937#include <iostream>#include <chrono>#include <random>using namespace std; // Driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // mt19937 is a standard //mersenne_twister_engine mt19937 generator (seed); //use of operator() cout << generator() << \" is a random number between \"; //use of max and min cout << generator.min() << \" and \" << generator.max(); return 0;}", "e": 33289, "s": 32673, "text": null }, { "code": null, "e": 33297, "s": 33289, "text": "Output:" }, { "code": null, "e": 33352, "s": 33297, "text": "1445431990 is a random number between 0 and 4294967295" }, { "code": null, "e": 33534, "s": 33352, "text": "4. ranlux24_base: It is Ranlux 24 base generator. It’s a subtract-with-carry pseudo-random generator of 24-bit numbers, generally used as the base engine for the ranlux24 generator." }, { "code": null, "e": 33715, "s": 33534, "text": "operator(): It returns a new random number.The function changes the internal state by calling its transition algorithm which applies a subtract-with-carry operation on the element." }, { "code": null, "e": 33770, "s": 33715, "text": "max: It returns the maximum value given by operator()." }, { "code": null, "e": 33825, "s": 33770, "text": "min: It returns the minimum value given by operator()." }, { "code": null, "e": 33829, "s": 33825, "text": "C++" }, { "code": "// C++ program to illustrate // the use of operator(),min and max// in ranlux24_base#include <iostream>#include <chrono>#include <random>using namespace std; //Driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); subtract_with_carry_engine<unsigned,24,10,24> generator (seed); //use of operator() cout << generator() << \" is a random number between \"; //use of max and min cout << generator.min() << \" and \" << generator.max(); return 0;}", "e": 34427, "s": 33829, "text": null }, { "code": null, "e": 34435, "s": 34427, "text": "Output:" }, { "code": null, "e": 34485, "s": 34435, "text": "7275352 is a random number between 0 and 16777215" }, { "code": null, "e": 34538, "s": 34485, "text": "Similar format is applicable for the other examples." }, { "code": null, "e": 34558, "s": 34538, "text": "IV. Engine Adaptors" }, { "code": null, "e": 34885, "s": 34558, "text": "1. discard_block_engine: It is an engine adaptor class template that adapts a pseudo-random number generator Engine type by using only ‘r’ elements of each block of ‘p’ elements from the sequence it produces, discarding the rest.The adaptor keeps an internal count of how many elements have been produced in the current block." }, { "code": null, "e": 34986, "s": 34885, "text": "The standard generators ranlux24 and ranlux48 adapt a subtract_with_carry_engine using this adaptor." }, { "code": null, "e": 35030, "s": 34986, "text": "operator(): It returns a new random number." }, { "code": null, "e": 35085, "s": 35030, "text": "max: It returns the maximum value given by operator()." }, { "code": null, "e": 35140, "s": 35085, "text": "min: It returns the minimum value given by operator()." }, { "code": null, "e": 35144, "s": 35140, "text": "C++" }, { "code": "// C++ program to illustrate// the use of operator(),min and max// in the discard_block_engine#include <iostream>#include <chrono>#include <random>using namespace std; //Driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // ranlux24 is a standard instantiation //of discard_block_engine: ranlux24 generator (seed); //use of operator() cout << generator() << \" is a random number between \"; //use of max and min cout << generator.min() << \" and \" << generator.max(); return 0;}", "e": 35785, "s": 35144, "text": null }, { "code": null, "e": 35793, "s": 35785, "text": "Output:" }, { "code": null, "e": 35843, "s": 35793, "text": "8132325 is a random number between 0 and 16777215" }, { "code": null, "e": 36029, "s": 35843, "text": "2. independent_bits_engine: It is an engine adaptor class template that adapts a pseudo-random number generator Engine type to produce random numbers with a specific number of bits (w)." }, { "code": null, "e": 36238, "s": 36029, "text": "operator(): It returns a new random number.The engine’s transition algorithm invokes the base engines’s operator() member as many times as needed to obtain enough significant bits to construct a random value." }, { "code": null, "e": 36293, "s": 36238, "text": "max: It returns the maximum value given by operator()." }, { "code": null, "e": 36348, "s": 36293, "text": "min: It returns the minimum value given by operator()." }, { "code": null, "e": 36352, "s": 36348, "text": "C++" }, { "code": "// C++ program to illustrate// the use of operator(),min and max// in independent_bits_engine#include <iostream>#include <chrono> // It imports the symbol names in // std namespace and possibly in Global namespace.#include <cstdint>#include <random>using namespace std; //Driver programint main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); //use of independent_bits_engine independent_bits_engine<mt19937,64,uint_fast64_t> generator (seed); //use of operator() cout << generator() << \" is a random number between \"; //use of max and min cout << generator.min() << \" and \" << generator.max(); return 0;}", "e": 37103, "s": 36352, "text": null }, { "code": null, "e": 37111, "s": 37103, "text": "Output:" }, { "code": null, "e": 37172, "s": 37111, "text": "13551674127875514537 is a random number between 0 and 184467" }, { "code": null, "e": 37543, "s": 37172, "text": "3. shuffle_order_engine: It is an engine adaptor class template that adapts a pseudo-random number generator Engine type so that the numbers are delivered in a different sequence.The object keeps a buffer of k generated numbers internally, and when requested, returns a randomly selected number within the buffer, replacing it with a value obtained from its base engine." }, { "code": null, "e": 37756, "s": 37543, "text": "operator(): It returns a new random number.The engine’s transition algorithm picks a value in the internal table (which is returned by the function) and replaces it with a new value obtained from its base engine." }, { "code": null, "e": 37811, "s": 37756, "text": "max: It returns the maximum value given by operator()." }, { "code": null, "e": 37866, "s": 37811, "text": "min: It returns the minimum value given by operator()." }, { "code": null, "e": 37870, "s": 37866, "text": "C++" }, { "code": "// C++ program to illustrate// the use of operator(),min and max// in shuffle_order_engine#include <iostream>#include <chrono>#include <random>using namespace std; int main (){ // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // ranlux24 is a standard instantiation // of discard_block_engine: ranlux24 generator (seed); //use of operator() cout << generator() << \" is a random number between \"; //use of max and min cout << generator.min() << \" and \" << generator.max(); return 0;}", "e": 38492, "s": 37870, "text": null }, { "code": null, "e": 38500, "s": 38492, "text": "Output:" }, { "code": null, "e": 38550, "s": 38500, "text": "9213395 is a random number between 0 and 16777215" }, { "code": null, "e": 38564, "s": 38550, "text": "sumitgumber28" }, { "code": null, "e": 38581, "s": 38564, "text": "akshaysingh98088" }, { "code": null, "e": 38585, "s": 38581, "text": "C++" }, { "code": null, "e": 38604, "s": 38585, "text": "Technical Scripter" }, { "code": null, "e": 38608, "s": 38604, "text": "CPP" }, { "code": null, "e": 38706, "s": 38608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38715, "s": 38706, "text": "Comments" }, { "code": null, "e": 38728, "s": 38715, "text": "Old Comments" }, { "code": null, "e": 38747, "s": 38728, "text": "Inheritance in C++" }, { "code": null, "e": 38790, "s": 38747, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 38810, "s": 38790, "text": "Constructors in C++" }, { "code": null, "e": 38834, "s": 38810, "text": "C++ Classes and Objects" }, { "code": null, "e": 38862, "s": 38834, "text": "Socket Programming in C/C++" }, { "code": null, "e": 38889, "s": 38862, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 38917, "s": 38889, "text": "Operator Overloading in C++" }, { "code": null, "e": 38952, "s": 38917, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 38976, "s": 38952, "text": "Copy Constructor in C++" } ]
Tryit Editor v3.7
Tryit: HTML footer element
[]
Using Snorkel For Multi-Label Annotation. | by Ori Cohen | Towards Data Science
Snorkel is a nice little package that allows us to use labeling functions (LFs) as simple as heuristics or keywords or as complex as algorithms and human annotators in order to create a labeled dataset for the purpose of training a classifier. “Snorkel is a system for programmatically building and managing training datasets without manual labeling. In Snorkel, users can develop large training datasets in hours or days rather than hand-labeling them over weeks or months.” — Snorkel.org The motivation to use snorkel in order to create multi-labels is simple. Snorkel allows us to use simple heuristics or keywords in order to create a supervised dataset. Using it as a labeling algorithm allows a certain level of clarity when we need to understand why a sample was assigned a certain class. You can also think of a scenario in which you created a heuristical multi-labeling algorithm that assigns a sparse amount of multi-labels; when your product or feature requires large quantities of multi-labels in order to give a higher value to your clients. It's worth noting that throughout the process, we are actually creating two classifiers, the first one using snorkel’s MajorityLabelVoter or LabelModel, the former gives us a majority vote as a baseline and the latter gives us the secret-sauce model that Snorkel is known for and the latter is to train a machine or deep-learning (MLDL) algorithm because we don't want to rely on the labeling functions that we created. We want to train a classifier that is not limited to our keywords, regexes, etc. We want a classifier that generalizes beyond what we gave it. Ideally, it will find correlations between, for example, tokens that we didn't account for in the labeling process to our final labels. First, we need to understand how to use Snorkel. Consider a sentiment classification task and the following sentences: 1. “the cake tasted really bad”, 2. “the cream is really good” & 3. “this food is fair”. These sentences are NEGATIVE, POSITIVE & NEUTRAL, respectively. Therefore, we will create several LFs that assign a label accordingly. from snorkel.labeling import labeling_function@labeling_function()def lf_keyword_good(x): return POSITIVE if "good" in x.text.lower() else ABSTAIN@labeling_function()def lf_keyword_bad(x): return NEGATIVE if "bad" in x.text.lower() else ABSTAIN@labeling_function()def lf_keyword_fair(x): return NEUTRAL if "fair" in x.text.lower() else ABSTAIN The rest of the process is easy, once you have many LFs you apply them on your pandas.DataFrame and train one of the models, i.e., MajorityLabelVoter or LabelModel. from snorkel.labeling import LabelModel, PandasLFApplier# Define the set of labeling functions (LFs)lfs = [lf_keyword_bad, lf_keyword_good, lf_keyword_fair]# Apply the LFs to the unlabeled training dataapplier = PandasLFApplier(lfs)L_train = applier.apply(df_train)# Train the label model and compute the training labelslabel_model = LabelModel(cardinality=3, verbose=True)label_model.fit(L_train, n_epochs=500, log_freq=50)df_train["label"] = label_model.predict(L=L_train, tie_break_policy="abstain") df_train[“label”] will contain ABSTAIN labels as well, therefore in order to further train our secondary classifier, we’ll have to filter them out. df_train = df_train[df_train.label != ABSTAIN] Again, the purpose of training a secondary classifier (Random forest in this example) on the filtered dataset is “to generalize beyond the coverage of the labeling functions and the LabelModel. — snorkel.org" from sklearn.ensemble import RandomForestClassifierclf = RandomForestClassifier()clf.fit(df_train.drop(['label'],axis=1), df_train["label"]) Snorkel can only be used out of the box as a multi-class labeler. To use it for Multi-label, you can do one of the following three methods: Use MajorityLabelVoter’s predict_proba() and assign all the classes that have a ‘probability’ ≥ 0. i.e., the first and the last [0.5, 0, 0.5]. We can think of it as a sample that resides in two clusters or two keywords from two classes that allows a sample to have multi labels. For example, “The hamburger was good and bad”.Use LabelModel’s predict_proba and assign all the classes in which probability is above the ‘knee’. You can use Kneed to figure it out. essentially our probabilities are softmax and only a handful will receive high values. Please note that from my empirical tests, there is a high correlation between MajorityLabelVoter’s probability values to LabelModel’s, i.e., the former is a “hard” softmax and the latter is what you expect from softmax. i.e., [0.5, 0, 0.5] vs [0.45, 0.06, 0.49], respectively.Train ‘one vs all’ models, for each class using MajorityLabelVoter or LabelModel and assign a multi-label according to the prediction. Note that you need to think of a strategy when considering ABSTAIN labels. Use MajorityLabelVoter’s predict_proba() and assign all the classes that have a ‘probability’ ≥ 0. i.e., the first and the last [0.5, 0, 0.5]. We can think of it as a sample that resides in two clusters or two keywords from two classes that allows a sample to have multi labels. For example, “The hamburger was good and bad”. Use LabelModel’s predict_proba and assign all the classes in which probability is above the ‘knee’. You can use Kneed to figure it out. essentially our probabilities are softmax and only a handful will receive high values. Please note that from my empirical tests, there is a high correlation between MajorityLabelVoter’s probability values to LabelModel’s, i.e., the former is a “hard” softmax and the latter is what you expect from softmax. i.e., [0.5, 0, 0.5] vs [0.45, 0.06, 0.49], respectively. Train ‘one vs all’ models, for each class using MajorityLabelVoter or LabelModel and assign a multi-label according to the prediction. Note that you need to think of a strategy when considering ABSTAIN labels. Because ‘1’ & ‘2’ gave similar outputs and the calculation to get multi-labels from ‘1’ was simpler, I chose to assign multi-labels based on 1. Please note that when a model assigns an ABSTAIN label, it can’t decide who is the winner. We observe this behavior in predict_proba()’s output. For example, consider the following probability vector: [1.0, 0, 0], the winner here is the first class. Now, consider the following vector: [0.5,0, 0.5], we see that isn't a clear winner, therefore, Snorkel will assign an ABSTAIN label. When we assign a label for each class that has a non-zero probability, we are in fact eliminating all ABSTAIN labels, labeling all the dataset and assigning a lot of multi-labels per sample. The following codes use a MajorityLabelVoter classifier and assign labels according to all the classes that have a higher than zero score. It's as simple as that :). from snorkel.labeling import MajorityLabelVoterfrom sklearn.preprocessing import MultiLabelBinarizerY = [['POSITIVE', 'NEGATIVE', 'NEUTRAL']]# fit a MultiLabelBinarizermlb = MultiLabelBinarizer()mlb.fit_transform(Y)# create a majority vote model and predictmajority_model = MajorityLabelVoter(cardinality=3)predictions = majority_model.predict_proba(L=L_test)df_multilabel = pd.DataFrame()df_multilabel['predict_proba'] = predictions.tolist()# get all the non zero indices which are the multi labelsdf_multilabel['multi_labels'] = df_multilabel['predict_proba'].apply(lambda x: np.nonzero(x)[0]) #transform to mlb for classification reportdf_multilabel['mlb_pred'] = df_multilabel['multi_labels'].apply(lambda x: mlb.transform([x])[0])print(df_multilabel.head())#convert to str in order to see how many multi labels did we gainmulti_label_string = df_multilabel.multi_labels.apply(lambda x: ", ".join(le.inverse_transform(x)))print(multi_label_string.value_counts()[:50])# print some metrics using classification report y_pred = df_multilabel.mlb_pred.apply(lambda x: list(x)).to_numpy().tolist()y_true = mlb.transform(Y.values).tolist()print(classification_report(y_true, y_pred, target_names = mlb.classes_)) That’s it, you have created multi labels for each sample. Please keep in mind that due to this methodology of using Snorkel, which is very greedy in terms of labeling strategy, you may get a very RECALL-ORIENTED model. Your experience will vary. Dr. Ori Cohen has a Ph.D. in Computer Science with a focus on machine-learning. He is a lead data-scientist at New Relic TLV, doing machine and deep learning research in the field of AIOps.
[ { "code": null, "e": 416, "s": 172, "text": "Snorkel is a nice little package that allows us to use labeling functions (LFs) as simple as heuristics or keywords or as complex as algorithms and human annotators in order to create a labeled dataset for the purpose of training a classifier." }, { "code": null, "e": 662, "s": 416, "text": "“Snorkel is a system for programmatically building and managing training datasets without manual labeling. In Snorkel, users can develop large training datasets in hours or days rather than hand-labeling them over weeks or months.” — Snorkel.org" }, { "code": null, "e": 1227, "s": 662, "text": "The motivation to use snorkel in order to create multi-labels is simple. Snorkel allows us to use simple heuristics or keywords in order to create a supervised dataset. Using it as a labeling algorithm allows a certain level of clarity when we need to understand why a sample was assigned a certain class. You can also think of a scenario in which you created a heuristical multi-labeling algorithm that assigns a sparse amount of multi-labels; when your product or feature requires large quantities of multi-labels in order to give a higher value to your clients." }, { "code": null, "e": 1926, "s": 1227, "text": "It's worth noting that throughout the process, we are actually creating two classifiers, the first one using snorkel’s MajorityLabelVoter or LabelModel, the former gives us a majority vote as a baseline and the latter gives us the secret-sauce model that Snorkel is known for and the latter is to train a machine or deep-learning (MLDL) algorithm because we don't want to rely on the labeling functions that we created. We want to train a classifier that is not limited to our keywords, regexes, etc. We want a classifier that generalizes beyond what we gave it. Ideally, it will find correlations between, for example, tokens that we didn't account for in the labeling process to our final labels." }, { "code": null, "e": 2269, "s": 1926, "text": "First, we need to understand how to use Snorkel. Consider a sentiment classification task and the following sentences: 1. “the cake tasted really bad”, 2. “the cream is really good” & 3. “this food is fair”. These sentences are NEGATIVE, POSITIVE & NEUTRAL, respectively. Therefore, we will create several LFs that assign a label accordingly." }, { "code": null, "e": 2622, "s": 2269, "text": "from snorkel.labeling import labeling_function@labeling_function()def lf_keyword_good(x): return POSITIVE if \"good\" in x.text.lower() else ABSTAIN@labeling_function()def lf_keyword_bad(x): return NEGATIVE if \"bad\" in x.text.lower() else ABSTAIN@labeling_function()def lf_keyword_fair(x): return NEUTRAL if \"fair\" in x.text.lower() else ABSTAIN" }, { "code": null, "e": 2787, "s": 2622, "text": "The rest of the process is easy, once you have many LFs you apply them on your pandas.DataFrame and train one of the models, i.e., MajorityLabelVoter or LabelModel." }, { "code": null, "e": 3290, "s": 2787, "text": "from snorkel.labeling import LabelModel, PandasLFApplier# Define the set of labeling functions (LFs)lfs = [lf_keyword_bad, lf_keyword_good, lf_keyword_fair]# Apply the LFs to the unlabeled training dataapplier = PandasLFApplier(lfs)L_train = applier.apply(df_train)# Train the label model and compute the training labelslabel_model = LabelModel(cardinality=3, verbose=True)label_model.fit(L_train, n_epochs=500, log_freq=50)df_train[\"label\"] = label_model.predict(L=L_train, tie_break_policy=\"abstain\")" }, { "code": null, "e": 3438, "s": 3290, "text": "df_train[“label”] will contain ABSTAIN labels as well, therefore in order to further train our secondary classifier, we’ll have to filter them out." }, { "code": null, "e": 3485, "s": 3438, "text": "df_train = df_train[df_train.label != ABSTAIN]" }, { "code": null, "e": 3694, "s": 3485, "text": "Again, the purpose of training a secondary classifier (Random forest in this example) on the filtered dataset is “to generalize beyond the coverage of the labeling functions and the LabelModel. — snorkel.org\"" }, { "code": null, "e": 3835, "s": 3694, "text": "from sklearn.ensemble import RandomForestClassifierclf = RandomForestClassifier()clf.fit(df_train.drop(['label'],axis=1), df_train[\"label\"])" }, { "code": null, "e": 3975, "s": 3835, "text": "Snorkel can only be used out of the box as a multi-class labeler. To use it for Multi-label, you can do one of the following three methods:" }, { "code": null, "e": 5009, "s": 3975, "text": "Use MajorityLabelVoter’s predict_proba() and assign all the classes that have a ‘probability’ ≥ 0. i.e., the first and the last [0.5, 0, 0.5]. We can think of it as a sample that resides in two clusters or two keywords from two classes that allows a sample to have multi labels. For example, “The hamburger was good and bad”.Use LabelModel’s predict_proba and assign all the classes in which probability is above the ‘knee’. You can use Kneed to figure it out. essentially our probabilities are softmax and only a handful will receive high values. Please note that from my empirical tests, there is a high correlation between MajorityLabelVoter’s probability values to LabelModel’s, i.e., the former is a “hard” softmax and the latter is what you expect from softmax. i.e., [0.5, 0, 0.5] vs [0.45, 0.06, 0.49], respectively.Train ‘one vs all’ models, for each class using MajorityLabelVoter or LabelModel and assign a multi-label according to the prediction. Note that you need to think of a strategy when considering ABSTAIN labels." }, { "code": null, "e": 5335, "s": 5009, "text": "Use MajorityLabelVoter’s predict_proba() and assign all the classes that have a ‘probability’ ≥ 0. i.e., the first and the last [0.5, 0, 0.5]. We can think of it as a sample that resides in two clusters or two keywords from two classes that allows a sample to have multi labels. For example, “The hamburger was good and bad”." }, { "code": null, "e": 5835, "s": 5335, "text": "Use LabelModel’s predict_proba and assign all the classes in which probability is above the ‘knee’. You can use Kneed to figure it out. essentially our probabilities are softmax and only a handful will receive high values. Please note that from my empirical tests, there is a high correlation between MajorityLabelVoter’s probability values to LabelModel’s, i.e., the former is a “hard” softmax and the latter is what you expect from softmax. i.e., [0.5, 0, 0.5] vs [0.45, 0.06, 0.49], respectively." }, { "code": null, "e": 6045, "s": 5835, "text": "Train ‘one vs all’ models, for each class using MajorityLabelVoter or LabelModel and assign a multi-label according to the prediction. Note that you need to think of a strategy when considering ABSTAIN labels." }, { "code": null, "e": 6189, "s": 6045, "text": "Because ‘1’ & ‘2’ gave similar outputs and the calculation to get multi-labels from ‘1’ was simpler, I chose to assign multi-labels based on 1." }, { "code": null, "e": 6572, "s": 6189, "text": "Please note that when a model assigns an ABSTAIN label, it can’t decide who is the winner. We observe this behavior in predict_proba()’s output. For example, consider the following probability vector: [1.0, 0, 0], the winner here is the first class. Now, consider the following vector: [0.5,0, 0.5], we see that isn't a clear winner, therefore, Snorkel will assign an ABSTAIN label." }, { "code": null, "e": 6763, "s": 6572, "text": "When we assign a label for each class that has a non-zero probability, we are in fact eliminating all ABSTAIN labels, labeling all the dataset and assigning a lot of multi-labels per sample." }, { "code": null, "e": 6929, "s": 6763, "text": "The following codes use a MajorityLabelVoter classifier and assign labels according to all the classes that have a higher than zero score. It's as simple as that :)." }, { "code": null, "e": 8143, "s": 6929, "text": "from snorkel.labeling import MajorityLabelVoterfrom sklearn.preprocessing import MultiLabelBinarizerY = [['POSITIVE', 'NEGATIVE', 'NEUTRAL']]# fit a MultiLabelBinarizermlb = MultiLabelBinarizer()mlb.fit_transform(Y)# create a majority vote model and predictmajority_model = MajorityLabelVoter(cardinality=3)predictions = majority_model.predict_proba(L=L_test)df_multilabel = pd.DataFrame()df_multilabel['predict_proba'] = predictions.tolist()# get all the non zero indices which are the multi labelsdf_multilabel['multi_labels'] = df_multilabel['predict_proba'].apply(lambda x: np.nonzero(x)[0]) #transform to mlb for classification reportdf_multilabel['mlb_pred'] = df_multilabel['multi_labels'].apply(lambda x: mlb.transform([x])[0])print(df_multilabel.head())#convert to str in order to see how many multi labels did we gainmulti_label_string = df_multilabel.multi_labels.apply(lambda x: \", \".join(le.inverse_transform(x)))print(multi_label_string.value_counts()[:50])# print some metrics using classification report y_pred = df_multilabel.mlb_pred.apply(lambda x: list(x)).to_numpy().tolist()y_true = mlb.transform(Y.values).tolist()print(classification_report(y_true, y_pred, target_names = mlb.classes_))" }, { "code": null, "e": 8389, "s": 8143, "text": "That’s it, you have created multi labels for each sample. Please keep in mind that due to this methodology of using Snorkel, which is very greedy in terms of labeling strategy, you may get a very RECALL-ORIENTED model. Your experience will vary." } ]
Maximize sum of products at corresponding indices in two arrays by reversing at most one subarray in first Array - GeeksforGeeks
17 Jan, 2022 Given two arrays A and B of size N, the task is to maximize the sum of A[i]*B[i] across all values of i from 0 to N-1 by reversing at most one subarray of array A. Examples: Input: N = 4, A = [5, 1, 2, 3], B = [1, 4, 3, 2]Output: 33Explanation: Array A after reversing the subarray A[0, 1] will become [1, 5, 2, 3]. Sum of A[i]*B[i] after the reversal becomes 1*1+5*4+2*3+3*2 = 33. Input: N = 3, A = [6, 7, 3], B = [5, 1, 7]Output: 82 Naive Approach: One simple way to solve this problem is to check for all possible subarrays of A and reverse them one by one to find the maximum possible value of the sum. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program of the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum sum of A[i]*B[i]// across all values of i from 0 to N-1 by reversing// at most one subarray of array Aint maxSum(vector<int>& A, vector<int>& B){ int N = A.size(); // Initialising maximum possible sum variable int maxPosSum = 0; // Iterating for all subarrays for (int L = 0; L < N - 1; L++) { for (int R = L; R < N; R++) { // Variable for storing the sum after reversing // The subarray from L to R int curSum = 0; for (int i = 0; i < N; i++) { // Checking if the current index is in the // reversed subarray if (i >= L && i <= R) curSum += A[L + R - i] * B[i]; else curSum += A[i] * B[i]; } // Updating the answer maxPosSum = max(maxPosSum, curSum); } } // Returning the Maximum Possible Sum of product return maxPosSum;} // Driver Codeint main(){ // Given Input int N = 4; vector<int> A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 }; cout << maxSum(A, B);} // Java code to implement above approachimport java.util.*;public class GFG { // Function to find the maximum sum of A[i]*B[i] // across all values of i from 0 to N-1 by reversing // at most one subarray of array A static int maxSum(int []A, int []B) { int N = A.length; // Initialising maximum possible sum variable int maxPosSum = 0; // Iterating for all subarrays for (int L = 0; L < N - 1; L++) { for (int R = L; R < N; R++) { // Variable for storing the sum after reversing // The subarray from L to R int curSum = 0; for (int i = 0; i < N; i++) { // Checking if the current index is in the // reversed subarray if (i >= L && i <= R) curSum += A[L + R - i] * B[i]; else curSum += A[i] * B[i]; } // Updating the answer maxPosSum = Math.max(maxPosSum, curSum); } } // Returning the Maximum Possible Sum of product return maxPosSum; } // Driver code public static void main(String args[]) { // Given Input int N = 4; int []A = { 5, 1, 2, 3 }; int []B = { 1, 4, 3, 2 }; System.out.println(maxSum(A, B)); }} // This code is contributed by Samim Hossain Mondal. # Python code for the above approach # Function to find the maximum sum of A[i]*B[i]# across all values of i from 0 to N-1 by reversing# at most one subarray of array Adef maxSum(A, B): N = len(A) # Initialising maximum possible sum variable maxPosSum = 0 # Iterating for all subarrays for L in range(N - 1): for R in range(L, N): # Variable for storing the sum after reversing # The subarray from L to R curSum = 0 for i in range(N): # Checking if the current index is in the # reversed subarray if (i >= L and i <= R): curSum += A[L + R - i] * B[i] else: curSum += A[i] * B[i] # Updating the answer maxPosSum = max(maxPosSum, curSum) # Returning the Maximum Possible Sum of product return maxPosSum # Driver Code # Given InputN = 4A = [5, 1, 2, 3]B = [1, 4, 3, 2]print(maxSum(A, B)) # This code is contributed by gfgking // C# code to implement above approachusing System;public class GFG { // Function to find the maximum sum of A[i]*B[i] // across all values of i from 0 to N-1 by reversing // at most one subarray of array A static int maxSum(int []A, int []B) { int N = A.Length; // Initialising maximum possible sum variable int maxPosSum = 0; // Iterating for all subarrays for (int L = 0; L < N - 1; L++) { for (int R = L; R < N; R++) { // Variable for storing the sum after reversing // The subarray from L to R int curSum = 0; for (int i = 0; i < N; i++) { // Checking if the current index is in the // reversed subarray if (i >= L && i <= R) curSum += A[L + R - i] * B[i]; else curSum += A[i] * B[i]; } // Updating the answer maxPosSum = Math.Max(maxPosSum, curSum); } } // Returning the Maximum Possible Sum of product return maxPosSum; } // Driver code public static void Main() { // Given Input int []A = { 5, 1, 2, 3 }; int []B = { 1, 4, 3, 2 }; Console.Write(maxSum(A, B)); }} // This code is contributed by Saurabh Jaiswal <script> // JavaScript code for the above approach // Function to find the maximum sum of A[i]*B[i] // across all values of i from 0 to N-1 by reversing // at most one subarray of array A function maxSum(A, B) { let N = A.length; // Initialising maximum possible sum variable let maxPosSum = 0; // Iterating for all subarrays for (let L = 0; L < N - 1; L++) { for (let R = L; R < N; R++) { // Variable for storing the sum after reversing // The subarray from L to R let curSum = 0; for (let i = 0; i < N; i++) { // Checking if the current index is in the // reversed subarray if (i >= L && i <= R) curSum += A[L + R - i] * B[i]; else curSum += A[i] * B[i]; } // Updating the answer maxPosSum = Math.max(maxPosSum, curSum); } } // Returning the Maximum Possible Sum of product return maxPosSum; } // Driver Code // Given Input let N = 4; let A = [5, 1, 2, 3], B = [1, 4, 3, 2]; document.write(maxSum(A, B)); // This code is contributed by Potta Lokesh </script> 33 Time Complexity: O(N3)Auxiliary Space: O(1) Efficient Approach: The above problem can be solved with the use of dynamic programming. Follow the below steps to solve this problem: Let dp[L][[R] represent the sum of the product of A[i] and B[i] after reversing subarray A[L, R]. Observe that if the subarray A[L, R] is reversed, the subarray A[L+1, R-1] is also reversed. Therefore, dp[L][R] can be calculated by the use of dp[L+1][R-1] and by using the formula: dp[L][R] = dp[L+1][R-1]+ (A[R] * B[L]) – (A[L] * B[L]) + (A[L] * B[R]) – (A[R] * B[R]) Because In the calculation of dp[L+1][R-1], A[L]*B[L] and A[R]*B[R] is added whereas for the calculation dp[L][R], A[R]*B[L] and A[L]*B[R ]is added. Hence we need to subtract A[L]*B[L] and A[R]*B[R] and add A[R]*B[L] and A[L]*B[R] to dp[L+1][R-1] for calculation of dp[L][R]. Print the answer according to the above observation. Below is the implementation of the dynamic programming approach. C++ Java Python C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum sum of A[i]*B[i]// across all values of i from 0 to N-1 by reversing// at most one subarray of array Aint maxSum(vector<int>& A, vector<int>& B){ int N = A.size(); // Initialising maximum possible sum variable int maxPosSum = 0; int dp[N][N]; // Initialising the dp array memset(dp, 0, sizeof(dp)); // Value of maxPosSum when no subarray is reversed for (int i = 0; i < N; i++) maxPosSum += A[i] * B[i]; // Initialising dp for subarray of length 1 for (int i = 0; i < N; i++) dp[i][i] = maxPosSum; // Initialising dp for subarray of length 2 for (int i = 0; i < N - 1; i++) { int R = i + 1; int L = i; dp[L][R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } // Calculating the complete dp array for (int R = 0; R < N; R++) { for (int L = 0; L < N; L++) { // If length of subarray is less 3, then // continuing if (R - L + 1 < 3) continue; dp[L][R] = dp[L + 1][R - 1] + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } } // Updating the maxPosSum variable for (int L = 0; L < N; L++) { for (int R = L; R < N; R++) { maxPosSum = max(maxPosSum, dp[L][R]); } } // Returning the maximum possible sum of product return maxPosSum;} // Driver Codeint main(){ // Given Input vector<int> A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 }; cout << maxSum(A, B); return 0;} // Java implementation of the above approachimport java.util.*; class GFG{ // Function to find the maximum sum of A[i]*B[i]// across all values of i from 0 to N-1 by reversing// at most one subarray of array Astatic int maxSum(int[] A, int[] B){ int N = A.length; // Initialising maximum possible sum variable int maxPosSum = 0; int [][]dp = new int[N][N]; // Value of maxPosSum when no subarray is reversed for (int i = 0; i < N; i++) maxPosSum += A[i] * B[i]; // Initialising dp for subarray of length 1 for (int i = 0; i < N; i++) dp[i][i] = maxPosSum; // Initialising dp for subarray of length 2 for (int i = 0; i < N - 1; i++) { int R = i + 1; int L = i; dp[L][R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } // Calculating the complete dp array for (int R = 0; R < N; R++) { for (int L = 0; L < N; L++) { // If length of subarray is less 3, then // continuing if (R - L + 1 < 3) continue; dp[L][R] = dp[L + 1][R - 1] + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } } // Updating the maxPosSum variable for (int L = 0; L < N; L++) { for (int R = L; R < N; R++) { maxPosSum = Math.max(maxPosSum, dp[L][R]); } } // Returning the maximum possible sum of product return maxPosSum;} // Driver Codepublic static void main(String[] args){ // Given Input int[] A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 }; System.out.print(maxSum(A, B));}} // This code is contributed by 29AjayKumar # Python implementation of the above approach # Function to find the maximum sum of A[i]*B[i]# across all values of i from 0 to N-1 by reversing# at most one subarray of array Adef maxSum(A, B): N = len(A) # Initialising maximum possible sum variable maxPosSum = 0 # Initialising the dp array dp = ([[0 for i in range(N)] for i in range(N)]) # Value of maxPosSum when no subarray is reversed for i in range(0, N): maxPosSum = maxPosSum + (A[i] * B[i]) # Initialising dp for subarray of length 1 for i in range(0, N): dp[i][i] = maxPosSum # Initialising dp for subarray of length 2 for i in range(0, N - 1): R = i + 1 L = i dp[L][R] = maxPosSum + (A[R] * B[L]) - \ (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]) # Calculating the complete dp array for R in range(0, N): for L in range(0, N): # If length of subarray is less 3, then # continuing if (R - L + 1 < 3): continue dp[L][R] = dp[L + 1][R - 1] + \ (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]) # Updating the maxPosSum variable for R in range(0, N): for L in range(0, N): maxPosSum = max(maxPosSum, dp[L][R]) # Returning the maximum possible sum of product return maxPosSum # Driver Code# Given InputA = [5, 1, 2, 3]B = [1, 4, 3, 2] print(maxSum(A, B)) # This code is contributed by Samim Hossain Mondal. // C# implementation of the above approachusing System;class GFG { // Function to find the maximum sum of A[i]*B[i] // across all values of i from 0 to N-1 by reversing // at most one subarray of array A static int maxSum(int[] A, int[] B) { int N = A.Length; // Initialising maximum possible sum variable int maxPosSum = 0; int[, ] dp = new int[N, N]; // Initialising the dp array // memset(dp, 0, sizeof(dp)); // Value of maxPosSum when no subarray is reversed for (int i = 0; i < N; i++) maxPosSum += A[i] * B[i]; // Initialising dp for subarray of length 1 for (int i = 0; i < N; i++) dp[i, i] = maxPosSum; // Initialising dp for subarray of length 2 for (int i = 0; i < N - 1; i++) { int R = i + 1; int L = i; dp[L, R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } // Calculating the complete dp array for (int R = 0; R < N; R++) { for (int L = 0; L < N; L++) { // If length of subarray is less 3, then // continuing if (R - L + 1 < 3) continue; dp[L, R] = dp[L + 1, R - 1] + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } } // Updating the maxPosSum variable for (int L = 0; L < N; L++) { for (int R = L; R < N; R++) { maxPosSum = Math.Max(maxPosSum, dp[L, R]); } } // Returning the maximum possible sum of product return maxPosSum; } // Driver Code public static void Main() { // Given Input int[] A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 }; Console.WriteLine(maxSum(A, B)); }} // This code is contributed by ukasp. <script>// javascript implementation of the above approach // Function to find the maximum sum of A[i]*B[i]// across all values of i from 0 to N-1 by reversing// at most one subarray of array Afunction maxSum(A, B){ var N = A.length; // Initialising maximum possible sum variable var maxPosSum = 0; var dp = Array(N).fill(0).map(x => Array(N).fill(0)); // Value of maxPosSum when no subarray is reversed for (var i = 0; i < N; i++) maxPosSum += A[i] * B[i]; // Initialising dp for subarray of length 1 for (var i = 0; i < N; i++) dp[i][i] = maxPosSum; // Initialising dp for subarray of length 2 for (var i = 0; i < N - 1; i++) { var R = i + 1; var L = i; dp[L][R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } // Calculating the complete dp array for (var R = 0; R < N; R++) { for (var L = 0; L < N; L++) { // If length of subarray is less 3, then // continuing if (R - L + 1 < 3) continue; dp[L][R] = dp[L + 1][R - 1] + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } } // Updating the maxPosSum variable for (var L = 0; L < N; L++) { for (var R = L; R < N; R++) { maxPosSum = Math.max(maxPosSum, dp[L][R]); } } // Returning the maximum possible sum of product return maxPosSum;} // Driver Code// Given Inputvar A = [ 5, 1, 2, 3 ], B = [ 1, 4, 3, 2 ]; document.write(maxSum(A, B)); // This code is contributed by 29AjayKumar</script> 33 Time Complexity: O(N2)Auxiliary Space: O(N2) lokeshpotta20 gfgking samim2000 _saurabh_jaiswal ukasp 29AjayKumar subarray Arrays Dynamic Programming Mathematical Arrays Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Trapping Rain Water Building Heap from Array Program to find sum of elements in a given array Reversal algorithm for array rotation 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Bellman–Ford Algorithm | DP-23 Longest Common Subsequence | DP-4 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 24796, "s": 24768, "text": "\n17 Jan, 2022" }, { "code": null, "e": 24960, "s": 24796, "text": "Given two arrays A and B of size N, the task is to maximize the sum of A[i]*B[i] across all values of i from 0 to N-1 by reversing at most one subarray of array A." }, { "code": null, "e": 24970, "s": 24960, "text": "Examples:" }, { "code": null, "e": 25178, "s": 24970, "text": "Input: N = 4, A = [5, 1, 2, 3], B = [1, 4, 3, 2]Output: 33Explanation: Array A after reversing the subarray A[0, 1] will become [1, 5, 2, 3]. Sum of A[i]*B[i] after the reversal becomes 1*1+5*4+2*3+3*2 = 33." }, { "code": null, "e": 25231, "s": 25178, "text": "Input: N = 3, A = [6, 7, 3], B = [5, 1, 7]Output: 82" }, { "code": null, "e": 25403, "s": 25231, "text": "Naive Approach: One simple way to solve this problem is to check for all possible subarrays of A and reverse them one by one to find the maximum possible value of the sum." }, { "code": null, "e": 25454, "s": 25403, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25458, "s": 25454, "text": "C++" }, { "code": null, "e": 25463, "s": 25458, "text": "Java" }, { "code": null, "e": 25471, "s": 25463, "text": "Python3" }, { "code": null, "e": 25474, "s": 25471, "text": "C#" }, { "code": null, "e": 25485, "s": 25474, "text": "Javascript" }, { "code": "// C++ program of the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum sum of A[i]*B[i]// across all values of i from 0 to N-1 by reversing// at most one subarray of array Aint maxSum(vector<int>& A, vector<int>& B){ int N = A.size(); // Initialising maximum possible sum variable int maxPosSum = 0; // Iterating for all subarrays for (int L = 0; L < N - 1; L++) { for (int R = L; R < N; R++) { // Variable for storing the sum after reversing // The subarray from L to R int curSum = 0; for (int i = 0; i < N; i++) { // Checking if the current index is in the // reversed subarray if (i >= L && i <= R) curSum += A[L + R - i] * B[i]; else curSum += A[i] * B[i]; } // Updating the answer maxPosSum = max(maxPosSum, curSum); } } // Returning the Maximum Possible Sum of product return maxPosSum;} // Driver Codeint main(){ // Given Input int N = 4; vector<int> A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 }; cout << maxSum(A, B);}", "e": 26682, "s": 25485, "text": null }, { "code": "// Java code to implement above approachimport java.util.*;public class GFG { // Function to find the maximum sum of A[i]*B[i] // across all values of i from 0 to N-1 by reversing // at most one subarray of array A static int maxSum(int []A, int []B) { int N = A.length; // Initialising maximum possible sum variable int maxPosSum = 0; // Iterating for all subarrays for (int L = 0; L < N - 1; L++) { for (int R = L; R < N; R++) { // Variable for storing the sum after reversing // The subarray from L to R int curSum = 0; for (int i = 0; i < N; i++) { // Checking if the current index is in the // reversed subarray if (i >= L && i <= R) curSum += A[L + R - i] * B[i]; else curSum += A[i] * B[i]; } // Updating the answer maxPosSum = Math.max(maxPosSum, curSum); } } // Returning the Maximum Possible Sum of product return maxPosSum; } // Driver code public static void main(String args[]) { // Given Input int N = 4; int []A = { 5, 1, 2, 3 }; int []B = { 1, 4, 3, 2 }; System.out.println(maxSum(A, B)); }} // This code is contributed by Samim Hossain Mondal.", "e": 27923, "s": 26682, "text": null }, { "code": "# Python code for the above approach # Function to find the maximum sum of A[i]*B[i]# across all values of i from 0 to N-1 by reversing# at most one subarray of array Adef maxSum(A, B): N = len(A) # Initialising maximum possible sum variable maxPosSum = 0 # Iterating for all subarrays for L in range(N - 1): for R in range(L, N): # Variable for storing the sum after reversing # The subarray from L to R curSum = 0 for i in range(N): # Checking if the current index is in the # reversed subarray if (i >= L and i <= R): curSum += A[L + R - i] * B[i] else: curSum += A[i] * B[i] # Updating the answer maxPosSum = max(maxPosSum, curSum) # Returning the Maximum Possible Sum of product return maxPosSum # Driver Code # Given InputN = 4A = [5, 1, 2, 3]B = [1, 4, 3, 2]print(maxSum(A, B)) # This code is contributed by gfgking", "e": 28943, "s": 27923, "text": null }, { "code": "// C# code to implement above approachusing System;public class GFG { // Function to find the maximum sum of A[i]*B[i] // across all values of i from 0 to N-1 by reversing // at most one subarray of array A static int maxSum(int []A, int []B) { int N = A.Length; // Initialising maximum possible sum variable int maxPosSum = 0; // Iterating for all subarrays for (int L = 0; L < N - 1; L++) { for (int R = L; R < N; R++) { // Variable for storing the sum after reversing // The subarray from L to R int curSum = 0; for (int i = 0; i < N; i++) { // Checking if the current index is in the // reversed subarray if (i >= L && i <= R) curSum += A[L + R - i] * B[i]; else curSum += A[i] * B[i]; } // Updating the answer maxPosSum = Math.Max(maxPosSum, curSum); } } // Returning the Maximum Possible Sum of product return maxPosSum; } // Driver code public static void Main() { // Given Input int []A = { 5, 1, 2, 3 }; int []B = { 1, 4, 3, 2 }; Console.Write(maxSum(A, B)); }} // This code is contributed by Saurabh Jaiswal", "e": 30138, "s": 28943, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to find the maximum sum of A[i]*B[i] // across all values of i from 0 to N-1 by reversing // at most one subarray of array A function maxSum(A, B) { let N = A.length; // Initialising maximum possible sum variable let maxPosSum = 0; // Iterating for all subarrays for (let L = 0; L < N - 1; L++) { for (let R = L; R < N; R++) { // Variable for storing the sum after reversing // The subarray from L to R let curSum = 0; for (let i = 0; i < N; i++) { // Checking if the current index is in the // reversed subarray if (i >= L && i <= R) curSum += A[L + R - i] * B[i]; else curSum += A[i] * B[i]; } // Updating the answer maxPosSum = Math.max(maxPosSum, curSum); } } // Returning the Maximum Possible Sum of product return maxPosSum; } // Driver Code // Given Input let N = 4; let A = [5, 1, 2, 3], B = [1, 4, 3, 2]; document.write(maxSum(A, B)); // This code is contributed by Potta Lokesh </script>", "e": 31298, "s": 30138, "text": null }, { "code": null, "e": 31304, "s": 31301, "text": "33" }, { "code": null, "e": 31350, "s": 31306, "text": "Time Complexity: O(N3)Auxiliary Space: O(1)" }, { "code": null, "e": 31487, "s": 31352, "text": "Efficient Approach: The above problem can be solved with the use of dynamic programming. Follow the below steps to solve this problem:" }, { "code": null, "e": 31587, "s": 31489, "text": "Let dp[L][[R] represent the sum of the product of A[i] and B[i] after reversing subarray A[L, R]." }, { "code": null, "e": 31771, "s": 31587, "text": "Observe that if the subarray A[L, R] is reversed, the subarray A[L+1, R-1] is also reversed. Therefore, dp[L][R] can be calculated by the use of dp[L+1][R-1] and by using the formula:" }, { "code": null, "e": 31859, "s": 31771, "text": " dp[L][R] = dp[L+1][R-1]+ (A[R] * B[L]) – (A[L] * B[L]) + (A[L] * B[R]) – (A[R] * B[R])" }, { "code": null, "e": 32008, "s": 31859, "text": "Because In the calculation of dp[L+1][R-1], A[L]*B[L] and A[R]*B[R] is added whereas for the calculation dp[L][R], A[R]*B[L] and A[L]*B[R ]is added." }, { "code": null, "e": 32135, "s": 32008, "text": "Hence we need to subtract A[L]*B[L] and A[R]*B[R] and add A[R]*B[L] and A[L]*B[R] to dp[L+1][R-1] for calculation of dp[L][R]." }, { "code": null, "e": 32188, "s": 32135, "text": "Print the answer according to the above observation." }, { "code": null, "e": 32255, "s": 32190, "text": "Below is the implementation of the dynamic programming approach." }, { "code": null, "e": 32261, "s": 32257, "text": "C++" }, { "code": null, "e": 32266, "s": 32261, "text": "Java" }, { "code": null, "e": 32273, "s": 32266, "text": "Python" }, { "code": null, "e": 32276, "s": 32273, "text": "C#" }, { "code": null, "e": 32287, "s": 32276, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum sum of A[i]*B[i]// across all values of i from 0 to N-1 by reversing// at most one subarray of array Aint maxSum(vector<int>& A, vector<int>& B){ int N = A.size(); // Initialising maximum possible sum variable int maxPosSum = 0; int dp[N][N]; // Initialising the dp array memset(dp, 0, sizeof(dp)); // Value of maxPosSum when no subarray is reversed for (int i = 0; i < N; i++) maxPosSum += A[i] * B[i]; // Initialising dp for subarray of length 1 for (int i = 0; i < N; i++) dp[i][i] = maxPosSum; // Initialising dp for subarray of length 2 for (int i = 0; i < N - 1; i++) { int R = i + 1; int L = i; dp[L][R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } // Calculating the complete dp array for (int R = 0; R < N; R++) { for (int L = 0; L < N; L++) { // If length of subarray is less 3, then // continuing if (R - L + 1 < 3) continue; dp[L][R] = dp[L + 1][R - 1] + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } } // Updating the maxPosSum variable for (int L = 0; L < N; L++) { for (int R = L; R < N; R++) { maxPosSum = max(maxPosSum, dp[L][R]); } } // Returning the maximum possible sum of product return maxPosSum;} // Driver Codeint main(){ // Given Input vector<int> A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 }; cout << maxSum(A, B); return 0;}", "e": 33987, "s": 32287, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to find the maximum sum of A[i]*B[i]// across all values of i from 0 to N-1 by reversing// at most one subarray of array Astatic int maxSum(int[] A, int[] B){ int N = A.length; // Initialising maximum possible sum variable int maxPosSum = 0; int [][]dp = new int[N][N]; // Value of maxPosSum when no subarray is reversed for (int i = 0; i < N; i++) maxPosSum += A[i] * B[i]; // Initialising dp for subarray of length 1 for (int i = 0; i < N; i++) dp[i][i] = maxPosSum; // Initialising dp for subarray of length 2 for (int i = 0; i < N - 1; i++) { int R = i + 1; int L = i; dp[L][R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } // Calculating the complete dp array for (int R = 0; R < N; R++) { for (int L = 0; L < N; L++) { // If length of subarray is less 3, then // continuing if (R - L + 1 < 3) continue; dp[L][R] = dp[L + 1][R - 1] + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } } // Updating the maxPosSum variable for (int L = 0; L < N; L++) { for (int R = L; R < N; R++) { maxPosSum = Math.max(maxPosSum, dp[L][R]); } } // Returning the maximum possible sum of product return maxPosSum;} // Driver Codepublic static void main(String[] args){ // Given Input int[] A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 }; System.out.print(maxSum(A, B));}} // This code is contributed by 29AjayKumar", "e": 35687, "s": 33987, "text": null }, { "code": "# Python implementation of the above approach # Function to find the maximum sum of A[i]*B[i]# across all values of i from 0 to N-1 by reversing# at most one subarray of array Adef maxSum(A, B): N = len(A) # Initialising maximum possible sum variable maxPosSum = 0 # Initialising the dp array dp = ([[0 for i in range(N)] for i in range(N)]) # Value of maxPosSum when no subarray is reversed for i in range(0, N): maxPosSum = maxPosSum + (A[i] * B[i]) # Initialising dp for subarray of length 1 for i in range(0, N): dp[i][i] = maxPosSum # Initialising dp for subarray of length 2 for i in range(0, N - 1): R = i + 1 L = i dp[L][R] = maxPosSum + (A[R] * B[L]) - \\ (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]) # Calculating the complete dp array for R in range(0, N): for L in range(0, N): # If length of subarray is less 3, then # continuing if (R - L + 1 < 3): continue dp[L][R] = dp[L + 1][R - 1] + \\ (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]) # Updating the maxPosSum variable for R in range(0, N): for L in range(0, N): maxPosSum = max(maxPosSum, dp[L][R]) # Returning the maximum possible sum of product return maxPosSum # Driver Code# Given InputA = [5, 1, 2, 3]B = [1, 4, 3, 2] print(maxSum(A, B)) # This code is contributed by Samim Hossain Mondal.", "e": 37180, "s": 35687, "text": null }, { "code": "// C# implementation of the above approachusing System;class GFG { // Function to find the maximum sum of A[i]*B[i] // across all values of i from 0 to N-1 by reversing // at most one subarray of array A static int maxSum(int[] A, int[] B) { int N = A.Length; // Initialising maximum possible sum variable int maxPosSum = 0; int[, ] dp = new int[N, N]; // Initialising the dp array // memset(dp, 0, sizeof(dp)); // Value of maxPosSum when no subarray is reversed for (int i = 0; i < N; i++) maxPosSum += A[i] * B[i]; // Initialising dp for subarray of length 1 for (int i = 0; i < N; i++) dp[i, i] = maxPosSum; // Initialising dp for subarray of length 2 for (int i = 0; i < N - 1; i++) { int R = i + 1; int L = i; dp[L, R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } // Calculating the complete dp array for (int R = 0; R < N; R++) { for (int L = 0; L < N; L++) { // If length of subarray is less 3, then // continuing if (R - L + 1 < 3) continue; dp[L, R] = dp[L + 1, R - 1] + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } } // Updating the maxPosSum variable for (int L = 0; L < N; L++) { for (int R = L; R < N; R++) { maxPosSum = Math.Max(maxPosSum, dp[L, R]); } } // Returning the maximum possible sum of product return maxPosSum; } // Driver Code public static void Main() { // Given Input int[] A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 }; Console.WriteLine(maxSum(A, B)); }} // This code is contributed by ukasp.", "e": 39150, "s": 37180, "text": null }, { "code": "<script>// javascript implementation of the above approach // Function to find the maximum sum of A[i]*B[i]// across all values of i from 0 to N-1 by reversing// at most one subarray of array Afunction maxSum(A, B){ var N = A.length; // Initialising maximum possible sum variable var maxPosSum = 0; var dp = Array(N).fill(0).map(x => Array(N).fill(0)); // Value of maxPosSum when no subarray is reversed for (var i = 0; i < N; i++) maxPosSum += A[i] * B[i]; // Initialising dp for subarray of length 1 for (var i = 0; i < N; i++) dp[i][i] = maxPosSum; // Initialising dp for subarray of length 2 for (var i = 0; i < N - 1; i++) { var R = i + 1; var L = i; dp[L][R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } // Calculating the complete dp array for (var R = 0; R < N; R++) { for (var L = 0; L < N; L++) { // If length of subarray is less 3, then // continuing if (R - L + 1 < 3) continue; dp[L][R] = dp[L + 1][R - 1] + (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R]); } } // Updating the maxPosSum variable for (var L = 0; L < N; L++) { for (var R = L; R < N; R++) { maxPosSum = Math.max(maxPosSum, dp[L][R]); } } // Returning the maximum possible sum of product return maxPosSum;} // Driver Code// Given Inputvar A = [ 5, 1, 2, 3 ], B = [ 1, 4, 3, 2 ]; document.write(maxSum(A, B)); // This code is contributed by 29AjayKumar</script>", "e": 40804, "s": 39150, "text": null }, { "code": null, "e": 40810, "s": 40807, "text": "33" }, { "code": null, "e": 40857, "s": 40812, "text": "Time Complexity: O(N2)Auxiliary Space: O(N2)" }, { "code": null, "e": 40873, "s": 40859, "text": "lokeshpotta20" }, { "code": null, "e": 40881, "s": 40873, "text": "gfgking" }, { "code": null, "e": 40891, "s": 40881, "text": "samim2000" }, { "code": null, "e": 40908, "s": 40891, "text": "_saurabh_jaiswal" }, { "code": null, "e": 40914, "s": 40908, "text": "ukasp" }, { "code": null, "e": 40926, "s": 40914, "text": "29AjayKumar" }, { "code": null, "e": 40935, "s": 40926, "text": "subarray" }, { "code": null, "e": 40942, "s": 40935, "text": "Arrays" }, { "code": null, "e": 40962, "s": 40942, "text": "Dynamic Programming" }, { "code": null, "e": 40975, "s": 40962, "text": "Mathematical" }, { "code": null, "e": 40982, "s": 40975, "text": "Arrays" }, { "code": null, "e": 41002, "s": 40982, "text": "Dynamic Programming" }, { "code": null, "e": 41015, "s": 41002, "text": "Mathematical" }, { "code": null, "e": 41113, "s": 41015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41122, "s": 41113, "text": "Comments" }, { "code": null, "e": 41135, "s": 41122, "text": "Old Comments" }, { "code": null, "e": 41160, "s": 41135, "text": "Window Sliding Technique" }, { "code": null, "e": 41180, "s": 41160, "text": "Trapping Rain Water" }, { "code": null, "e": 41205, "s": 41180, "text": "Building Heap from Array" }, { "code": null, "e": 41254, "s": 41205, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 41292, "s": 41254, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 41321, "s": 41292, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 41351, "s": 41321, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 41382, "s": 41351, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 41416, "s": 41382, "text": "Longest Common Subsequence | DP-4" } ]
Clustering Music to Create your Playlists on Spotify Using Python and R. | by Cristóbal Veas | Towards Data Science
Spotify is one of the most famous Music Platforms to discover new music. The company uses a lot of different algorithms to recommend the user new music based on their music preferences and most of these recommendations are located in Playlists. These Playlists are created for different users based on a wide diversity of music genres and even Spotify is capable to recommend new music based in moods. Music has been in my daily routine during all my life, It’s a kind of drug that I need when I’m doing housework, working at the office, walking the dog, workouts and so on. I have a lot of music on Spotify that I always wanted to separate according to the similarities of the songs and save them into different playlists. Fortunately, with a little knowledge of Machine Learning Algorithms and Python, I could achieve that goal !!!. So to do that, first I will list the tools required and some definitions of the Spotify Audio Features that I will use for built the Clustering model. Pandas and Numpy for data analysis. Sklearn to build the Machine Learning model. Spotipy Python Library (click here for more info). Spotify Credentials to access Api Database and Playlists Modify (click here for more info). Spotify uses a series of different features to classify the tracks. I copy/paste the information from the Spotify Webpage. Acousticness: A confidence measure from 0.0 to 1.0 of whether the track is acoustic. 1.0 represents high confidence the track is acoustic. Danceability: Danceability describes how suitable a track is for dancing based on a combination of musical elements including tempo, rhythm stability, beat strength, and overall regularity. A value of 0.0 is least danceable and 1.0 is most danceable. Energy: Energy is a measure from 0.0 to 1.0 and represents a perceptual measure of intensity and activity. Typically, energetic tracks feel fast, loud, and noisy. For example, death metal has high energy, while a Bach prelude scores low on the scale. Perceptual features contributing to this attribute include dynamic range, perceived loudness, timbre, onset rate, and general entropy. Instrumentalness: Predicts whether a track contains no vocals. “Ooh” and “aah” sounds are treated as instrumental in this context. Rap or spoken word tracks are clearly “vocal”. The closer the instrumentalness value is to 1.0, the greater likelihood the track contains no vocal content. Values above 0.5 are intended to represent instrumental tracks, but confidence is higher as the value approaches 1.0. Liveness: Detects the presence of an audience in the recording. Higher liveness values represent an increased probability that the track was performed live. A value above 0.8 provides a strong likelihood that the track is live. Loudness: the overall loudness of a track in decibels (dB). Loudness values are averaged across the entire track and are useful for comparing the relative loudness of tracks. Loudness is the quality of a sound that is the primary psychological correlate of physical strength (amplitude). Values typically range between -60 and 0 db. Speechiness: Speechiness detects the presence of spoken words in a track. The more exclusively speech-like the recording (e.g. talk show, audiobook, poetry), the closer to 1.0 the attribute value. Values above 0.66 describe tracks that are probably made entirely of spoken words. Values between 0.33 and 0.66 describe tracks that may contain both music and speech, either in sections or layered, including such cases as rap music. Values below 0.33 most likely represent music and other non-speech-like tracks. Valence: A measure from 0.0 to 1.0 describing the musical positiveness conveyed by a track. Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), while tracks with low valence sound more negative (e.g. sad, depressed, angry). Tempo: The overall estimated tempo of a track in beats per minute (BPM). In musical terminology, the tempo is the speed or pace of a given piece and derives directly from the average beat duration. For information reduction purposes I decided to use the features of Loudness, Valence, Energy, and Danceability because they have more influence to differentiate between Energetic and Relaxed songs. My favorite band is Radiohead, so I decided to obtain their discography and all the music created by the musicians in their solo music careers. Using the Spotipy Library I created some functions to download all the songs of Radiohead, Thom Yorke, Atoms For Peace, Jonny Greenwood, Ed O’Brien, Colin Greenwood, and Phil Selway (Yes, I’m obsessed with their music hehe). You can access those functions on my Github Repository (click here). I obtained the following data: I always wondered why I like a lot the music of Radiohead and I realized that most of their songs tend towards melancholy. Describing the features above, the data showed me that Valence and Energy are less than 0.5 and Danceability tends to low values, so I like tracks with low energy and negative sound (there is still something of my 2000’s Emo Side watching MTV Videos). I decided to use K-means Clustering for Unsupervised Machine Learning due to the shape of my data (423 tracks ) and considering I want to create 2 playlists separating Relaxed tracks from Energetic tracks (K=2). Important: I’m not using train and test data because in this case I just want to group all the tracks into 2 different groups to create playlists with the entire data. So let’s do it!. I first import the libraries: from sklearn.cluster import KMeansfrom sklearn.preprocessing import MinMaxScaler Then I need to define features and normalize the values of the model. I’ will use MinMaxScaler to preserve the shape of the original distribution and scale the features between a range from 0 to 1. Once I have the values in the correct format, I just simply create the K-Means model and then save the labels into the main Data Frame called “df”. col_features = ['danceability', 'energy', 'valence', 'loudness']X = MinMaxScaler().fit_transform(df[col_features])kmeans = KMeans(init="kmeans++", n_clusters=2, random_state=15).fit(X)df['kmeans'] = kmeans.labels_ That’s All, I have the music clustered in 2 groups !!! But now I need to study the features of these labels, so I plot the tracks in a 3D Scatter and then I analyze the respective mean of each feature grouping the data frame by the K-Means result labels. As I noticed on the graph the values are quite well grouped, blue values are located in label 0 and red values in label 1. Looking at the table of means, the label 0 grouped tracks with less danceability, energy, valence, loudness, so this one corresponds to Relaxed songs, likewise, the label 1 has the Energetic songs. I know that Clustering accuracy is a bit subjective trying to evaluate the best result of a Clustering Algorithm, but in the same way, I wanted to observe if my model is separating the tracks well. So with a little help from Rstudio, I used the Silhouette Analysis. to measure the accuracy of my model. In Rstudio I used the library “cluster” and “factoextra” to visualize and calculate the Silhouette Analysis using the Euclidean distance. the complete code is on my Github Repository (click here): #Calculate The euclidean distance of my dataframe values.dd <- dist(df,method="euclidean")#Silhouette Analysis using the K-means model(km) and distance(dd)sil.km <- silhouette(km$cluster,dd)fviz_silhouette(sil.km) The result is: The Silhouette Analysis is a way to measure how close each point in a cluster is to the points in its neighboring clusters. Silhouette values lies in the range of [-1, 1]. A value of +1 indicates that the sample is far away from its neighboring cluster and very close to the cluster its assigned. Similarly, a value of -1 indicates that the point is close to its neighboring cluster than to the cluster its assigned. So in my case values are between 0.25 and 0.60 inferring that most of the values are quite well grouped. To create the playlists and add the clustered tracks I use the library Spotipy explained in the first part of this article. You just need to get a client id, client secret, and username code to use the Spotify’s Apis and manipulate your library music. I let you the link with the information (Click Here). I had to separate the tracks grouped into 2 different variables and then having the ids of the tracks I just create 2 new playlists and pass them the ids of the tracks. The code is the following one: #Separating the clusters into new variablescluster_0 = df[df['kmeans']==0]cluster_1 = df[df['kmeans']==1]#Obtaining the ids of the songs and conver the id dataframe column to a list.ids_0 = cluster_0['id'].tolist()ids_1 = cluster_1['id'].tolist()#Creating 2 new playlists on my Spotify Userpl_energy = sp.user_playlist_create(username=username, name="Radiohead :)")pl_relaxed = sp.user_playlist_create(user=username, name="Radiohead :(")#Adding the tracks into the playlists#For energetic Playlistsp.user_playlist_add_tracks(user=username, playlist_id = pl_energy['id'], tracks=ids_1)#For relaxed Playlistsp.user_playlist_add_tracks(user=username, playlist_id = pl_relaxed['id'], tracks=ids_0) Finally, I have my 2 playlists of Radiohead’s songs using a K-means Clustering Algorithm to separate Energetic Songs from Relaxed Songs !!!!. If you want to listen to both playlists you can access them below. Machine Learning Algorithms are a lot of fun to implement ideas or projects related to things you like. In my case, I like music a lot, so I could use this knowledge to create cool ways helping me to automate a task that can take a long time to perform it. I also could learn more about this amazing world of Data Science and my tendencies to music tastes. Una Forma Genial para Buscar y Analizar Arriendos de Departamentos en la Web Predicting the Music Mood of a Song with Deep Learning Una Forma Interactiva para Buscar y Analizar Ofertas de Trabajo en la Web. Automating Playlists on Spotify From the Music Folders of your Computer
[ { "code": null, "e": 574, "s": 172, "text": "Spotify is one of the most famous Music Platforms to discover new music. The company uses a lot of different algorithms to recommend the user new music based on their music preferences and most of these recommendations are located in Playlists. These Playlists are created for different users based on a wide diversity of music genres and even Spotify is capable to recommend new music based in moods." }, { "code": null, "e": 1007, "s": 574, "text": "Music has been in my daily routine during all my life, It’s a kind of drug that I need when I’m doing housework, working at the office, walking the dog, workouts and so on. I have a lot of music on Spotify that I always wanted to separate according to the similarities of the songs and save them into different playlists. Fortunately, with a little knowledge of Machine Learning Algorithms and Python, I could achieve that goal !!!." }, { "code": null, "e": 1158, "s": 1007, "text": "So to do that, first I will list the tools required and some definitions of the Spotify Audio Features that I will use for built the Clustering model." }, { "code": null, "e": 1194, "s": 1158, "text": "Pandas and Numpy for data analysis." }, { "code": null, "e": 1239, "s": 1194, "text": "Sklearn to build the Machine Learning model." }, { "code": null, "e": 1290, "s": 1239, "text": "Spotipy Python Library (click here for more info)." }, { "code": null, "e": 1382, "s": 1290, "text": "Spotify Credentials to access Api Database and Playlists Modify (click here for more info)." }, { "code": null, "e": 1505, "s": 1382, "text": "Spotify uses a series of different features to classify the tracks. I copy/paste the information from the Spotify Webpage." }, { "code": null, "e": 1644, "s": 1505, "text": "Acousticness: A confidence measure from 0.0 to 1.0 of whether the track is acoustic. 1.0 represents high confidence the track is acoustic." }, { "code": null, "e": 1895, "s": 1644, "text": "Danceability: Danceability describes how suitable a track is for dancing based on a combination of musical elements including tempo, rhythm stability, beat strength, and overall regularity. A value of 0.0 is least danceable and 1.0 is most danceable." }, { "code": null, "e": 2281, "s": 1895, "text": "Energy: Energy is a measure from 0.0 to 1.0 and represents a perceptual measure of intensity and activity. Typically, energetic tracks feel fast, loud, and noisy. For example, death metal has high energy, while a Bach prelude scores low on the scale. Perceptual features contributing to this attribute include dynamic range, perceived loudness, timbre, onset rate, and general entropy." }, { "code": null, "e": 2686, "s": 2281, "text": "Instrumentalness: Predicts whether a track contains no vocals. “Ooh” and “aah” sounds are treated as instrumental in this context. Rap or spoken word tracks are clearly “vocal”. The closer the instrumentalness value is to 1.0, the greater likelihood the track contains no vocal content. Values above 0.5 are intended to represent instrumental tracks, but confidence is higher as the value approaches 1.0." }, { "code": null, "e": 2914, "s": 2686, "text": "Liveness: Detects the presence of an audience in the recording. Higher liveness values represent an increased probability that the track was performed live. A value above 0.8 provides a strong likelihood that the track is live." }, { "code": null, "e": 3247, "s": 2914, "text": "Loudness: the overall loudness of a track in decibels (dB). Loudness values are averaged across the entire track and are useful for comparing the relative loudness of tracks. Loudness is the quality of a sound that is the primary psychological correlate of physical strength (amplitude). Values typically range between -60 and 0 db." }, { "code": null, "e": 3758, "s": 3247, "text": "Speechiness: Speechiness detects the presence of spoken words in a track. The more exclusively speech-like the recording (e.g. talk show, audiobook, poetry), the closer to 1.0 the attribute value. Values above 0.66 describe tracks that are probably made entirely of spoken words. Values between 0.33 and 0.66 describe tracks that may contain both music and speech, either in sections or layered, including such cases as rap music. Values below 0.33 most likely represent music and other non-speech-like tracks." }, { "code": null, "e": 4009, "s": 3758, "text": "Valence: A measure from 0.0 to 1.0 describing the musical positiveness conveyed by a track. Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), while tracks with low valence sound more negative (e.g. sad, depressed, angry)." }, { "code": null, "e": 4207, "s": 4009, "text": "Tempo: The overall estimated tempo of a track in beats per minute (BPM). In musical terminology, the tempo is the speed or pace of a given piece and derives directly from the average beat duration." }, { "code": null, "e": 4406, "s": 4207, "text": "For information reduction purposes I decided to use the features of Loudness, Valence, Energy, and Danceability because they have more influence to differentiate between Energetic and Relaxed songs." }, { "code": null, "e": 4550, "s": 4406, "text": "My favorite band is Radiohead, so I decided to obtain their discography and all the music created by the musicians in their solo music careers." }, { "code": null, "e": 4844, "s": 4550, "text": "Using the Spotipy Library I created some functions to download all the songs of Radiohead, Thom Yorke, Atoms For Peace, Jonny Greenwood, Ed O’Brien, Colin Greenwood, and Phil Selway (Yes, I’m obsessed with their music hehe). You can access those functions on my Github Repository (click here)." }, { "code": null, "e": 4875, "s": 4844, "text": "I obtained the following data:" }, { "code": null, "e": 5250, "s": 4875, "text": "I always wondered why I like a lot the music of Radiohead and I realized that most of their songs tend towards melancholy. Describing the features above, the data showed me that Valence and Energy are less than 0.5 and Danceability tends to low values, so I like tracks with low energy and negative sound (there is still something of my 2000’s Emo Side watching MTV Videos)." }, { "code": null, "e": 5462, "s": 5250, "text": "I decided to use K-means Clustering for Unsupervised Machine Learning due to the shape of my data (423 tracks ) and considering I want to create 2 playlists separating Relaxed tracks from Energetic tracks (K=2)." }, { "code": null, "e": 5630, "s": 5462, "text": "Important: I’m not using train and test data because in this case I just want to group all the tracks into 2 different groups to create playlists with the entire data." }, { "code": null, "e": 5677, "s": 5630, "text": "So let’s do it!. I first import the libraries:" }, { "code": null, "e": 5758, "s": 5677, "text": "from sklearn.cluster import KMeansfrom sklearn.preprocessing import MinMaxScaler" }, { "code": null, "e": 6104, "s": 5758, "text": "Then I need to define features and normalize the values of the model. I’ will use MinMaxScaler to preserve the shape of the original distribution and scale the features between a range from 0 to 1. Once I have the values in the correct format, I just simply create the K-Means model and then save the labels into the main Data Frame called “df”." }, { "code": null, "e": 6348, "s": 6104, "text": "col_features = ['danceability', 'energy', 'valence', 'loudness']X = MinMaxScaler().fit_transform(df[col_features])kmeans = KMeans(init=\"kmeans++\", n_clusters=2, random_state=15).fit(X)df['kmeans'] = kmeans.labels_" }, { "code": null, "e": 6403, "s": 6348, "text": "That’s All, I have the music clustered in 2 groups !!!" }, { "code": null, "e": 6603, "s": 6403, "text": "But now I need to study the features of these labels, so I plot the tracks in a 3D Scatter and then I analyze the respective mean of each feature grouping the data frame by the K-Means result labels." }, { "code": null, "e": 6924, "s": 6603, "text": "As I noticed on the graph the values are quite well grouped, blue values are located in label 0 and red values in label 1. Looking at the table of means, the label 0 grouped tracks with less danceability, energy, valence, loudness, so this one corresponds to Relaxed songs, likewise, the label 1 has the Energetic songs." }, { "code": null, "e": 7227, "s": 6924, "text": "I know that Clustering accuracy is a bit subjective trying to evaluate the best result of a Clustering Algorithm, but in the same way, I wanted to observe if my model is separating the tracks well. So with a little help from Rstudio, I used the Silhouette Analysis. to measure the accuracy of my model." }, { "code": null, "e": 7424, "s": 7227, "text": "In Rstudio I used the library “cluster” and “factoextra” to visualize and calculate the Silhouette Analysis using the Euclidean distance. the complete code is on my Github Repository (click here):" }, { "code": null, "e": 7638, "s": 7424, "text": "#Calculate The euclidean distance of my dataframe values.dd <- dist(df,method=\"euclidean\")#Silhouette Analysis using the K-means model(km) and distance(dd)sil.km <- silhouette(km$cluster,dd)fviz_silhouette(sil.km)" }, { "code": null, "e": 7653, "s": 7638, "text": "The result is:" }, { "code": null, "e": 8175, "s": 7653, "text": "The Silhouette Analysis is a way to measure how close each point in a cluster is to the points in its neighboring clusters. Silhouette values lies in the range of [-1, 1]. A value of +1 indicates that the sample is far away from its neighboring cluster and very close to the cluster its assigned. Similarly, a value of -1 indicates that the point is close to its neighboring cluster than to the cluster its assigned. So in my case values are between 0.25 and 0.60 inferring that most of the values are quite well grouped." }, { "code": null, "e": 8481, "s": 8175, "text": "To create the playlists and add the clustered tracks I use the library Spotipy explained in the first part of this article. You just need to get a client id, client secret, and username code to use the Spotify’s Apis and manipulate your library music. I let you the link with the information (Click Here)." }, { "code": null, "e": 8681, "s": 8481, "text": "I had to separate the tracks grouped into 2 different variables and then having the ids of the tracks I just create 2 new playlists and pass them the ids of the tracks. The code is the following one:" }, { "code": null, "e": 9569, "s": 8681, "text": "#Separating the clusters into new variablescluster_0 = df[df['kmeans']==0]cluster_1 = df[df['kmeans']==1]#Obtaining the ids of the songs and conver the id dataframe column to a list.ids_0 = cluster_0['id'].tolist()ids_1 = cluster_1['id'].tolist()#Creating 2 new playlists on my Spotify Userpl_energy = sp.user_playlist_create(username=username, name=\"Radiohead :)\")pl_relaxed = sp.user_playlist_create(user=username, name=\"Radiohead :(\")#Adding the tracks into the playlists#For energetic Playlistsp.user_playlist_add_tracks(user=username, playlist_id = pl_energy['id'], tracks=ids_1)#For relaxed Playlistsp.user_playlist_add_tracks(user=username, playlist_id = pl_relaxed['id'], tracks=ids_0)" }, { "code": null, "e": 9711, "s": 9569, "text": "Finally, I have my 2 playlists of Radiohead’s songs using a K-means Clustering Algorithm to separate Energetic Songs from Relaxed Songs !!!!." }, { "code": null, "e": 9778, "s": 9711, "text": "If you want to listen to both playlists you can access them below." }, { "code": null, "e": 10135, "s": 9778, "text": "Machine Learning Algorithms are a lot of fun to implement ideas or projects related to things you like. In my case, I like music a lot, so I could use this knowledge to create cool ways helping me to automate a task that can take a long time to perform it. I also could learn more about this amazing world of Data Science and my tendencies to music tastes." }, { "code": null, "e": 10212, "s": 10135, "text": "Una Forma Genial para Buscar y Analizar Arriendos de Departamentos en la Web" }, { "code": null, "e": 10267, "s": 10212, "text": "Predicting the Music Mood of a Song with Deep Learning" }, { "code": null, "e": 10342, "s": 10267, "text": "Una Forma Interactiva para Buscar y Analizar Ofertas de Trabajo en la Web." } ]
Word Dictionary using Python Tkinter
In this article, we will create a GUI-based dictionary using PyDictionary and Tkinter Module. PyDictionary is a Python Module that helps to get meaning translations, antonyms and synonyms of words. It uses WordNet for getting meanings, Google for translations, and synonym.com for getting synonyms and antonyms. PyDictionary uses BeautifulSoup, Requests module as the dependencies. In order to create the application, we will first install these modules in our environment using pip install PyDictionary After installing, we will create a tkinter frame and some other element. # Import Required Librares from tkinter import * from PyDictionary import PyDictionary # Create instances and objests dictionary = PyDictionary() win =Tk() #Define the size of the window win.geometry("700x400") win.title("Python Dictionary") #Define Helper Function to use the other atributes of PyDictionary Class def dict(): meaning.config(text=dictionary.meaning(word.get())['Noun'][0]) #Define Labels and Buttons Label(win, text="Dictionary", font=("Times New Roman" ,20)).pack(pady=20) # Frame 1 frame = Frame(win) Label(frame, text="Type any Word ", font=("Poppins bold", 15)).pack(side=LEFT) word = Entry(frame, font=("Times New Roman", 15)) word.pack() frame.pack(pady=10) # Frame 2 frame1 = Frame(win) Label(frame1, text="Meaning:", font=("Aerial", 18)).pack(side=LEFT) meaning = Label(frame1, text="", font=("Poppins",15), width= 30) meaning.pack() frame1.pack(pady=10) Button(win, text="Find", font=("Poppins bold",15), command=dict).pack() # Execute Tkinter win.mainloop() Running the above code will create and display the Dictionary Application. However, using PyDictionary, we can add other attributes like finding synonym, antonyms, etc. Now, type “Hello” in the textbox and click the “Find” button. It will pull the meaning of “Hello” from the dictionary.
[ { "code": null, "e": 1156, "s": 1062, "text": "In this article, we will create a GUI-based dictionary using PyDictionary and Tkinter\nModule." }, { "code": null, "e": 1444, "s": 1156, "text": "PyDictionary is a Python Module that helps to get meaning translations, antonyms and synonyms of words. It uses WordNet for getting meanings, Google for translations, and synonym.com for getting synonyms and antonyms. PyDictionary uses BeautifulSoup, Requests module as the dependencies." }, { "code": null, "e": 1566, "s": 1444, "text": "In order to create the application, we will first install these modules in our environment using pip install PyDictionary" }, { "code": null, "e": 1639, "s": 1566, "text": "After installing, we will create a tkinter frame and some other element." }, { "code": null, "e": 2635, "s": 1639, "text": "# Import Required Librares\nfrom tkinter import *\nfrom PyDictionary import PyDictionary\n\n# Create instances and objests\ndictionary = PyDictionary()\nwin =Tk()\n\n#Define the size of the window\nwin.geometry(\"700x400\")\n\nwin.title(\"Python Dictionary\")\n\n#Define Helper Function to use the other atributes of PyDictionary Class\ndef dict():\n meaning.config(text=dictionary.meaning(word.get())['Noun'][0])\n\n#Define Labels and Buttons\nLabel(win, text=\"Dictionary\", font=(\"Times New Roman\" ,20)).pack(pady=20)\n\n# Frame 1\nframe = Frame(win)\nLabel(frame, text=\"Type any Word \", font=(\"Poppins bold\", 15)).pack(side=LEFT)\nword = Entry(frame, font=(\"Times New Roman\", 15))\nword.pack()\nframe.pack(pady=10)\n# Frame 2\nframe1 = Frame(win)\nLabel(frame1, text=\"Meaning:\", font=(\"Aerial\", 18)).pack(side=LEFT)\nmeaning = Label(frame1, text=\"\", font=(\"Poppins\",15), width= 30)\nmeaning.pack()\nframe1.pack(pady=10)\n\nButton(win, text=\"Find\", font=(\"Poppins bold\",15), command=dict).pack()\n\n# Execute Tkinter\nwin.mainloop()" }, { "code": null, "e": 2804, "s": 2635, "text": "Running the above code will create and display the Dictionary Application. However,\nusing PyDictionary, we can add other attributes like finding synonym, antonyms, etc." }, { "code": null, "e": 2923, "s": 2804, "text": "Now, type “Hello” in the textbox and click the “Find” button. It will pull the meaning of “Hello” from the dictionary." } ]
How to add a title to JTable in Java Swing?
To display a title to the JTable, you can set a title for the JPanel, which already consists of a JTable. Here, we are using createTitledBorder() for the JPanel to set the title for the panel border that would eventually work for table title. Let’s say the following is the JPanel − JPanel panel = new JPanel(); Now, use setBorder() and the BorderFactory class to set a title border for the panel that would be our table title as well − panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "My Demo Table", TitledBorder.LEFT, TitledBorder.TOP)); The following is an example to add a title to a JTable − package my; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.border.TitledBorder; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "My Demo Table", TitledBorder.LEFT, TitledBorder.TOP)); String[][] rec = { { "001", "David", "AUS" }, { "002", "Steve", "AUS" }, { "003", "Yuvraj", "IND" }, { "004", "Kane", "NZ" }, { "005", "Ben", "ENG" }, { "006", "Eion", "ENG" }, { "007", "Miller", "SA" }, { "008", "Rohit", "IND" } }; String[] header = { "Id", "Player", "Team" }; JTable table = new JTable(rec, header); panel.add(new JScrollPane(table)); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } }
[ { "code": null, "e": 1168, "s": 1062, "text": "To display a title to the JTable, you can set a title for the JPanel, which already consists of a JTable." }, { "code": null, "e": 1305, "s": 1168, "text": "Here, we are using createTitledBorder() for the JPanel to set the title for the panel border that would eventually work for table title." }, { "code": null, "e": 1345, "s": 1305, "text": "Let’s say the following is the JPanel −" }, { "code": null, "e": 1374, "s": 1345, "text": "JPanel panel = new JPanel();" }, { "code": null, "e": 1499, "s": 1374, "text": "Now, use setBorder() and the BorderFactory class to set a title border for the panel that would be our table title as well −" }, { "code": null, "e": 1644, "s": 1499, "text": "panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createEtchedBorder(), \"My Demo Table\", TitledBorder.LEFT,\nTitledBorder.TOP));" }, { "code": null, "e": 1701, "s": 1644, "text": "The following is an example to add a title to a JTable −" }, { "code": null, "e": 2747, "s": 1701, "text": "package my;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n JPanel panel = new JPanel();\n panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createEtchedBorder(), \"My Demo Table\", TitledBorder.LEFT,\n TitledBorder.TOP));\n String[][] rec = {\n { \"001\", \"David\", \"AUS\" },\n { \"002\", \"Steve\", \"AUS\" },\n { \"003\", \"Yuvraj\", \"IND\" },\n { \"004\", \"Kane\", \"NZ\" },\n { \"005\", \"Ben\", \"ENG\" },\n { \"006\", \"Eion\", \"ENG\" },\n { \"007\", \"Miller\", \"SA\" },\n { \"008\", \"Rohit\", \"IND\" }\n };\n String[] header = { \"Id\", \"Player\", \"Team\" };\n JTable table = new JTable(rec, header);\n panel.add(new JScrollPane(table));\n frame.add(panel);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}" } ]
Java String contains() Method
❮ String Methods Find out if a string contains a sequence of characters: String myStr = "Hello"; System.out.println(myStr.contains("Hel")); // true System.out.println(myStr.contains("e")); // true System.out.println(myStr.contains("Hi")); // false Try it Yourself » The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not. public boolean contains(CharSequence chars) The CharSequence interface is a readable sequence of char values, found in the java.lang package. true - sequence of characters exists false - sequence of characters do not exist We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 19, "s": 0, "text": "\n❮ String Methods\n" }, { "code": null, "e": 75, "s": 19, "text": "Find out if a string contains a sequence of characters:" }, { "code": null, "e": 259, "s": 75, "text": "String myStr = \"Hello\";\nSystem.out.println(myStr.contains(\"Hel\")); // true\nSystem.out.println(myStr.contains(\"e\")); // true\nSystem.out.println(myStr.contains(\"Hi\")); // false" }, { "code": null, "e": 279, "s": 259, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 360, "s": 279, "text": "The contains() method checks whether a string contains a sequence of characters." }, { "code": null, "e": 415, "s": 360, "text": "Returns true if the characters exist and false if not." }, { "code": null, "e": 460, "s": 415, "text": "public boolean contains(CharSequence chars)\n" }, { "code": null, "e": 558, "s": 460, "text": "The CharSequence interface is a readable sequence of char values, found in the java.lang package." }, { "code": null, "e": 595, "s": 558, "text": "true - sequence of characters exists" }, { "code": null, "e": 639, "s": 595, "text": "false - sequence of characters do not exist" }, { "code": null, "e": 672, "s": 639, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 714, "s": 672, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 821, "s": 714, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 840, "s": 821, "text": "help@w3schools.com" } ]
HTML width/height Attribute vs CSS width/height Property - GeeksforGeeks
26 Jul, 2021 In HTML 5, few elements follow the width and height attributes and maximum elements do not follow this attribute. Like img, iframe, canvas, and svg kind of elements follow the width and height attributes but div, span, article and section type of elements don’t follow them.The width and height attributes are affected in img, svg tags, those are weak kind of styling, it can be overridden by CSS. If you have assigned an img tag with the width=”500′′ and height=”200′′ and load a CSS width and height property for img tag like width: 400px; then that 500 will be dully 400 will effect the image. <!-- Normally in HTML --> <img src=" " width="600" height="200"> /* In CSS for override*/ img { width: 400px; height: 400px; } There are few more attributes that are not selected for a few elements those are very strongly affected on the output. To apply CSS properties on those element you have to know how to apply !important in CSS?. Differences between HTML width/height attribute and CSS width/height property: Below example uses height/width attributes and height/width property.Example: html <!DOCTYPE html><html> <head> <title> Comparison between height/width attributes and height/width property </title> <style> h1 { color: green; } .container { width: 95%; border: 2px solid black; padding: 5px; height: 400px; } .first { text-align: center; width: 45%; float: left; } .second { text-align: center; width: 45%; float: right; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> HTML height/width Attribute Vs CSS height/width property </h2> <div class="container"> <div class="first"> <h3>HTML width/height Attributes</h3> <img src="" width="150px" height="150px" style="border:2px solid #000000;"> <iframe src="" width="150px" height="150px" style="border:2px solid #000000;"> </iframe> <canvas src="" width="150px" height="150px" style="border:2px solid #000000;"> </canvas> <svg src="" width="150px" height="150px" style="border:2px solid #000000;"> </svg> </div> <div class="second"> <h3>CSS width/height Property</h3> <div width="150px" height="150px" style="border:2px solid #000000;"> This is div tag </div> <br><br> <span width="150px" height="150px" style="border:2px solid #000000;"> This is span tag </span> <br><br> <article width="150px" height="150px" style="border:2px solid #000000;"> This is article tag </article> <br><br> <section width="150px" height="150px" style="border:2px solid #000000;"> This is section tag </section> </div> </div> </center></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. kalrap615 CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction) Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 24606, "s": 24578, "text": "\n26 Jul, 2021" }, { "code": null, "e": 25205, "s": 24606, "text": "In HTML 5, few elements follow the width and height attributes and maximum elements do not follow this attribute. Like img, iframe, canvas, and svg kind of elements follow the width and height attributes but div, span, article and section type of elements don’t follow them.The width and height attributes are affected in img, svg tags, those are weak kind of styling, it can be overridden by CSS. If you have assigned an img tag with the width=”500′′ and height=”200′′ and load a CSS width and height property for img tag like width: 400px; then that 500 will be dully 400 will effect the image. " }, { "code": null, "e": 25342, "s": 25205, "text": "<!-- Normally in HTML -->\n<img src=\" \" width=\"600\" height=\"200\">\n\n/* In CSS for override*/\nimg {\n width: 400px;\n height: 400px;\n}" }, { "code": null, "e": 25632, "s": 25342, "text": "There are few more attributes that are not selected for a few elements those are very strongly affected on the output. To apply CSS properties on those element you have to know how to apply !important in CSS?. Differences between HTML width/height attribute and CSS width/height property: " }, { "code": null, "e": 25711, "s": 25632, "text": "Below example uses height/width attributes and height/width property.Example: " }, { "code": null, "e": 25716, "s": 25711, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Comparison between height/width attributes and height/width property </title> <style> h1 { color: green; } .container { width: 95%; border: 2px solid black; padding: 5px; height: 400px; } .first { text-align: center; width: 45%; float: left; } .second { text-align: center; width: 45%; float: right; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> HTML height/width Attribute Vs CSS height/width property </h2> <div class=\"container\"> <div class=\"first\"> <h3>HTML width/height Attributes</h3> <img src=\"\" width=\"150px\" height=\"150px\" style=\"border:2px solid #000000;\"> <iframe src=\"\" width=\"150px\" height=\"150px\" style=\"border:2px solid #000000;\"> </iframe> <canvas src=\"\" width=\"150px\" height=\"150px\" style=\"border:2px solid #000000;\"> </canvas> <svg src=\"\" width=\"150px\" height=\"150px\" style=\"border:2px solid #000000;\"> </svg> </div> <div class=\"second\"> <h3>CSS width/height Property</h3> <div width=\"150px\" height=\"150px\" style=\"border:2px solid #000000;\"> This is div tag </div> <br><br> <span width=\"150px\" height=\"150px\" style=\"border:2px solid #000000;\"> This is span tag </span> <br><br> <article width=\"150px\" height=\"150px\" style=\"border:2px solid #000000;\"> This is article tag </article> <br><br> <section width=\"150px\" height=\"150px\" style=\"border:2px solid #000000;\"> This is section tag </section> </div> </div> </center></body> </html>", "e": 28205, "s": 25716, "text": null }, { "code": null, "e": 28214, "s": 28205, "text": "Output: " }, { "code": null, "e": 28351, "s": 28214, "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": 28361, "s": 28351, "text": "kalrap615" }, { "code": null, "e": 28370, "s": 28361, "text": "CSS-Misc" }, { "code": null, "e": 28380, "s": 28370, "text": "HTML-Misc" }, { "code": null, "e": 28384, "s": 28380, "text": "CSS" }, { "code": null, "e": 28389, "s": 28384, "text": "HTML" }, { "code": null, "e": 28406, "s": 28389, "text": "Web Technologies" }, { "code": null, "e": 28433, "s": 28406, "text": "Web technologies Questions" }, { "code": null, "e": 28438, "s": 28433, "text": "HTML" }, { "code": null, "e": 28536, "s": 28438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28594, "s": 28536, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28631, "s": 28594, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28695, "s": 28631, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28732, "s": 28695, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28773, "s": 28732, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28833, "s": 28773, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28886, "s": 28833, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28936, "s": 28886, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28960, "s": 28936, "text": "REST API (Introduction)" } ]
Rexx - ask Command
This command is used to read a line from the default input stream. variable = ask Variable − The variable to store the value entered by the user. Variable − The variable to store the value entered by the user. None /* Main program */ input = ask say input When we run the above program we will get the following result. If we input the value hello, we will get the output of hello. ASK Print Add Notes Bookmark this page
[ { "code": null, "e": 2406, "s": 2339, "text": "This command is used to read a line from the default input stream." }, { "code": null, "e": 2423, "s": 2406, "text": "variable = ask \n" }, { "code": null, "e": 2487, "s": 2423, "text": "Variable − The variable to store the value entered by the user." }, { "code": null, "e": 2551, "s": 2487, "text": "Variable − The variable to store the value entered by the user." }, { "code": null, "e": 2556, "s": 2551, "text": "None" }, { "code": null, "e": 2599, "s": 2556, "text": "/* Main program */ \ninput = ask \nsay input" }, { "code": null, "e": 2725, "s": 2599, "text": "When we run the above program we will get the following result. If we input the value hello, we will get the output of hello." }, { "code": null, "e": 2730, "s": 2725, "text": "ASK\n" }, { "code": null, "e": 2737, "s": 2730, "text": " Print" }, { "code": null, "e": 2748, "s": 2737, "text": " Add Notes" } ]
Count Number of Words in String using R - GeeksforGeeks
23 May, 2021 In this article, we are going to see how to count the number of words in character String in R Programming Language. Method 1: Using strplit and sapply methods The strsplit() method in R is used to return a vector of words contained in the specified string based on matching with regex defined. Each element of this vector is a substring of the original string. The length of the returned vector is therefore equivalent to the number of words. Syntax: strsplit( str , regex ) Arguments : str – The string to count the occurrences of regex – The character vector (or object which can be coerced ) containing regular expression, for the pattern to be matched. In the case of finding the number of words the pattern is simply equivalent to ” “. sapply() method: It is used to compute the length of the vector containing words. The sapply() method is used to apply functions over vectors or lists, and return outputs based on these computations. In case the second argument, that is, the function is length, then the length of the split vector is returned. sapply (str , FUN) The combined approach to determine the composite words is defined by the following syntax in R : sapply(strsplit(str, " "), length) Code: R # declaring stringstr <- "Counting the words in this R sentence?\Try this approach in GFG! " print ("Original string")print (str)print ("Total number of words") # splitting a string by spacessplit <- strsplit(str, " ")sapply( split , length) Output [1] "Original string" [1] "Counting the words in this R sentence? Try this approach in GFG! " [1] "Total number of words" [1] 12 Method 2: Using gregexpr method. This method uses a variety of methods available in base R to compute the number of occurrences of a specific character in R. The gregexpr() method is used to return a list of sublists that match a specific pattern of the argument list of the function. The pattern matching used is case-sensitive in this case. The pattern in our case is \\W+. Syntax: gregexpr(pattern, text) The lengths method is then applied in order to return the individual lengths of all the elements of the argument vector. Syntax: lengths(x) This method uses the regular expression symbol \\W to match non-word characters, using + to indicate one or more in a row. It returns the number of separators between the words, so the number of words is actually, separators + 1, in most cases. Code: R # declaring stringstr <- "Counting the words in this R sentence? \Try this approach in GFG! " print ("Original string")print (str)print ("Total number of words") # splitting a string by spaceslengths(gregexpr("\\W+", str)) + 1 Output [1] "Original string" [1] "Counting the words in this R sentence? Try this approach in GFG! " [1] "Total number of words" [1] 13 Method 3: Using stringr package The stringR package in R is used to perform string manipulations. It needs to be explicitly installed in the working space to access its methods and routines. install.packages("stringr") The stringr package provides a str_count() method which is used to count the number of occurrences of a certain pattern specified as an argument to the function. The pattern may be a single character or a group of characters. Any instances matching the expression result in the increment of the count. This method can also be invoked over a vector of strings, and an individual count vector is returned containing individual counts of the number of pattern matches found. However, this method is only considered approximate of regex matching. In case, no matches are found 0 is returned. Syntax: str_count(str, pattern = “”) Arguments : str – The string to count the occurrences of pattern – the pattern to match to Code: R library("stringr") # declaring stringstr <- "Counting the words in this R sentence? Try this approach in GFG! "print ("Original string")print (str)print ("Total number of words") # splitting a string by spacesstr_count(str ,"\\W+") Output: [1] "Original string" [1] "Counting the words in this R sentence? Try this approach in GFG! " [1] "Total number of words" [1] 12 Picked R String-Programs R-strings R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n23 May, 2021" }, { "code": null, "e": 25360, "s": 25242, "text": "In this article, we are going to see how to count the number of words in character String in R Programming Language. " }, { "code": null, "e": 25403, "s": 25360, "text": "Method 1: Using strplit and sapply methods" }, { "code": null, "e": 25688, "s": 25403, "text": "The strsplit() method in R is used to return a vector of words contained in the specified string based on matching with regex defined. Each element of this vector is a substring of the original string. The length of the returned vector is therefore equivalent to the number of words. " }, { "code": null, "e": 25720, "s": 25688, "text": "Syntax: strsplit( str , regex )" }, { "code": null, "e": 25732, "s": 25720, "text": "Arguments :" }, { "code": null, "e": 25777, "s": 25732, "text": "str – The string to count the occurrences of" }, { "code": null, "e": 25986, "s": 25777, "text": "regex – The character vector (or object which can be coerced ) containing regular expression, for the pattern to be matched. In the case of finding the number of words the pattern is simply equivalent to ” “." }, { "code": null, "e": 26298, "s": 25986, "text": "sapply() method: It is used to compute the length of the vector containing words. The sapply() method is used to apply functions over vectors or lists, and return outputs based on these computations. In case the second argument, that is, the function is length, then the length of the split vector is returned. " }, { "code": null, "e": 26317, "s": 26298, "text": "sapply (str , FUN)" }, { "code": null, "e": 26414, "s": 26317, "text": "The combined approach to determine the composite words is defined by the following syntax in R :" }, { "code": null, "e": 26449, "s": 26414, "text": "sapply(strsplit(str, \" \"), length)" }, { "code": null, "e": 26455, "s": 26449, "text": "Code:" }, { "code": null, "e": 26457, "s": 26455, "text": "R" }, { "code": "# declaring stringstr <- \"Counting the words in this R sentence?\\Try this approach in GFG! \" print (\"Original string\")print (str)print (\"Total number of words\") # splitting a string by spacessplit <- strsplit(str, \" \")sapply( split , length)", "e": 26701, "s": 26457, "text": null }, { "code": null, "e": 26708, "s": 26701, "text": "Output" }, { "code": null, "e": 26837, "s": 26708, "text": "[1] \"Original string\"\n[1] \"Counting the words in this R sentence? Try this approach in GFG! \"\n[1] \"Total number of words\"\n[1] 12" }, { "code": null, "e": 26870, "s": 26837, "text": "Method 2: Using gregexpr method." }, { "code": null, "e": 27214, "s": 26870, "text": "This method uses a variety of methods available in base R to compute the number of occurrences of a specific character in R. The gregexpr() method is used to return a list of sublists that match a specific pattern of the argument list of the function. The pattern matching used is case-sensitive in this case. The pattern in our case is \\\\W+. " }, { "code": null, "e": 27246, "s": 27214, "text": "Syntax: gregexpr(pattern, text)" }, { "code": null, "e": 27367, "s": 27246, "text": "The lengths method is then applied in order to return the individual lengths of all the elements of the argument vector." }, { "code": null, "e": 27386, "s": 27367, "text": "Syntax: lengths(x)" }, { "code": null, "e": 27631, "s": 27386, "text": "This method uses the regular expression symbol \\\\W to match non-word characters, using + to indicate one or more in a row. It returns the number of separators between the words, so the number of words is actually, separators + 1, in most cases." }, { "code": null, "e": 27637, "s": 27631, "text": "Code:" }, { "code": null, "e": 27639, "s": 27637, "text": "R" }, { "code": "# declaring stringstr <- \"Counting the words in this R sentence? \\Try this approach in GFG! \" print (\"Original string\")print (str)print (\"Total number of words\") # splitting a string by spaceslengths(gregexpr(\"\\\\W+\", str)) + 1 ", "e": 27870, "s": 27639, "text": null }, { "code": null, "e": 27877, "s": 27870, "text": "Output" }, { "code": null, "e": 28006, "s": 27877, "text": "[1] \"Original string\"\n[1] \"Counting the words in this R sentence? Try this approach in GFG! \"\n[1] \"Total number of words\"\n[1] 13" }, { "code": null, "e": 28039, "s": 28006, "text": "Method 3: Using stringr package " }, { "code": null, "e": 28198, "s": 28039, "text": "The stringR package in R is used to perform string manipulations. It needs to be explicitly installed in the working space to access its methods and routines." }, { "code": null, "e": 28226, "s": 28198, "text": "install.packages(\"stringr\")" }, { "code": null, "e": 28814, "s": 28226, "text": "The stringr package provides a str_count() method which is used to count the number of occurrences of a certain pattern specified as an argument to the function. The pattern may be a single character or a group of characters. Any instances matching the expression result in the increment of the count. This method can also be invoked over a vector of strings, and an individual count vector is returned containing individual counts of the number of pattern matches found. However, this method is only considered approximate of regex matching. In case, no matches are found 0 is returned." }, { "code": null, "e": 28851, "s": 28814, "text": "Syntax: str_count(str, pattern = “”)" }, { "code": null, "e": 28863, "s": 28851, "text": "Arguments :" }, { "code": null, "e": 28908, "s": 28863, "text": "str – The string to count the occurrences of" }, { "code": null, "e": 28942, "s": 28908, "text": "pattern – the pattern to match to" }, { "code": null, "e": 28948, "s": 28942, "text": "Code:" }, { "code": null, "e": 28950, "s": 28948, "text": "R" }, { "code": "library(\"stringr\") # declaring stringstr <- \"Counting the words in this R sentence? Try this approach in GFG! \"print (\"Original string\")print (str)print (\"Total number of words\") # splitting a string by spacesstr_count(str ,\"\\\\W+\") ", "e": 29185, "s": 28950, "text": null }, { "code": null, "e": 29193, "s": 29185, "text": "Output:" }, { "code": null, "e": 29322, "s": 29193, "text": "[1] \"Original string\"\n[1] \"Counting the words in this R sentence? Try this approach in GFG! \"\n[1] \"Total number of words\"\n[1] 12" }, { "code": null, "e": 29329, "s": 29322, "text": "Picked" }, { "code": null, "e": 29347, "s": 29329, "text": "R String-Programs" }, { "code": null, "e": 29357, "s": 29347, "text": "R-strings" }, { "code": null, "e": 29368, "s": 29357, "text": "R Language" }, { "code": null, "e": 29379, "s": 29368, "text": "R Programs" }, { "code": null, "e": 29477, "s": 29379, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29529, "s": 29477, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29567, "s": 29529, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29602, "s": 29567, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29660, "s": 29602, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29709, "s": 29660, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29767, "s": 29709, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29816, "s": 29767, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29866, "s": 29816, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29909, "s": 29866, "text": "Replace Specific Characters in String in R" } ]
Max rectangle | Practice | GeeksforGeeks
Given a binary matrix M of size n X m. Find the maximum area of a rectangle formed only of 1s in the given matrix. Example 1: Input: n = 4, m = 4 M[][] = {{0 1 1 0}, {1 1 1 1}, {1 1 1 1}, {1 1 0 0}} Output: 8 Explanation: For the above test case the matrix will look like 0 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0 the max size rectangle is 1 1 1 1 1 1 1 1 and area is 4 *2 = 8. Your Task: Your task is to complete the function maxArea which returns the maximum size rectangle area in a binary-sub-matrix with all 1’s. The function takes 3 arguments the first argument is the Matrix M[ ] [ ] and the next two are two integers n and m which denotes the size of the matrix M. Expected Time Complexity : O(n*m) Expected Auixiliary Space : O(m) Constraints: 1<=n,m<=1000 0<=M[][]<=1 Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. +1 anilcangulkaya73 days ago 0.89/2.62 #define xSafe(x, n) (x < n) #define ySafe(y, m) (y < m) int maxArea(int M[MAX][MAX], int n, int m) { // Your code here int maxCount = 0; for(int x = 0; x < n; ++x) for(int y = 0; y < m; ++y) for(int i = 0; M[x + i][y] && xSafe(i + x, n); ++i) { for(int j = 0; ySafe(j + y, m); ++j) { for(int k = 0; k <= i; ++k) if(!M[x+k][y+j]) { goto not_correct; } maxCount = max((i + 1) * (j + 1), maxCount); } not_correct:{} } return maxCount; } 0 bobbyprajapati962 weeks ago Simple Java Solution class Solution { static int[] prevSmaller(int arr[]){ Stack<Integer> st = new Stack<>(); int ans[] = new int[arr.length]; ans[0] = -1; for(int i=0;i<arr.length;i++) { while(!st.isEmpty() && arr[st.peek()]>=arr[i]) st.pop(); ans[i]=st.isEmpty()?-1:st.peek(); st.push(i); } return ans; } static int[] nextSmaller(int arr[]){ Stack<Integer> st = new Stack<>(); int ans[] = new int[arr.length]; ans[arr.length-1] = arr.length; st.push(arr.length-1); for(int i=arr.length-1;i>=0;i--){ while(!st.isEmpty() && arr[st.peek()]>=arr[i]) st.pop(); ans[i] = st.isEmpty()?arr.length:st.peek(); st.push(i); } return ans; } //Function to find largest rectangular area possible in a given histogram. public static int getMaxArea(int hist[], int n) { // your code here int prev[] = prevSmaller(hist); int next[] = nextSmaller(hist); int max = 0; for(int i=0;i<n;i++) max = Math.max(max,(next[i]-prev[i]-1)*hist[i]); return max; } public int maxArea(int a[][], int n, int m) { // add code here. int currRow[]=a[0]; int x=currRow.length; int maxAns=getMaxArea(currRow,x); for(int i=1;i<a.length;i++) { for(int j=0;j<a[0].length;j++) { if(a[i][j]==1) currRow[j]+=1; else currRow[j]=0; } int currAns=getMaxArea(currRow,x); maxAns=Math.max(maxAns,currAns); } return maxAns; }} +1 aloksinghbais023 weeks ago C++ solution having time complexity as O(n*m) and space complexity as O(m) is as follows :- Execution Time :- 1.62 / 2.69 sec int maxArea(int M[MAX][MAX], int n, int m) { int his[m]; int ans = 0; for(int i = 0; i<n; i++){ if(i == 0){ for(int j = 0; j < m; j++) his[j] = M[i][j]; } else{ for(int j = 0; j < m; j++){ if(M[i][j] == 0) his[j] = 0; else his[j] += M[i][j]; } } stack<int> stk; vector<int> nser(m); for(int j = m-1; j>=0; j--){ while(!stk.empty() && his[stk.top()] >= his[j]) stk.pop(); if(!stk.empty()) nser[j] = stk.top(); else nser[j] = m; stk.push(j); } while(!stk.empty()) stk.pop(); vector<int> nsel(m); for(int j = 0; j<m; j++){ while(!stk.empty() && his[stk.top()] >= his[j]) stk.pop(); if(!stk.empty()) nsel[j] = stk.top(); else nsel[j] = -1; stk.push(j); } int mx = 0; for(int j = 0; j < m; j++){ int li = nsel[j] + 1; int ri = nser[j] - 1; mx = max(mx,(ri-li+1)*his[j]); } ans = max(ans,mx); } return (ans); } 0 himanshukug19cs4 weeks ago java solution public int maxArea(int mat[][], int n, int m) { // add code here. int ans=0; int[] h = new int[m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(mat[i][j]==0) h[j]=0; else if(mat[i][j]==1) h[j]+=1; } ans=Math.max(ans,getMaxArea(h,m)); } return ans; } int getMaxArea(int heights[], int n1) { int n=heights.length; int maxArea=-1; int[] nsl=nslIndex(heights,n); int[] nsr=nsrIndex(heights,n); for(int i=0;i<n;i++){ int width=nsr[i]-nsl[i]-1; int area=heights[i]*width; maxArea=Math.max(maxArea,area); } return maxArea; } int[] nslIndex(int[] arr, int n){ Stack<Integer> s=new Stack<>(); int[] l=new int[n]; for(int i=0;i<n;i++){ while(!s.isEmpty() && arr[i]<=arr[s.peek()]) s.pop(); if(s.isEmpty()) l[i]=-1; else l[i]=s.peek(); s.add(i); } return l; } static int[] nsrIndex(int[] arr, int n){ Stack<Integer> s=new Stack<>(); int[] l=new int[n]; for(int i=n-1;i>=0;i--){ while(!s.isEmpty() && arr[i]<=arr[s.peek()]) s.pop(); if(s.isEmpty()) l[i]=n; else l[i]=s.peek(); s.add(i); } return l; } +1 swastikp17111 month ago Standard Java Solution using Maximum Rectangular Area in a Histogram class Histogram { public static int[] nslIndex(int[] arr, int n){ Stack<Integer> s=new Stack<>(); int[] l=new int[n]; for(int i=0;i<n;i++){ while(!s.isEmpty() && arr[i]<=arr[s.peek()]) s.pop(); if(s.isEmpty()) l[i]=-1; else l[i]=s.peek(); s.add(i); } return l; } public static int[] nsrIndex(int[] arr, int n){ Stack<Integer> s=new Stack<>(); int[] l=new int[n]; for(int i=n-1;i>=0;i--){ while(!s.isEmpty() && arr[i]<=arr[s.peek()]) s.pop(); if(s.isEmpty()) l[i]=n; else l[i]=s.peek(); s.add(i); } return l; } public static int getMaxArea(int heights[], int n) { int maxArea=-1; int[] nsl=nslIndex(heights,n); int[] nsr=nsrIndex(heights,n); for(int i=0;i<n;i++){ int width=nsr[i]-nsl[i]-1; int area=heights[i]*width; maxArea=Math.max(maxArea,area); } return maxArea; } } class Solution { public int maxArea(int M[][], int n, int m) { int[] heights=new int[m]; Histogram h=new Histogram(); int maxArea=-1; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ heights[j]= M[i][j]==0 ? heights[j]=0 : heights[j]+M[i][j]; } int area=h.getMaxArea(heights,m); maxArea=Math.max(maxArea,area); } return maxArea; } } 0 santoshkumarroy971 month ago // { Driver Code Startsimport java.util.*; class FindMinCost{public static void main(String args[]){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int arr[][] = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++ ) { arr[i][j] = sc.nextInt(); } } System.out.println(new Solution().maxArea(arr, n, m)); t--; }}}// } Driver Code Ends /*Complete the function given below*/class Solution { public int maxArea(int M[][], int n, int m) { // add code here. int ans=0; int col=M[0].length; int arr[]=new int[col]; // main arr; for(int i=0;i<M.length;i++){ int ptr=0; for(int j=0;j<col;j++){ if(M[i][j]==1){ arr[ptr]+=1; } else{ arr[ptr]=0; } ptr++; } Stack<Integer> s=new Stack<>(); int left[]=new int[arr.length]; int right[]=new int[arr.length]; for(int a=0;a<arr.length;a++){///////// while(!s.isEmpty() && arr[s.peek()]>=arr[a]){ s.pop(); } if(s.isEmpty()){ left[a]=-1; } else{ left[a]=s.peek(); } s.push(a); }////////// s.clear(); for(int a=arr.length-1;a>=0;a--){///////// while(!s.isEmpty() && arr[s.peek()]>=arr[a]){ s.pop(); } if(s.isEmpty()) right[a]=arr.length; else right[a]=s.peek(); s.push(a); }////////// for(int a=0;a<arr.length;a++){ int area=(right[a]-left[a]-1)*arr[a]; ans=Math.max(area,ans); } s.clear(); } return ans; }} 0 santoshkumarroy97 This comment was deleted. 0 hanumanmanyam8371 month ago class Solution { public static int getMaxArea(int arr[], int n) { // your code here Stack<Integer>st=new Stack<>(); int res=0; for(int i=0;i<n;i++) { while(!st.isEmpty() && arr[st.peek()]>=arr[i]) { int t=st.pop(); int area=arr[t]*(st.isEmpty()?i:i-st.peek()-1); res=Math.max(res,area); } st.push(i); } while(!st.isEmpty()) { int a=st.pop(); int are=arr[a]*(st.isEmpty()?n:n-st.peek()-1); res=Math.max(res,are); } return res; } public int maxArea(int mat[][], int n, int m) { // add code here. Solution s= new Solution(); int res= s.getMaxArea(mat[0], m); for(int i=1;i<n;i++) { for(int j=0;j<m;j++) { if(mat[i][j]==1) { mat[i][j]+=mat[i-1][j]; } } res=Math.max(res,s.getMaxArea(mat[i], m)); } return res; } 0 prashanttomar7651 month ago *YE KAEY NAHI CHALTA HAI JI.*😔😑 *FAILING ON TESTCASE NO. 148* int maxhist(vector<int> arr, int n) { vector<long long> right; stack<pair<long long,long long>> s; int pseudoindex = n; for(long long i=n-1; i>=0; i--) { if(s.size() == 0) right.push_back(pseudoindex); else if(s.size() > 0 && s.top().first < arr[i]) right.push_back(s.top().second); else if(s.size() > 0 && s.top().first >= arr[i]) { while(s.size() > 0 && s.top().first >= arr[i]) s.pop(); if(s.size()==0) right.push_back(pseudoindex); else right.push_back(s.top().second); } s.push({arr[i],i}); } reverse(right.begin(),right.end()); while(!s.empty()) s.pop(); // NSL vector<long long> left; pseudoindex = -1; for(long long i=0; i<n; i++) { if(s.size() == 0) left.push_back(pseudoindex); else if(s.size() > 0 && s.top().first < arr[i]) left.push_back(s.top().second); else if(s.size() > 0 && s.top().first >= arr[i]) { while(s.size() > 0 && s.top().first >= arr[i]) s.pop(); if(s.size()==0) left.push_back(pseudoindex); else left.push_back(s.top().second); } s.push({arr[i],i}); } // NSR - NSL - 1 for(int i=0; i<n; i++) { right[i] = right[i] - left[i] - 1; } // Area = width * arr[i] long long ans = INT_MIN; for(int i=0; i<n; i++) { right[i] = right[i] * arr[i]; // Max of area ans = max(right[i],ans); } return ans; } int maxArea(int M[MAX][MAX], int n, int m) { vector<int> v(m,0); int ans = INT_MIN; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if(M[i][j] == 0) v[j]=0; else v[j] = v[j] + M[i][j]; } ans = max(ans, maxhist(v,m)); } return ans; }}; -3 imaniket1 month ago C++ Solution using MAH | O(N*M) vector<int> SSL(int arr[], int n) { vector<int> ans; stack<int> st; for (int i = 0; i < n; i++) { if (st.empty()) ans.push_back(i - 0 + 1); else if (arr[st.top()] < arr[i]) ans.push_back(i - st.top()); else if (arr[st.top()] >= arr[i]) { while (!st.empty() && arr[st.top()] >= arr[i]) st.pop(); if (st.empty()) ans.push_back(i - 0 + 1); else ans.push_back(i - st.top()); } st.push(i); } return ans; } vector<int> SSR(int arr[], int n) { vector<int> ans; stack<int> st; for (int i = n - 1; i >= 0; i--) { if (st.empty()) ans.push_back(n - i); else if (arr[st.top()] < arr[i]) ans.push_back(st.top() - i); else if (arr[st.top()] >= arr[i]) { while (!st.empty() && arr[st.top()] >= arr[i]) st.pop(); if (st.empty()) ans.push_back(n - i); else ans.push_back(st.top() - i); } st.push(i); } reverse(ans.begin(), ans.end()); return ans; } int maxHist(int a[], int n) { auto ssl = SSL(a, n); auto ssr = SSR(a, n); int maxi = INT_MIN; for (int i = 0; i < n; i++) maxi = max(maxi, a[i] * (ssr[i] + ssl[i] - 1)); return maxi; } int maxArea(int M[MAX][MAX], int n, int m) { for (int i = 1; i < n; i++) for (int j = 0; j < m; j++) if (M[i][j] == 1) M[i][j] += M[i-1][j]; int maxi = INT_MIN; for (int i = 0; i < n; i++) maxi = max(maxi, maxHist(M[i], m)); return maxi; } 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": 354, "s": 238, "text": "Given a binary matrix M of size n X m. Find the maximum area of a rectangle formed only of 1s in the given matrix. " }, { "code": null, "e": 365, "s": 354, "text": "Example 1:" }, { "code": null, "e": 635, "s": 365, "text": "Input:\nn = 4, m = 4\nM[][] = {{0 1 1 0},\n {1 1 1 1},\n {1 1 1 1},\n {1 1 0 0}}\nOutput: 8\nExplanation: For the above test case the\nmatrix will look like\n0 1 1 0\n1 1 1 1\n1 1 1 1\n1 1 0 0\nthe max size rectangle is \n1 1 1 1\n1 1 1 1\nand area is 4 *2 = 8." }, { "code": null, "e": 932, "s": 635, "text": "Your Task: \nYour task is to complete the function maxArea which returns the maximum size rectangle area in a binary-sub-matrix with all 1’s. The function takes 3 arguments the first argument is the Matrix M[ ] [ ] and the next two are two integers n and m which denotes the size of the matrix M. " }, { "code": null, "e": 999, "s": 932, "text": "Expected Time Complexity : O(n*m)\nExpected Auixiliary Space : O(m)" }, { "code": null, "e": 1347, "s": 999, "text": "Constraints:\n1<=n,m<=1000\n0<=M[][]<=1\n\nNote:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1350, "s": 1347, "text": "+1" }, { "code": null, "e": 1376, "s": 1350, "text": "anilcangulkaya73 days ago" }, { "code": null, "e": 1386, "s": 1376, "text": "0.89/2.62" }, { "code": null, "e": 1985, "s": 1386, "text": "\n\n#define xSafe(x, n) (x < n)\n#define ySafe(y, m) (y < m)\n\nint maxArea(int M[MAX][MAX], int n, int m) {\n // Your code here\n int maxCount = 0;\n for(int x = 0; x < n; ++x)\n for(int y = 0; y < m; ++y)\n for(int i = 0; M[x + i][y] && xSafe(i + x, n); ++i)\n {\n for(int j = 0; ySafe(j + y, m); ++j)\n {\n for(int k = 0; k <= i; ++k)\n if(!M[x+k][y+j]) { goto not_correct; }\n \n maxCount = max((i + 1) * (j + 1), maxCount);\n }\n not_correct:{}\n }\n \n return maxCount;\n}" }, { "code": null, "e": 1987, "s": 1985, "text": "0" }, { "code": null, "e": 2015, "s": 1987, "text": "bobbyprajapati962 weeks ago" }, { "code": null, "e": 2036, "s": 2015, "text": "Simple Java Solution" }, { "code": null, "e": 3685, "s": 2036, "text": "class Solution { static int[] prevSmaller(int arr[]){ Stack<Integer> st = new Stack<>(); int ans[] = new int[arr.length]; ans[0] = -1; for(int i=0;i<arr.length;i++) { while(!st.isEmpty() && arr[st.peek()]>=arr[i]) st.pop(); ans[i]=st.isEmpty()?-1:st.peek(); st.push(i); } return ans; } static int[] nextSmaller(int arr[]){ Stack<Integer> st = new Stack<>(); int ans[] = new int[arr.length]; ans[arr.length-1] = arr.length; st.push(arr.length-1); for(int i=arr.length-1;i>=0;i--){ while(!st.isEmpty() && arr[st.peek()]>=arr[i]) st.pop(); ans[i] = st.isEmpty()?arr.length:st.peek(); st.push(i); } return ans; } //Function to find largest rectangular area possible in a given histogram. public static int getMaxArea(int hist[], int n) { // your code here int prev[] = prevSmaller(hist); int next[] = nextSmaller(hist); int max = 0; for(int i=0;i<n;i++) max = Math.max(max,(next[i]-prev[i]-1)*hist[i]); return max; } public int maxArea(int a[][], int n, int m) { // add code here. int currRow[]=a[0]; int x=currRow.length; int maxAns=getMaxArea(currRow,x); for(int i=1;i<a.length;i++) { for(int j=0;j<a[0].length;j++) { if(a[i][j]==1) currRow[j]+=1; else currRow[j]=0; } int currAns=getMaxArea(currRow,x); maxAns=Math.max(maxAns,currAns); } return maxAns; }}" }, { "code": null, "e": 3688, "s": 3685, "text": "+1" }, { "code": null, "e": 3715, "s": 3688, "text": "aloksinghbais023 weeks ago" }, { "code": null, "e": 3808, "s": 3715, "text": "C++ solution having time complexity as O(n*m) and space complexity as O(m) is as follows :- " }, { "code": null, "e": 3844, "s": 3810, "text": "Execution Time :- 1.62 / 2.69 sec" }, { "code": null, "e": 5137, "s": 3846, "text": "int maxArea(int M[MAX][MAX], int n, int m) { int his[m]; int ans = 0; for(int i = 0; i<n; i++){ if(i == 0){ for(int j = 0; j < m; j++) his[j] = M[i][j]; } else{ for(int j = 0; j < m; j++){ if(M[i][j] == 0) his[j] = 0; else his[j] += M[i][j]; } } stack<int> stk; vector<int> nser(m); for(int j = m-1; j>=0; j--){ while(!stk.empty() && his[stk.top()] >= his[j]) stk.pop(); if(!stk.empty()) nser[j] = stk.top(); else nser[j] = m; stk.push(j); } while(!stk.empty()) stk.pop(); vector<int> nsel(m); for(int j = 0; j<m; j++){ while(!stk.empty() && his[stk.top()] >= his[j]) stk.pop(); if(!stk.empty()) nsel[j] = stk.top(); else nsel[j] = -1; stk.push(j); } int mx = 0; for(int j = 0; j < m; j++){ int li = nsel[j] + 1; int ri = nser[j] - 1; mx = max(mx,(ri-li+1)*his[j]); } ans = max(ans,mx); } return (ans); }" }, { "code": null, "e": 5139, "s": 5137, "text": "0" }, { "code": null, "e": 5166, "s": 5139, "text": "himanshukug19cs4 weeks ago" }, { "code": null, "e": 5180, "s": 5166, "text": "java solution" }, { "code": null, "e": 6671, "s": 5180, "text": " public int maxArea(int mat[][], int n, int m) { // add code here. int ans=0; int[] h = new int[m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(mat[i][j]==0) h[j]=0; else if(mat[i][j]==1) h[j]+=1; } ans=Math.max(ans,getMaxArea(h,m)); } return ans; } int getMaxArea(int heights[], int n1) { int n=heights.length; int maxArea=-1; int[] nsl=nslIndex(heights,n); int[] nsr=nsrIndex(heights,n); for(int i=0;i<n;i++){ int width=nsr[i]-nsl[i]-1; int area=heights[i]*width; maxArea=Math.max(maxArea,area); } return maxArea; } int[] nslIndex(int[] arr, int n){ Stack<Integer> s=new Stack<>(); int[] l=new int[n]; for(int i=0;i<n;i++){ while(!s.isEmpty() && arr[i]<=arr[s.peek()]) s.pop(); if(s.isEmpty()) l[i]=-1; else l[i]=s.peek(); s.add(i); } return l; } static int[] nsrIndex(int[] arr, int n){ Stack<Integer> s=new Stack<>(); int[] l=new int[n]; for(int i=n-1;i>=0;i--){ while(!s.isEmpty() && arr[i]<=arr[s.peek()]) s.pop(); if(s.isEmpty()) l[i]=n; else l[i]=s.peek(); s.add(i); } return l; } " }, { "code": null, "e": 6674, "s": 6671, "text": "+1" }, { "code": null, "e": 6698, "s": 6674, "text": "swastikp17111 month ago" }, { "code": null, "e": 6767, "s": 6698, "text": "Standard Java Solution using Maximum Rectangular Area in a Histogram" }, { "code": null, "e": 8451, "s": 6769, "text": "class Histogram\n{\n public static int[] nslIndex(int[] arr, int n){\n \n Stack<Integer> s=new Stack<>();\n int[] l=new int[n];\n \n for(int i=0;i<n;i++){\n while(!s.isEmpty() && arr[i]<=arr[s.peek()])\n s.pop();\n if(s.isEmpty())\n l[i]=-1;\n else\n l[i]=s.peek();\n s.add(i);\n }\n return l;\n }\n public static int[] nsrIndex(int[] arr, int n){\n \n Stack<Integer> s=new Stack<>();\n int[] l=new int[n];\n \n for(int i=n-1;i>=0;i--){\n while(!s.isEmpty() && arr[i]<=arr[s.peek()])\n s.pop();\n if(s.isEmpty())\n l[i]=n;\n else\n l[i]=s.peek();\n s.add(i);\n }\n return l;\n }\n public static int getMaxArea(int heights[], int n) \n {\n int maxArea=-1;\n \n int[] nsl=nslIndex(heights,n);\n int[] nsr=nsrIndex(heights,n);\n \n for(int i=0;i<n;i++){\n int width=nsr[i]-nsl[i]-1;\n int area=heights[i]*width;\n maxArea=Math.max(maxArea,area);\n }\n return maxArea;\n }\n \n}\nclass Solution {\n public int maxArea(int M[][], int n, int m) {\n \n int[] heights=new int[m];\n Histogram h=new Histogram();\n \n int maxArea=-1;\n \n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n heights[j]= M[i][j]==0 ? heights[j]=0 : heights[j]+M[i][j];\n }\n int area=h.getMaxArea(heights,m);\n maxArea=Math.max(maxArea,area);\n }\n return maxArea;\n }\n}" }, { "code": null, "e": 8453, "s": 8451, "text": "0" }, { "code": null, "e": 8482, "s": 8453, "text": "santoshkumarroy971 month ago" }, { "code": null, "e": 8525, "s": 8482, "text": "// { Driver Code Startsimport java.util.*;" }, { "code": null, "e": 8912, "s": 8525, "text": "class FindMinCost{public static void main(String args[]){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int arr[][] = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++ ) { arr[i][j] = sc.nextInt(); } } System.out.println(new Solution().maxArea(arr, n, m)); t--; }}}// } Driver Code Ends" }, { "code": null, "e": 10609, "s": 8912, "text": "/*Complete the function given below*/class Solution { public int maxArea(int M[][], int n, int m) { // add code here. int ans=0; int col=M[0].length; int arr[]=new int[col]; // main arr; for(int i=0;i<M.length;i++){ int ptr=0; for(int j=0;j<col;j++){ if(M[i][j]==1){ arr[ptr]+=1; } else{ arr[ptr]=0; } ptr++; } Stack<Integer> s=new Stack<>(); int left[]=new int[arr.length]; int right[]=new int[arr.length]; for(int a=0;a<arr.length;a++){///////// while(!s.isEmpty() && arr[s.peek()]>=arr[a]){ s.pop(); } if(s.isEmpty()){ left[a]=-1; } else{ left[a]=s.peek(); } s.push(a); }////////// s.clear(); for(int a=arr.length-1;a>=0;a--){///////// while(!s.isEmpty() && arr[s.peek()]>=arr[a]){ s.pop(); } if(s.isEmpty()) right[a]=arr.length; else right[a]=s.peek(); s.push(a); }////////// for(int a=0;a<arr.length;a++){ int area=(right[a]-left[a]-1)*arr[a]; ans=Math.max(area,ans); } s.clear(); } return ans; }}" }, { "code": null, "e": 10611, "s": 10609, "text": "0" }, { "code": null, "e": 10629, "s": 10611, "text": "santoshkumarroy97" }, { "code": null, "e": 10655, "s": 10629, "text": "This comment was deleted." }, { "code": null, "e": 10657, "s": 10655, "text": "0" }, { "code": null, "e": 10685, "s": 10657, "text": "hanumanmanyam8371 month ago" }, { "code": null, "e": 11910, "s": 10685, "text": "class Solution {\n public static int getMaxArea(int arr[], int n) \n {\n // your code here\n Stack<Integer>st=new Stack<>();\n int res=0;\n for(int i=0;i<n;i++)\n {\n while(!st.isEmpty() && arr[st.peek()]>=arr[i])\n {\n int t=st.pop();\n int area=arr[t]*(st.isEmpty()?i:i-st.peek()-1);\n res=Math.max(res,area);\n \n }\n st.push(i);\n }\n while(!st.isEmpty())\n {\n \n int a=st.pop();\n int are=arr[a]*(st.isEmpty()?n:n-st.peek()-1);\n res=Math.max(res,are);\n \n \n }\n return res;\n }\n public int maxArea(int mat[][], int n, int m) {\n // add code here.\n Solution s= new Solution();\n int res= s.getMaxArea(mat[0], m);\n for(int i=1;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(mat[i][j]==1)\n {\n mat[i][j]+=mat[i-1][j];\n }\n }\n res=Math.max(res,s.getMaxArea(mat[i], m));\n \n }\n return res;\n \n \n \n }" }, { "code": null, "e": 11912, "s": 11910, "text": "0" }, { "code": null, "e": 11940, "s": 11912, "text": "prashanttomar7651 month ago" }, { "code": null, "e": 11972, "s": 11940, "text": "*YE KAEY NAHI CHALTA HAI JI.*😔😑" }, { "code": null, "e": 12002, "s": 11972, "text": "*FAILING ON TESTCASE NO. 148*" }, { "code": null, "e": 14173, "s": 12004, "text": "int maxhist(vector<int> arr, int n) { vector<long long> right; stack<pair<long long,long long>> s; int pseudoindex = n; for(long long i=n-1; i>=0; i--) { if(s.size() == 0) right.push_back(pseudoindex); else if(s.size() > 0 && s.top().first < arr[i]) right.push_back(s.top().second); else if(s.size() > 0 && s.top().first >= arr[i]) { while(s.size() > 0 && s.top().first >= arr[i]) s.pop(); if(s.size()==0) right.push_back(pseudoindex); else right.push_back(s.top().second); } s.push({arr[i],i}); } reverse(right.begin(),right.end()); while(!s.empty()) s.pop(); // NSL vector<long long> left; pseudoindex = -1; for(long long i=0; i<n; i++) { if(s.size() == 0) left.push_back(pseudoindex); else if(s.size() > 0 && s.top().first < arr[i]) left.push_back(s.top().second); else if(s.size() > 0 && s.top().first >= arr[i]) { while(s.size() > 0 && s.top().first >= arr[i]) s.pop(); if(s.size()==0) left.push_back(pseudoindex); else left.push_back(s.top().second); } s.push({arr[i],i}); } // NSR - NSL - 1 for(int i=0; i<n; i++) { right[i] = right[i] - left[i] - 1; } // Area = width * arr[i] long long ans = INT_MIN; for(int i=0; i<n; i++) { right[i] = right[i] * arr[i]; // Max of area ans = max(right[i],ans); } return ans; } int maxArea(int M[MAX][MAX], int n, int m) { vector<int> v(m,0); int ans = INT_MIN; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if(M[i][j] == 0) v[j]=0; else v[j] = v[j] + M[i][j]; } ans = max(ans, maxhist(v,m)); } return ans; }}; " }, { "code": null, "e": 14188, "s": 14185, "text": "-3" }, { "code": null, "e": 14208, "s": 14188, "text": "imaniket1 month ago" }, { "code": null, "e": 14240, "s": 14208, "text": "C++ Solution using MAH | O(N*M)" }, { "code": null, "e": 15949, "s": 14240, "text": "vector<int> SSL(int arr[], int n)\n{\n vector<int> ans;\n stack<int> st;\n for (int i = 0; i < n; i++)\n {\n if (st.empty())\n ans.push_back(i - 0 + 1);\n else if (arr[st.top()] < arr[i])\n ans.push_back(i - st.top());\n else if (arr[st.top()] >= arr[i])\n {\n while (!st.empty() && arr[st.top()] >= arr[i])\n st.pop();\n if (st.empty())\n ans.push_back(i - 0 + 1);\n else\n ans.push_back(i - st.top());\n }\n st.push(i);\n }\n return ans;\n}\n\nvector<int> SSR(int arr[], int n)\n{\n vector<int> ans;\n stack<int> st;\n for (int i = n - 1; i >= 0; i--)\n {\n if (st.empty())\n ans.push_back(n - i);\n else if (arr[st.top()] < arr[i])\n ans.push_back(st.top() - i);\n else if (arr[st.top()] >= arr[i])\n {\n while (!st.empty() && arr[st.top()] >= arr[i])\n st.pop();\n if (st.empty())\n ans.push_back(n - i);\n else\n ans.push_back(st.top() - i);\n }\n st.push(i);\n }\n reverse(ans.begin(), ans.end());\n return ans;\n}\n\nint maxHist(int a[], int n)\n{\n auto ssl = SSL(a, n);\n auto ssr = SSR(a, n);\n int maxi = INT_MIN;\n for (int i = 0; i < n; i++)\n maxi = max(maxi, a[i] * (ssr[i] + ssl[i] - 1));\n return maxi;\n}\n\nint maxArea(int M[MAX][MAX], int n, int m) {\n for (int i = 1; i < n; i++)\n for (int j = 0; j < m; j++)\n if (M[i][j] == 1) M[i][j] += M[i-1][j];\n \n int maxi = INT_MIN;\n for (int i = 0; i < n; i++)\n maxi = max(maxi, maxHist(M[i], m));\n return maxi;\n}" }, { "code": null, "e": 16095, "s": 15949, "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": 16131, "s": 16095, "text": " Login to access your submissions. " }, { "code": null, "e": 16141, "s": 16131, "text": "\nProblem\n" }, { "code": null, "e": 16151, "s": 16141, "text": "\nContest\n" }, { "code": null, "e": 16214, "s": 16151, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 16362, "s": 16214, "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": 16570, "s": 16362, "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": 16676, "s": 16570, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Fusing EfficientNet & YoloV5 — Advanced Object Detection 2 stage pipeline tutorial | by Mostafa Ibrahim | Towards Data Science
In this article, I am going to be explaining a concept which I call the “2 class filter”. This is an ensembling technique for object detection and classification models that was heavily used during a Kaggle competition that I have been doing for the last few weeks. This technique has been used by almost everyone doing the competition and it seems to boost the performance by around 5–25% which is quite useful. We start off by training a YoloV5 model on our dataset whilst using weighted boxes fusion (WBF) for post/pre-processing, if you want to find out more, I suggest checking these 2 articles: towardsdatascience.com towardsdatascience.com I don’t want to dive into the details of training YoloV5 with WBF again. But, essentially all you need to do is to eliminate duplicate boxes using WBF, then preprocess the data to run YoloV5 on it. YoloV5 needs a certain hierarchy for the dataset to be present to start training and evaluation. The next thing to do is to train a classification network on the dataset. But, the interesting bit is that although the object detection models were trained on 14 different classes (13 different types of diseases and 1 no-disease class), we are going to train the classification network on only 2 classes (disease and no disease). You can think of this as a modeling trick that simplifies our data science problem because classifying 2 classes for a network is much easier than classifying 14 and when we fuse those 2 networks we don’t really need the specifics of every disease, we will just need one of those 2 classes. Of course, this might be a bit different for your problem, so you will probably need to experiment with different settings, but hopefully, you can get an idea or 2 from this article. One of the best State-of-the-art current classification networks is EfficientNet. For this dataset, we are going to be using a B6 EfficientNet, trained with Keras (TensorFlow), along with these augmentations: ( rescale=1.0 / 255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode="nearest",) If you want to see the full tutorial, I suggest checking out this: towardsdatascience.com This is where the 2 class filter comes in to boost performance and what the article is really about. I didn’t want to talk too much about training YoloV5 and EfficientNet since there are a lot of resources for those. The main idea that I wanted to highlight is that although the classification predictions of Yolo are quite good if you can mix them with the classification of another more powerful network, you can get a quite decent boost in performance. Let’s see how this can be implemented. The idea being used here is to set a high and a low threshold. And then we are going to be checking each classification prediction. If the probability is less than the low threshold, we set whatever the prediction is to “No Disease”. Recall that our original problem was classifying one of the 14 diseases or the “No Disease” class. This low threshold can be any value between 0 and 1, but will probably fall be something between 0 and 0.1. Moreover, if the classification prediction is between the low and high threshold, we add a “No Disease” prediction with EfficientNet’s confidence for that prediction (Not Yolo’s) because there is a higher chance of having any disease in this scenario. Finally, if the classification prediction is higher than the high threshold, we do nothing because this means that the network is highly confident. This can be implemented as shown here: low_thr = 0.08high_thr = 0.95def filter_2cls(row, low_thr=low_thr, high_thr=high_thr): prob = row['target'] if prob<low_thr: ## Less chance of having any disease row['PredictionString'] = '14 1 0 0 1 1' elif low_thr<=prob<high_thr: ## More chance of having any disease row['PredictionString']+=f' 14 {prob} 0 0 1 1' elif high_thr<=prob: ## Good chance of having any disease so believe in object detection model row['PredictionString'] = row['PredictionString'] else: raise ValueError('Prediction must be from [0-1]') return row Source: Kaggle Final thoughts I have experimented with this 2 class filter on various different scenarios and models during the competition and it always seems to boost the performance by up to 25% which is amazing. I think if you want to apply it to your custom scenario, you will need to think about what cases the classification network prediction can help your object detection model. It’s not exactly swapping the prediction confidences, it's more about “fusing” them in a smart way.
[ { "code": null, "e": 584, "s": 171, "text": "In this article, I am going to be explaining a concept which I call the “2 class filter”. This is an ensembling technique for object detection and classification models that was heavily used during a Kaggle competition that I have been doing for the last few weeks. This technique has been used by almost everyone doing the competition and it seems to boost the performance by around 5–25% which is quite useful." }, { "code": null, "e": 772, "s": 584, "text": "We start off by training a YoloV5 model on our dataset whilst using weighted boxes fusion (WBF) for post/pre-processing, if you want to find out more, I suggest checking these 2 articles:" }, { "code": null, "e": 795, "s": 772, "text": "towardsdatascience.com" }, { "code": null, "e": 818, "s": 795, "text": "towardsdatascience.com" }, { "code": null, "e": 1113, "s": 818, "text": "I don’t want to dive into the details of training YoloV5 with WBF again. But, essentially all you need to do is to eliminate duplicate boxes using WBF, then preprocess the data to run YoloV5 on it. YoloV5 needs a certain hierarchy for the dataset to be present to start training and evaluation." }, { "code": null, "e": 1918, "s": 1113, "text": "The next thing to do is to train a classification network on the dataset. But, the interesting bit is that although the object detection models were trained on 14 different classes (13 different types of diseases and 1 no-disease class), we are going to train the classification network on only 2 classes (disease and no disease). You can think of this as a modeling trick that simplifies our data science problem because classifying 2 classes for a network is much easier than classifying 14 and when we fuse those 2 networks we don’t really need the specifics of every disease, we will just need one of those 2 classes. Of course, this might be a bit different for your problem, so you will probably need to experiment with different settings, but hopefully, you can get an idea or 2 from this article." }, { "code": null, "e": 2127, "s": 1918, "text": "One of the best State-of-the-art current classification networks is EfficientNet. For this dataset, we are going to be using a B6 EfficientNet, trained with Keras (TensorFlow), along with these augmentations:" }, { "code": null, "e": 2315, "s": 2127, "text": "( rescale=1.0 / 255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode=\"nearest\",)" }, { "code": null, "e": 2382, "s": 2315, "text": "If you want to see the full tutorial, I suggest checking out this:" }, { "code": null, "e": 2405, "s": 2382, "text": "towardsdatascience.com" }, { "code": null, "e": 2622, "s": 2405, "text": "This is where the 2 class filter comes in to boost performance and what the article is really about. I didn’t want to talk too much about training YoloV5 and EfficientNet since there are a lot of resources for those." }, { "code": null, "e": 2900, "s": 2622, "text": "The main idea that I wanted to highlight is that although the classification predictions of Yolo are quite good if you can mix them with the classification of another more powerful network, you can get a quite decent boost in performance. Let’s see how this can be implemented." }, { "code": null, "e": 3741, "s": 2900, "text": "The idea being used here is to set a high and a low threshold. And then we are going to be checking each classification prediction. If the probability is less than the low threshold, we set whatever the prediction is to “No Disease”. Recall that our original problem was classifying one of the 14 diseases or the “No Disease” class. This low threshold can be any value between 0 and 1, but will probably fall be something between 0 and 0.1. Moreover, if the classification prediction is between the low and high threshold, we add a “No Disease” prediction with EfficientNet’s confidence for that prediction (Not Yolo’s) because there is a higher chance of having any disease in this scenario. Finally, if the classification prediction is higher than the high threshold, we do nothing because this means that the network is highly confident." }, { "code": null, "e": 3780, "s": 3741, "text": "This can be implemented as shown here:" }, { "code": null, "e": 4376, "s": 3780, "text": "low_thr = 0.08high_thr = 0.95def filter_2cls(row, low_thr=low_thr, high_thr=high_thr): prob = row['target'] if prob<low_thr: ## Less chance of having any disease row['PredictionString'] = '14 1 0 0 1 1' elif low_thr<=prob<high_thr: ## More chance of having any disease row['PredictionString']+=f' 14 {prob} 0 0 1 1' elif high_thr<=prob: ## Good chance of having any disease so believe in object detection model row['PredictionString'] = row['PredictionString'] else: raise ValueError('Prediction must be from [0-1]') return row" }, { "code": null, "e": 4391, "s": 4376, "text": "Source: Kaggle" }, { "code": null, "e": 4406, "s": 4391, "text": "Final thoughts" } ]
Erlang - Functions
Erlang is known as a functional programming language, hence you would expect to see a lot of emphasis on how functions work in Erlang. This chapter covers what all can be done with the functions in Erlang. The syntax of a function declaration is as follows − FunctionName(Pattern1... PatternN) -> Body; Where, FunctionName − The function name is an atom. FunctionName − The function name is an atom. Pattern1... PatternN − Each argument is a pattern. The number of arguments N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions. Pattern1... PatternN − Each argument is a pattern. The number of arguments N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions. Body − A clause body consists of a sequence of expressions separated by comma (,): Body − A clause body consists of a sequence of expressions separated by comma (,): The following program is a simple example of the use of functions − -module(helloworld). -export([add/2,start/0]). add(X,Y) -> Z = X+Y, io:fwrite("~w~n",[Z]). start() -> add(5,6). The following pointers should be noted about the above program − We are defining two functions, one is called add which takes 2 parameters and the other is the start function. We are defining two functions, one is called add which takes 2 parameters and the other is the start function. Both functions are defined with the export function. If we don’t do this, we will not be able to use the function. Both functions are defined with the export function. If we don’t do this, we will not be able to use the function. One function can be called inside another. Here we are calling the add function from the start function. One function can be called inside another. Here we are calling the add function from the start function. The output of the above program will be − 11 An anonymous function is a function, which has no name associated with it. Erlang has the facility to define anonymous functions. The following program is an example of an anonymous function. -module(helloworld). -export([start/0]). start() -> Fn = fun() -> io:fwrite("Anonymous Function") end, Fn(). The following points need to be noted about the above example − The anonymous function is defined with the fun() keyword. The anonymous function is defined with the fun() keyword. The Function is assigned to a variable called Fn. The Function is assigned to a variable called Fn. The Function is called via the variable name. The Function is called via the variable name. The output of the above program will be − Anonymous Function Erlang functions can be defined with zero or more parameters. Function overloading is also possible, wherein you can define a function with the same name multiple times, as long as they have different number of parameters. In the following example, the function demo is defined with multiple arguments for each function definition. -module(helloworld). -export([add/2,add/3,start/0]). add(X,Y) -> Z = X+Y, io:fwrite("~w~n",[Z]). add(X,Y,Z) -> A = X+Y+Z, io:fwrite("~w~n",[A]). start() -> add(5,6), add(5,6,6). In the above program, we are defining the add function twice. But the definition of the first add function takes in two parameters and the second one takes in three parameters. The output of the above program will be − 11 17 Functions in Erlang also have the capability of having guard sequences. These are nothing but expressions which only when evaluated to true will cause the function to run. The syntax of a function with a guard sequence is shown in the following program. FunctionName(Pattern1... PatternN) [when GuardSeq1]-> Body; Where, FunctionName − The function name is an atom. FunctionName − The function name is an atom. Pattern1... PatternN − Each argument is a pattern. The number of arguments N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions. Pattern1... PatternN − Each argument is a pattern. The number of arguments N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions. Body − A clause body consists of a sequence of expressions which are separated by a comma (,). Body − A clause body consists of a sequence of expressions which are separated by a comma (,). GuardSeq1 − This is the expression which gets evaluated when the function is called. GuardSeq1 − This is the expression which gets evaluated when the function is called. The following program is a simple example of the use of a function with a guard sequence. -module(helloworld). -export([add/1,start/0]). add(X) when X>3 -> io:fwrite("~w~n",[X]). start() -> add(4). The output of the above program is − 4 If the add function was called as add(3), the program will result in an error. Print Add Notes Bookmark this page
[ { "code": null, "e": 2507, "s": 2301, "text": "Erlang is known as a functional programming language, hence you would expect to see a lot of emphasis on how functions work in Erlang. This chapter covers what all can be done with the functions in Erlang." }, { "code": null, "e": 2560, "s": 2507, "text": "The syntax of a function declaration is as follows −" }, { "code": null, "e": 2605, "s": 2560, "text": "FunctionName(Pattern1... PatternN) ->\nBody;\n" }, { "code": null, "e": 2612, "s": 2605, "text": "Where," }, { "code": null, "e": 2657, "s": 2612, "text": "FunctionName − The function name is an atom." }, { "code": null, "e": 2702, "s": 2657, "text": "FunctionName − The function name is an atom." }, { "code": null, "e": 3008, "s": 2702, "text": "Pattern1... PatternN − Each argument is a pattern. The number of arguments N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions." }, { "code": null, "e": 3314, "s": 3008, "text": "Pattern1... PatternN − Each argument is a pattern. The number of arguments N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions." }, { "code": null, "e": 3397, "s": 3314, "text": "Body − A clause body consists of a sequence of expressions separated by comma (,):" }, { "code": null, "e": 3480, "s": 3397, "text": "Body − A clause body consists of a sequence of expressions separated by comma (,):" }, { "code": null, "e": 3548, "s": 3480, "text": "The following program is a simple example of the use of functions −" }, { "code": null, "e": 3680, "s": 3548, "text": "-module(helloworld). \n-export([add/2,start/0]). \n\nadd(X,Y) -> \n Z = X+Y, \n io:fwrite(\"~w~n\",[Z]). \n \nstart() -> \n add(5,6)." }, { "code": null, "e": 3745, "s": 3680, "text": "The following pointers should be noted about the above program −" }, { "code": null, "e": 3856, "s": 3745, "text": "We are defining two functions, one is called add which takes 2 parameters and the other is the start function." }, { "code": null, "e": 3967, "s": 3856, "text": "We are defining two functions, one is called add which takes 2 parameters and the other is the start function." }, { "code": null, "e": 4082, "s": 3967, "text": "Both functions are defined with the export function. If we don’t do this, we will not be able to use the function." }, { "code": null, "e": 4197, "s": 4082, "text": "Both functions are defined with the export function. If we don’t do this, we will not be able to use the function." }, { "code": null, "e": 4302, "s": 4197, "text": "One function can be called inside another. Here we are calling the add function from the start function." }, { "code": null, "e": 4407, "s": 4302, "text": "One function can be called inside another. Here we are calling the add function from the start function." }, { "code": null, "e": 4449, "s": 4407, "text": "The output of the above program will be −" }, { "code": null, "e": 4453, "s": 4449, "text": "11\n" }, { "code": null, "e": 4645, "s": 4453, "text": "An anonymous function is a function, which has no name associated with it. Erlang has the facility to define anonymous functions. The following program is an example of an anonymous function." }, { "code": null, "e": 4772, "s": 4645, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n Fn = fun() -> \n io:fwrite(\"Anonymous Function\") end, \n Fn()." }, { "code": null, "e": 4836, "s": 4772, "text": "The following points need to be noted about the above example −" }, { "code": null, "e": 4894, "s": 4836, "text": "The anonymous function is defined with the fun() keyword." }, { "code": null, "e": 4952, "s": 4894, "text": "The anonymous function is defined with the fun() keyword." }, { "code": null, "e": 5002, "s": 4952, "text": "The Function is assigned to a variable called Fn." }, { "code": null, "e": 5052, "s": 5002, "text": "The Function is assigned to a variable called Fn." }, { "code": null, "e": 5098, "s": 5052, "text": "The Function is called via the variable name." }, { "code": null, "e": 5144, "s": 5098, "text": "The Function is called via the variable name." }, { "code": null, "e": 5186, "s": 5144, "text": "The output of the above program will be −" }, { "code": null, "e": 5206, "s": 5186, "text": "Anonymous Function\n" }, { "code": null, "e": 5429, "s": 5206, "text": "Erlang functions can be defined with zero or more parameters. Function overloading is also possible, wherein you can define a function with the same name multiple times, as long as they have different number of parameters." }, { "code": null, "e": 5538, "s": 5429, "text": "In the following example, the function demo is defined with multiple arguments for each function definition." }, { "code": null, "e": 5750, "s": 5538, "text": "-module(helloworld). \n-export([add/2,add/3,start/0]). \n\nadd(X,Y) -> \n Z = X+Y, \n io:fwrite(\"~w~n\",[Z]). \n \nadd(X,Y,Z) -> \n A = X+Y+Z, \n io:fwrite(\"~w~n\",[A]). \n \nstart() ->\n add(5,6), \n add(5,6,6)." }, { "code": null, "e": 5927, "s": 5750, "text": "In the above program, we are defining the add function twice. But the definition of the first add function takes in two parameters and the second one takes in three parameters." }, { "code": null, "e": 5969, "s": 5927, "text": "The output of the above program will be −" }, { "code": null, "e": 5976, "s": 5969, "text": "11\n17\n" }, { "code": null, "e": 6148, "s": 5976, "text": "Functions in Erlang also have the capability of having guard sequences. These are nothing but expressions which only when evaluated to true will cause the function to run." }, { "code": null, "e": 6230, "s": 6148, "text": "The syntax of a function with a guard sequence is shown in the following program." }, { "code": null, "e": 6291, "s": 6230, "text": "FunctionName(Pattern1... PatternN) [when GuardSeq1]->\nBody;\n" }, { "code": null, "e": 6298, "s": 6291, "text": "Where," }, { "code": null, "e": 6343, "s": 6298, "text": "FunctionName − The function name is an atom." }, { "code": null, "e": 6388, "s": 6343, "text": "FunctionName − The function name is an atom." }, { "code": null, "e": 6694, "s": 6388, "text": "Pattern1... PatternN − Each argument is a pattern. The number of arguments N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions." }, { "code": null, "e": 7000, "s": 6694, "text": "Pattern1... PatternN − Each argument is a pattern. The number of arguments N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions." }, { "code": null, "e": 7095, "s": 7000, "text": "Body − A clause body consists of a sequence of expressions which are separated by a comma (,)." }, { "code": null, "e": 7190, "s": 7095, "text": "Body − A clause body consists of a sequence of expressions which are separated by a comma (,)." }, { "code": null, "e": 7275, "s": 7190, "text": "GuardSeq1 − This is the expression which gets evaluated when the function is called." }, { "code": null, "e": 7360, "s": 7275, "text": "GuardSeq1 − This is the expression which gets evaluated when the function is called." }, { "code": null, "e": 7450, "s": 7360, "text": "The following program is a simple example of the use of a function with a guard sequence." }, { "code": null, "e": 7571, "s": 7450, "text": "-module(helloworld). \n-export([add/1,start/0]). \n\nadd(X) when X>3 -> \n io:fwrite(\"~w~n\",[X]). \n\nstart() -> \n add(4)." }, { "code": null, "e": 7608, "s": 7571, "text": "The output of the above program is −" }, { "code": null, "e": 7611, "s": 7608, "text": "4\n" }, { "code": null, "e": 7690, "s": 7611, "text": "If the add function was called as add(3), the program will result in an error." }, { "code": null, "e": 7697, "s": 7690, "text": " Print" }, { "code": null, "e": 7708, "s": 7697, "text": " Add Notes" } ]
MongoDB Mock Test
This section presents you various set of Mock Tests related to MongoDB Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Q 1 - What kind of database MongoDB is? A - Graph Oriented B - Document Oriented C - Key Value Pair D - Column Based MongoDB stores data in JSON structure based documents. These documents in turn contains data in form of key value pairs. Q 2 - A collection and a document in MongoDB is equivalent to which of the SQL concepts respectively? A - Table and Row B - Table and Column C - Column and Row D - Database and Table The way SQL databases stores data rows in a table, MonngoDB stores documents inside collections. Q 3 - Which of the following is correct about MongoDB? A - MongoDB uses JSON format to represent documents B - MongoDB supports collection joins C - MongoDB supports some of the SQL functions D - MongoDB supports geospatial indexes MongoDB provides specific supports for functionalities related to 2d and 3d geospatial problems. Q 4 - Which of the following is a valid MongoDB JSON document: A {} B { "user_id"=1, "user_name"="Joe Sanders", "occupation"=["engineer","writer"] } C { "user_id":1; "user_name":"Joe Sanders"; "occupation":["engineer","writer"] } D { "user_id":1, "user_name":"Joe Sanders", "occupation":[ "occupation1":"engineer", "occupation2":"writer" ] } A blank document is valid in MongoDB. However, rest of the three documents have some or the other problem. Option b has �=�, Option c has �;� and Option d has an incorrect array format. It should be a sub-document instead. Q 5 - Which of the following is correct explanation of MongoDB processes? A - mongod.exe is the shell process and mongo.exe is the actual database process B - mongo.exe is the shell process and mongod.exe is the actual database process C - mongos.exe is the MongoDB server process needed to run database D - mongodump.exe can be used to import database backup dump The core components in the MongoDB package are: mongod, the core database process; mongos the controller and query router for sharded clusters; and mongo the interactive MongoDB Shell. Q 6 - Consider a collection posts which has fields: _id, post_text, post_author, post_timestamp, post_tags etc. Which of the following query retrieves ONLY the key named post_text from the first document retrieved? A - db.posts.find({},{_id:0, post_text:1}) B - db.posts.findOne({post_text:1}) C - db.posts.finOne({},{post_text:1}) D - db.posts.finOne({},{_id:0, post_text:1}) By default, MongoDB returns the _id field with each document. So in case you want ONLY the post_text field, you will have to exclude the _id field explicitly. Also, since we have to retrieve only the first document we have to use findOne and not find. Q 7 - Which of the following is incorrect statement about find and findOne operations in MongoDB? A - find() returns all the documents in a collection while findOne() retrieves only the first one. B - find() and findOne() returns cursors to the collection documents C - findOne() returns the actual first document retrieved from a collection D - find.limit(1) is not the same query as findOne() Both findOne() and find() queries are very much different. The find() method returns the cursor while the findOne() returns the actual document. Hence Option b is incorrect and rest of them are correct. Q 8 - In a collection that contains 100 post documents, what does the following command do? db.posts.find().skip(5).limit(5) A - Skip and limit nullify each other. Hence returning the first five documents. B - Skips the first five documents and returns the sixth document five times C - Skips the first five documents and returns the next five D - Limits the first five documents and then return them in reverse order The skip and limit functions are applies linearly and hence it will first skip documents 1-5, and then return documents 6-10. Q 9 - Which of the following MongoDB query is equivalent to the following SQL query: UPDATE users SET status = "C" WHERE age > 25 A db.users.update( { age: { $gt: 25 } }, { status: "C" }) B db.users.update( { age: { $gt: 25 } }, { $set: { status: "C" } }) C db.users.update( { age: { $gt: 25 } }, { $set: { status: "C" } }, { multi: true }) D db.users.update( { age: { $gt: 25 } }, { status: "C" }, { multi: true }) $set is used to set the value of a particular field in a document. The syntax of set is $set:{column_name : column_value}. Also, {multi:true} is needed to update all the documents. Otherwise only the first found document is updated. Q 10 - The MongoDB explain() method does not support which of the following verbosity mode: A - queryPlanner B - executionStats C - allPlansExecution D - customExecutionStats The possible modes of explain() are: "queryPlanner", "executionStats", and "allPlansExecution". Q 11 - Which is the default mode in which the explain() command runs? A - queryPlanner B - executionStats C - allPlansExecution D - customExecutionStats Default mode is "queryPlanner". Q 12 - Within how much time does MongDB writes are written to the journal? A - 60 s B - 100 ms C - 1 s D - 100 s Writes are physically written to the journal within 100 milliseconds, by default. Q 13 - Which of the following is true about sharding? A - Sharding is enabled at the database level B - Creating a sharded key automatically creates an index on the collection using that key C - We cannot change a shard key directly/automatically once it is set up D - A sharded environment does not support sorting functionality since the documents lie on various mongod instances There is no direct way of changing the sharded key unless you dump the entire data, drop the sharded key and then re-import everything. Other all options are false. Sharding is enabled at collection level, it does not create any index by default and finally sharding environment supports regular sorting. Q 14 - What is the maximum size of a MongoDB document? A - 2 MB B - 16 MB C - 12 MB D - There is no maximum size. It depends on the RAM. The maximum BSON document size is 16 megabytes. The maximum document size helps ensure that a single document cannot use excessive amount of RAM or, during transmission, excessive amount of bandwidth. Q 15 - What is the maximum size of Index Key Limit and Number of Indexes per collection? A - 64 bytes and 1024 indexes B - 12 mega bytes and 64 indexes C - 1024 bytes and 64 indexes D - 1024 bytes and unlimited indexes The total size of an index entry, which can include structural overhead depending on the BSON type, must be less than 1024 bytes. A single collection can have no more than 64 indexes. Q 16 - What is the output of the following program? A - 60 s B - 100 ms C - 1 s D - 100 s In the default configuration, MongoDB writes data to the main data files on disk every 60 seconds. Q 17 - Which of the following commands finds all the documents in the posts collection with post timestamp field as null? A - db.posts.find( { post_timestamp : { $type: 10 } } ) B - db.posts.find( { post_timestamp: { $type: null } } ) C - db.posts.find( { post_timestamp: { $fieldtype: 10 } } ) D - db.posts.find( { post_timestamp: { $fieldtype: null } } ) $type is used for all the operations involving checking the type of a field in MongoDB. 10 represents the BSON value for null. Q 18 - mongoimport command is used to: A - import all the data from one database to another B - import all the data from one collection to another C - imports content from an Extended JSON, CSV, or TSV export created by mongoexport D - import all the MongoDB data from one format to another The mongoimport tool imports content from an Extended JSON, CSV, or TSV export created by mongoexport, or potentially, another third-party export tool. Q 19 - Which of the following command can be used in mongo shell to show all the databases in your MongoDB instance? A - show dbs B - show databases C - show dbs -all D - ls dbs show dbs returns the list of all the databases. Q 20 - Which of the following replica sets vote in the election of a primary replica set? A - Secondary B - Hidden C - Delayed D - All of the above All members of a replica set, unless the value of votes is equal to 0, vote in elections. This includes all delayed, hidden and secondary-only members. Q 21 - Which of the following command can be used to check the size of a collection named posts? A - db.posts.stats() B - db.posts.findStats() C - db.posts.find({stats:1}) D - db.stats({ collection : posts }) To view the statistics for a collection, including the data size, use the db.collection.stats() method from the mongo shell. Q 22 - Which of the following commands can cause the database to be locked? A - Issuing a query B - Inserting data C - Map-reduce D - All of the above All the above commands wither result in a read lock or a write lock or both. Q 23 - By default, the MongoDB cursor in mongo shell is configured to return how many documents? To get the next set of documents, which command is used? A - 20, it B - 200, more C - 50, it D - No limit, none In the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times [1] to print up to the first 20 documents in the results. To get the next set of results, you should use it command which will iterate over the next set of results. Q 24 - Which of the following commands will return all the posts with number of likes greater than 100 and less than 200, both inclusive? A - db.posts.find({ likes : { $gt : 100, $lt : 200 } } ); B - db.posts.find({ likes : { $gte : 100, $lt : 200 } } ); C - db.posts.find({ likes : { $gt : 100 , $lte : 200 } } ); D - db.posts.find({ likes : { $gte : 100 , $lte : 200 } } ); Since 100 and 200 are both inclusive, we need $gte (greater than and equal) and $lte (less than and equal). Q 25 - In our posts collection, which command can be used to find all the posts whose author names begin lie between �A� and �C� in dictionary order? A - db.posts.find( { post_author : { $gte : "A" , $lte : "C" } } ); B - db.posts.find( { post_author : { $gte : "C" , $lte : "A" } } ); C - db.posts.find( { post_author : { $gt : "A" , $lt : "C" } } ); D - This type of search is not supported by MongoDB. $lt and $gt operators are applicable only for numeric values. The $gt, $lt and related operators can be applied for string manipulations too. They work in the same manner as they would work on numeric values. 44 Lectures 3 hours Arnab Chakraborty 54 Lectures 5.5 hours Eduonix Learning Solutions 44 Lectures 4.5 hours Kaushik Roy Chowdhury 40 Lectures 2.5 hours University Code 26 Lectures 8 hours Bassir Jafarzadeh 70 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2841, "s": 2553, "text": "This section presents you various set of Mock Tests related to MongoDB Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself." }, { "code": null, "e": 2881, "s": 2841, "text": "Q 1 - What kind of database MongoDB is?" }, { "code": null, "e": 2900, "s": 2881, "text": "A - Graph Oriented" }, { "code": null, "e": 2923, "s": 2900, "text": "B - Document Oriented " }, { "code": null, "e": 2943, "s": 2923, "text": "C - Key Value Pair " }, { "code": null, "e": 2960, "s": 2943, "text": "D - Column Based" }, { "code": null, "e": 3081, "s": 2960, "text": "MongoDB stores data in JSON structure based documents. These documents in turn contains data in form of key value pairs." }, { "code": null, "e": 3183, "s": 3081, "text": "Q 2 - A collection and a document in MongoDB is equivalent to which of the SQL concepts respectively?" }, { "code": null, "e": 3202, "s": 3183, "text": "A - Table and Row " }, { "code": null, "e": 3224, "s": 3202, "text": "B - Table and Column " }, { "code": null, "e": 3244, "s": 3224, "text": "C - Column and Row " }, { "code": null, "e": 3268, "s": 3244, "text": "D - Database and Table " }, { "code": null, "e": 3365, "s": 3268, "text": "The way SQL databases stores data rows in a table, MonngoDB stores documents inside collections." }, { "code": null, "e": 3420, "s": 3365, "text": "Q 3 - Which of the following is correct about MongoDB?" }, { "code": null, "e": 3472, "s": 3420, "text": "A - MongoDB uses JSON format to represent documents" }, { "code": null, "e": 3511, "s": 3472, "text": "B - MongoDB supports collection joins " }, { "code": null, "e": 3559, "s": 3511, "text": "C - MongoDB supports some of the SQL functions " }, { "code": null, "e": 3599, "s": 3559, "text": "D - MongoDB supports geospatial indexes" }, { "code": null, "e": 3696, "s": 3599, "text": "MongoDB provides specific supports for functionalities related to 2d and 3d geospatial problems." }, { "code": null, "e": 3759, "s": 3696, "text": "Q 4 - Which of the following is a valid MongoDB JSON document:" }, { "code": null, "e": 3762, "s": 3759, "text": "A\n" }, { "code": null, "e": 3765, "s": 3762, "text": "{}" }, { "code": null, "e": 3768, "s": 3765, "text": "B\n" }, { "code": null, "e": 3850, "s": 3768, "text": "{\n\t\"user_id\"=1,\n\t\"user_name\"=\"Joe Sanders\",\n\t\"occupation\"=[\"engineer\",\"writer\"]\n}" }, { "code": null, "e": 3853, "s": 3850, "text": "C\n" }, { "code": null, "e": 3936, "s": 3853, "text": "{\n\t\"user_id\":1;\n\t\"user_name\":\"Joe Sanders\";\n\t\"occupation\":[\"engineer\",\"writer\"]\n} " }, { "code": null, "e": 3939, "s": 3936, "text": "D\n" }, { "code": null, "e": 4057, "s": 3939, "text": "{\n\t\"user_id\":1,\n\t\"user_name\":\"Joe Sanders\",\n\t\"occupation\":[\n\t\t\"occupation1\":\"engineer\",\n\t\t\"occupation2\":\"writer\"\n\t]\n}" }, { "code": null, "e": 4280, "s": 4057, "text": "A blank document is valid in MongoDB. However, rest of the three documents have some or the other problem. Option b has �=�, Option c has �;� and Option d has an incorrect array format. It should be a sub-document instead." }, { "code": null, "e": 4354, "s": 4280, "text": "Q 5 - Which of the following is correct explanation of MongoDB processes?" }, { "code": null, "e": 4435, "s": 4354, "text": "A - mongod.exe is the shell process and mongo.exe is the actual database process" }, { "code": null, "e": 4516, "s": 4435, "text": "B - mongo.exe is the shell process and mongod.exe is the actual database process" }, { "code": null, "e": 4585, "s": 4516, "text": "C - mongos.exe is the MongoDB server process needed to run database " }, { "code": null, "e": 4647, "s": 4585, "text": "D - mongodump.exe can be used to import database backup dump " }, { "code": null, "e": 4832, "s": 4647, "text": "The core components in the MongoDB package are: mongod, the core database process; mongos the controller and query router for sharded clusters; and mongo the interactive MongoDB Shell." }, { "code": null, "e": 5047, "s": 4832, "text": "Q 6 - Consider a collection posts which has fields: _id, post_text, post_author, post_timestamp, post_tags etc. Which of the following query retrieves ONLY the key named post_text from the first document retrieved?" }, { "code": null, "e": 5090, "s": 5047, "text": "A - db.posts.find({},{_id:0, post_text:1})" }, { "code": null, "e": 5126, "s": 5090, "text": "B - db.posts.findOne({post_text:1})" }, { "code": null, "e": 5164, "s": 5126, "text": "C - db.posts.finOne({},{post_text:1})" }, { "code": null, "e": 5209, "s": 5164, "text": "D - db.posts.finOne({},{_id:0, post_text:1})" }, { "code": null, "e": 5461, "s": 5209, "text": "By default, MongoDB returns the _id field with each document. So in case you want ONLY the post_text field, you will have to exclude the _id field explicitly. Also, since we have to retrieve only the first document we have to use findOne and not find." }, { "code": null, "e": 5559, "s": 5461, "text": "Q 7 - Which of the following is incorrect statement about find and findOne operations in MongoDB?" }, { "code": null, "e": 5659, "s": 5559, "text": "A - find() returns all the documents in a collection while findOne() retrieves only the first one. " }, { "code": null, "e": 5728, "s": 5659, "text": "B - find() and findOne() returns cursors to the collection documents" }, { "code": null, "e": 5804, "s": 5728, "text": "C - findOne() returns the actual first document retrieved from a collection" }, { "code": null, "e": 5857, "s": 5804, "text": "D - find.limit(1) is not the same query as findOne()" }, { "code": null, "e": 6060, "s": 5857, "text": "Both findOne() and find() queries are very much different. The find() method returns the cursor while the findOne() returns the actual document. Hence Option b is incorrect and rest of them are correct." }, { "code": null, "e": 6152, "s": 6060, "text": "Q 8 - In a collection that contains 100 post documents, what does the following command do?" }, { "code": null, "e": 6185, "s": 6152, "text": "db.posts.find().skip(5).limit(5)" }, { "code": null, "e": 6266, "s": 6185, "text": "A - Skip and limit nullify each other. Hence returning the first five documents." }, { "code": null, "e": 6343, "s": 6266, "text": "B - Skips the first five documents and returns the sixth document five times" }, { "code": null, "e": 6405, "s": 6343, "text": "C - Skips the first five documents and returns the next five " }, { "code": null, "e": 6479, "s": 6405, "text": "D - Limits the first five documents and then return them in reverse order" }, { "code": null, "e": 6605, "s": 6479, "text": "The skip and limit functions are applies linearly and hence it will first skip documents 1-5, and then return documents 6-10." }, { "code": null, "e": 6690, "s": 6605, "text": "Q 9 - Which of the following MongoDB query is equivalent to the following SQL query:" }, { "code": null, "e": 6735, "s": 6690, "text": "UPDATE users SET status = \"C\" WHERE age > 25" }, { "code": null, "e": 6738, "s": 6735, "text": "A\n" }, { "code": null, "e": 6800, "s": 6738, "text": "db.users.update(\n { age: { $gt: 25 } },\n { status: \"C\" })" }, { "code": null, "e": 6803, "s": 6800, "text": "B\n" }, { "code": null, "e": 6871, "s": 6803, "text": "db.users.update(\n { age: { $gt: 25 } },\n { $set: { status: \"C\" } })" }, { "code": null, "e": 6874, "s": 6871, "text": "C\n" }, { "code": null, "e": 6960, "s": 6874, "text": "db.users.update(\n { age: { $gt: 25 } },\n { $set: { status: \"C\" } },\n { multi: true })" }, { "code": null, "e": 6963, "s": 6960, "text": "D\n" }, { "code": null, "e": 7039, "s": 6963, "text": "db.users.update(\n { age: { $gt: 25 } },\n { status: \"C\" },\n { multi: true })" }, { "code": null, "e": 7272, "s": 7039, "text": "$set is used to set the value of a particular field in a document. The syntax of set is $set:{column_name : column_value}. Also, {multi:true} is needed to update all the documents. Otherwise only the first found document is updated." }, { "code": null, "e": 7364, "s": 7272, "text": "Q 10 - The MongoDB explain() method does not support which of the following verbosity mode:" }, { "code": null, "e": 7381, "s": 7364, "text": "A - queryPlanner" }, { "code": null, "e": 7400, "s": 7381, "text": "B - executionStats" }, { "code": null, "e": 7422, "s": 7400, "text": "C - allPlansExecution" }, { "code": null, "e": 7447, "s": 7422, "text": "D - customExecutionStats" }, { "code": null, "e": 7543, "s": 7447, "text": "The possible modes of explain() are: \"queryPlanner\", \"executionStats\", and \"allPlansExecution\"." }, { "code": null, "e": 7613, "s": 7543, "text": "Q 11 - Which is the default mode in which the explain() command runs?" }, { "code": null, "e": 7630, "s": 7613, "text": "A - queryPlanner" }, { "code": null, "e": 7649, "s": 7630, "text": "B - executionStats" }, { "code": null, "e": 7671, "s": 7649, "text": "C - allPlansExecution" }, { "code": null, "e": 7696, "s": 7671, "text": "D - customExecutionStats" }, { "code": null, "e": 7728, "s": 7696, "text": "Default mode is \"queryPlanner\"." }, { "code": null, "e": 7803, "s": 7728, "text": "Q 12 - Within how much time does MongDB writes are written to the journal?" }, { "code": null, "e": 7812, "s": 7803, "text": "A - 60 s" }, { "code": null, "e": 7823, "s": 7812, "text": "B - 100 ms" }, { "code": null, "e": 7831, "s": 7823, "text": "C - 1 s" }, { "code": null, "e": 7841, "s": 7831, "text": "D - 100 s" }, { "code": null, "e": 7923, "s": 7841, "text": "Writes are physically written to the journal within 100 milliseconds, by default." }, { "code": null, "e": 7977, "s": 7923, "text": "Q 13 - Which of the following is true about sharding?" }, { "code": null, "e": 8023, "s": 7977, "text": "A - Sharding is enabled at the database level" }, { "code": null, "e": 8114, "s": 8023, "text": "B - Creating a sharded key automatically creates an index on the collection using that key" }, { "code": null, "e": 8188, "s": 8114, "text": "C - We cannot change a shard key directly/automatically once it is set up" }, { "code": null, "e": 8305, "s": 8188, "text": "D - A sharded environment does not support sorting functionality since the documents lie on various mongod instances" }, { "code": null, "e": 8610, "s": 8305, "text": "There is no direct way of changing the sharded key unless you dump the entire data, drop the sharded key and then re-import everything. Other all options are false. Sharding is enabled at collection level, it does not create any index by default and finally sharding environment supports regular sorting." }, { "code": null, "e": 8665, "s": 8610, "text": "Q 14 - What is the maximum size of a MongoDB document?" }, { "code": null, "e": 8674, "s": 8665, "text": "A - 2 MB" }, { "code": null, "e": 8684, "s": 8674, "text": "B - 16 MB" }, { "code": null, "e": 8694, "s": 8684, "text": "C - 12 MB" }, { "code": null, "e": 8747, "s": 8694, "text": "D - There is no maximum size. It depends on the RAM." }, { "code": null, "e": 8948, "s": 8747, "text": "The maximum BSON document size is 16 megabytes. The maximum document size helps ensure that a single document cannot use excessive amount of RAM or, during transmission, excessive amount of bandwidth." }, { "code": null, "e": 9037, "s": 8948, "text": "Q 15 - What is the maximum size of Index Key Limit and Number of Indexes per collection?" }, { "code": null, "e": 9067, "s": 9037, "text": "A - 64 bytes and 1024 indexes" }, { "code": null, "e": 9100, "s": 9067, "text": "B - 12 mega bytes and 64 indexes" }, { "code": null, "e": 9130, "s": 9100, "text": "C - 1024 bytes and 64 indexes" }, { "code": null, "e": 9167, "s": 9130, "text": "D - 1024 bytes and unlimited indexes" }, { "code": null, "e": 9351, "s": 9167, "text": "The total size of an index entry, which can include structural overhead depending on the BSON type, must be less than 1024 bytes. A single collection can have no more than 64 indexes." }, { "code": null, "e": 9403, "s": 9351, "text": "Q 16 - What is the output of the following program?" }, { "code": null, "e": 9412, "s": 9403, "text": "A - 60 s" }, { "code": null, "e": 9423, "s": 9412, "text": "B - 100 ms" }, { "code": null, "e": 9432, "s": 9423, "text": "C - 1 s " }, { "code": null, "e": 9442, "s": 9432, "text": "D - 100 s" }, { "code": null, "e": 9541, "s": 9442, "text": "In the default configuration, MongoDB writes data to the main data files on disk every 60 seconds." }, { "code": null, "e": 9663, "s": 9541, "text": "Q 17 - Which of the following commands finds all the documents in the posts collection with post timestamp field as null?" }, { "code": null, "e": 9719, "s": 9663, "text": "A - db.posts.find( { post_timestamp : { $type: 10 } } )" }, { "code": null, "e": 9776, "s": 9719, "text": "B - db.posts.find( { post_timestamp: { $type: null } } )" }, { "code": null, "e": 9836, "s": 9776, "text": "C - db.posts.find( { post_timestamp: { $fieldtype: 10 } } )" }, { "code": null, "e": 9898, "s": 9836, "text": "D - db.posts.find( { post_timestamp: { $fieldtype: null } } )" }, { "code": null, "e": 10025, "s": 9898, "text": "$type is used for all the operations involving checking the type of a field in MongoDB. 10 represents the BSON value for null." }, { "code": null, "e": 10065, "s": 10025, "text": "Q 18 - mongoimport command is used to: " }, { "code": null, "e": 10119, "s": 10065, "text": "A - import all the data from one database to another " }, { "code": null, "e": 10175, "s": 10119, "text": "B - import all the data from one collection to another " }, { "code": null, "e": 10260, "s": 10175, "text": "C - imports content from an Extended JSON, CSV, or TSV export created by mongoexport" }, { "code": null, "e": 10319, "s": 10260, "text": "D - import all the MongoDB data from one format to another" }, { "code": null, "e": 10471, "s": 10319, "text": "The mongoimport tool imports content from an Extended JSON, CSV, or TSV export created by mongoexport, or potentially, another third-party export tool." }, { "code": null, "e": 10588, "s": 10471, "text": "Q 19 - Which of the following command can be used in mongo shell to show all the databases in your MongoDB instance?" }, { "code": null, "e": 10601, "s": 10588, "text": "A - show dbs" }, { "code": null, "e": 10620, "s": 10601, "text": "B - show databases" }, { "code": null, "e": 10638, "s": 10620, "text": "C - show dbs -all" }, { "code": null, "e": 10649, "s": 10638, "text": "D - ls dbs" }, { "code": null, "e": 10697, "s": 10649, "text": "show dbs returns the list of all the databases." }, { "code": null, "e": 10787, "s": 10697, "text": "Q 20 - Which of the following replica sets vote in the election of a primary replica set?" }, { "code": null, "e": 10802, "s": 10787, "text": "A - Secondary " }, { "code": null, "e": 10814, "s": 10802, "text": "B - Hidden " }, { "code": null, "e": 10826, "s": 10814, "text": "C - Delayed" }, { "code": null, "e": 10847, "s": 10826, "text": "D - All of the above" }, { "code": null, "e": 10999, "s": 10847, "text": "All members of a replica set, unless the value of votes is equal to 0, vote in elections. This includes all delayed, hidden and secondary-only members." }, { "code": null, "e": 11096, "s": 10999, "text": "Q 21 - Which of the following command can be used to check the size of a collection named posts?" }, { "code": null, "e": 11117, "s": 11096, "text": "A - db.posts.stats()" }, { "code": null, "e": 11142, "s": 11117, "text": "B - db.posts.findStats()" }, { "code": null, "e": 11171, "s": 11142, "text": "C - db.posts.find({stats:1})" }, { "code": null, "e": 11208, "s": 11171, "text": "D - db.stats({ collection : posts })" }, { "code": null, "e": 11333, "s": 11208, "text": "To view the statistics for a collection, including the data size, use the db.collection.stats() method from the mongo shell." }, { "code": null, "e": 11409, "s": 11333, "text": "Q 22 - Which of the following commands can cause the database to be locked?" }, { "code": null, "e": 11430, "s": 11409, "text": "A - Issuing a query " }, { "code": null, "e": 11450, "s": 11430, "text": "B - Inserting data " }, { "code": null, "e": 11467, "s": 11450, "text": "C - Map-reduce " }, { "code": null, "e": 11488, "s": 11467, "text": "D - All of the above" }, { "code": null, "e": 11565, "s": 11488, "text": "All the above commands wither result in a read lock or a write lock or both." }, { "code": null, "e": 11719, "s": 11565, "text": "Q 23 - By default, the MongoDB cursor in mongo shell is configured to return how many documents? To get the next set of documents, which command is used?" }, { "code": null, "e": 11730, "s": 11719, "text": "A - 20, it" }, { "code": null, "e": 11744, "s": 11730, "text": "B - 200, more" }, { "code": null, "e": 11755, "s": 11744, "text": "C - 50, it" }, { "code": null, "e": 11774, "s": 11755, "text": "D - No limit, none" }, { "code": null, "e": 12092, "s": 11774, "text": "In the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times [1] to print up to the first 20 documents in the results. To get the next set of results, you should use it command which will iterate over the next set of results." }, { "code": null, "e": 12230, "s": 12092, "text": "Q 24 - Which of the following commands will return all the posts with number of likes greater than 100 and less than 200, both inclusive?" }, { "code": null, "e": 12288, "s": 12230, "text": "A - db.posts.find({ likes : { $gt : 100, $lt : 200 } } );" }, { "code": null, "e": 12347, "s": 12288, "text": "B - db.posts.find({ likes : { $gte : 100, $lt : 200 } } );" }, { "code": null, "e": 12407, "s": 12347, "text": "C - db.posts.find({ likes : { $gt : 100 , $lte : 200 } } );" }, { "code": null, "e": 12468, "s": 12407, "text": "D - db.posts.find({ likes : { $gte : 100 , $lte : 200 } } );" }, { "code": null, "e": 12576, "s": 12468, "text": "Since 100 and 200 are both inclusive, we need $gte (greater than and equal) and $lte (less than and equal)." }, { "code": null, "e": 12726, "s": 12576, "text": "Q 25 - In our posts collection, which command can be used to find all the posts whose author names begin lie between �A� and �C� in dictionary order?" }, { "code": null, "e": 12794, "s": 12726, "text": "A - db.posts.find( { post_author : { $gte : \"A\" , $lte : \"C\" } } );" }, { "code": null, "e": 12862, "s": 12794, "text": "B - db.posts.find( { post_author : { $gte : \"C\" , $lte : \"A\" } } );" }, { "code": null, "e": 12928, "s": 12862, "text": "C - db.posts.find( { post_author : { $gt : \"A\" , $lt : \"C\" } } );" }, { "code": null, "e": 13043, "s": 12928, "text": "D - This type of search is not supported by MongoDB. $lt and $gt operators are applicable only for numeric values." }, { "code": null, "e": 13190, "s": 13043, "text": "The $gt, $lt and related operators can be applied for string manipulations too. They work in the same manner as they would work on numeric values." }, { "code": null, "e": 13223, "s": 13190, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 13242, "s": 13223, "text": " Arnab Chakraborty" }, { "code": null, "e": 13277, "s": 13242, "text": "\n 54 Lectures \n 5.5 hours \n" }, { "code": null, "e": 13305, "s": 13277, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13340, "s": 13305, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13363, "s": 13340, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 13398, "s": 13363, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13415, "s": 13398, "text": " University Code" }, { "code": null, "e": 13448, "s": 13415, "text": "\n 26 Lectures \n 8 hours \n" }, { "code": null, "e": 13467, "s": 13448, "text": " Bassir Jafarzadeh" }, { "code": null, "e": 13502, "s": 13467, "text": "\n 70 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13522, "s": 13502, "text": " Skillbakerystudios" }, { "code": null, "e": 13529, "s": 13522, "text": " Print" }, { "code": null, "e": 13540, "s": 13529, "text": " Add Notes" } ]
How does [\d+] regular expression work in Python?
The following code shows what the regular expression [\d+] does on the given string [\d+] regular expression refers to one digit (0-9) or + character import re result = re.findall(r'[\d+]', 'Taran123tula+456') print result ['1', '2', '3', '+', '4', '5', '6']
[ { "code": null, "e": 1146, "s": 1062, "text": "The following code shows what the regular expression [\\d+] does on the given string" }, { "code": null, "e": 1213, "s": 1146, "text": "[\\d+] regular expression refers to one digit (0-9) or + character " }, { "code": null, "e": 1286, "s": 1213, "text": "import re\nresult = re.findall(r'[\\d+]', 'Taran123tula+456')\nprint result" }, { "code": null, "e": 1322, "s": 1286, "text": "['1', '2', '3', '+', '4', '5', '6']" } ]
C++ List Library - remove_if() Function
The C++ function std::list::remove_if() removes elements from the list that fulfills the condition. It removes all elements for which predicate returns true. Following is the declaration for std::list::remove_if() function form std::list header. template <class Predicate> void remove_if (Predicate pred); pred − Unary predicate that, which takes a value of the same type and returns true for those values to be removed from the container. None. If pred is guaranteed to not throw, then function never throws exceptions. Linear i.e. O(n) The following example shows the usage of std::list::remove_if() function. #include <iostream> #include <list> using namespace std; bool foo(int n) { return (n > 5); } int main(void) { list<int> l = {1, 2, 3, 4, 5, 6, 7, 8, 9}; cout << "Contents of list before remove_if operation" << endl; for (auto it = l.begin(); it != l.end(); ++it) cout << *it << endl; /* remove all elements larger than 5 */ l.remove_if(foo); cout << "Contents of list after remove_if operation" << endl; for (auto it = l.begin(); it != l.end(); ++it) cout << *it << endl; return 0; } Let us compile and run the above program, this will produce the following result − Contents of list before remove_if operation 1 2 3 4 5 6 7 8 9 Contents of list after remove_if operation 1 2 3 4 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2761, "s": 2603, "text": "The C++ function std::list::remove_if() removes elements from the list that fulfills the condition. It removes all elements for which predicate returns true." }, { "code": null, "e": 2849, "s": 2761, "text": "Following is the declaration for std::list::remove_if() function form std::list header." }, { "code": null, "e": 2910, "s": 2849, "text": "template <class Predicate>\nvoid remove_if (Predicate pred);\n" }, { "code": null, "e": 3044, "s": 2910, "text": "pred − Unary predicate that, which takes a value of the same type and returns true for those values to be removed from the container." }, { "code": null, "e": 3050, "s": 3044, "text": "None." }, { "code": null, "e": 3125, "s": 3050, "text": "If pred is guaranteed to not throw, then function never throws exceptions." }, { "code": null, "e": 3142, "s": 3125, "text": "Linear i.e. O(n)" }, { "code": null, "e": 3216, "s": 3142, "text": "The following example shows the usage of std::list::remove_if() function." }, { "code": null, "e": 3748, "s": 3216, "text": "#include <iostream>\n#include <list>\n\nusing namespace std;\n\nbool foo(int n) {\n return (n > 5);\n}\n\nint main(void) {\n list<int> l = {1, 2, 3, 4, 5, 6, 7, 8, 9};\n\n cout << \"Contents of list before remove_if operation\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n /* remove all elements larger than 5 */\n l.remove_if(foo);\n\n cout << \"Contents of list after remove_if operation\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}" }, { "code": null, "e": 3831, "s": 3748, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3947, "s": 3831, "text": "Contents of list before remove_if operation\n1\n2\n3\n4\n5\n6\n7\n8\n9\nContents of list after remove_if operation\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 3954, "s": 3947, "text": " Print" }, { "code": null, "e": 3965, "s": 3954, "text": " Add Notes" } ]
Time Series Modeling for Atmospheric CO2 Concentration(ppm), 1958–2019 | by Peyman Kor | Towards Data Science
In this post, I will go through the Time Series Modeling for historical CO2 Concentration (1958–2019) in R. The Seasonal ARIMA modeling will be used to build the model. The source code in the Rmarkdown format could be found in the author’s GitHub link here. Knowing that it has often been stated that the CO2 concentration should be attained below 460 ppm before the start of the second half of this century, specifically, this post seeks to answer this question: If the current trend in Co2 Concentration continues (Business as usual) what is the chance to reach 460 ppm at the beginning of the second half of the century? Ok, Let’s go start! The first things to do is to import the required packages in this analysis (if you have not installed them, install these package in the R beforehand): library(tidyverse)library(forecast)library(lubridate)library(car)library(scales)library(patchwork)library(kableExtra) The data of monthly CO2 Concentration in (ppm) over the period of the “1960/3–2019/12” measured at Mauna Loa Observatory, Hawaii will be used in this analysis. The link for this data is available here: https://www.esrl.noaa.gov/gmd/ccgg/trends/data.html Now, to read this data in the R, couples of points must be considered: The data has the comments, which is not our interest in analysis. Therefore, we show that with *comment.char = ‘#’ *, The data has 7 columns yet some of them like the Year and Month label have not been written in the data, so while importing we assign the following column names (Year, Month, Time, Co2_con, Interpolated, Trend, Days). The columns were separated using the white space, therefore the sep =” ’’ will be added to the code. Since we are including the column names, the header = F could be included. data <- read.delim('ftp://aftp.cmdl.noaa.gov/products/trends/co2/co2_mm_mlo.txt', comment.char = '#', header = F, sep = '', col.names = c('Year','Month','Time','Co2_Concentration','Interpolated','Trend','Days')) Look on any NA values: which(is.na(data))## integer(0) Good, we have the complete measured data! However, when reading the data we see some -99.99 values! — be careful, as was mentioned in the comments these values are when the measurement was not available — so for these points (which are 7 out of 741 measurements), we use the Interpolated column: data_cc <- data %>% mutate( Co2_Con = case_when( Co2_Concentration == -99.99 ~ Interpolated, TRUE ~ Co2_Concentration ) ) Let’s have look on column types: sapply(data_cc, class)## Year Month Time Co2_Concentration ## "integer" "integer" "numeric" "numeric" ## Interpolated Trend Days Co2_Con ## "numeric" "numeric" "integer" "numeric" We can see that column types are in an appropriate format, yet we can add the new column named Date which gives the date of measurement in the standard time-series format. Here Lubridate package provides an easy method to convert our Year and Month column to date: data_cc$Date <- ymd(paste0(data$Year, " ", data$Month, " ", "15")) Also, we can see in the analysis we want to do, we do not need all columns, so we could select the required column needed in our analysis: data_cc_sel <- data_cc %>% select(Year, Month, Date, Co2_Con ) Also, we need to have a portion of our data, to test the model we develop based on the training data- So, Here, we consider the data for 2017, 2018 and 2019 as the test data, the rest is the training data. data_cc_sel_test <- data_cc_sel %>% filter(Year > 2016)data_cc_sel_train <- data_cc_sel %>% filter(Year <= 2016) Now, let’s visualize the data first, ggplot(data_cc_sel,aes(Date, Co2_Con)) + geom_line(color='blue') + xlab("Year, Month") + scale_x_date(date_labels = "%Y-%m", date_breaks = "5 year") + theme(axis.text.x = element_text(face = "bold", color = "#993333", size = 12, angle = 45, hjust = 1)) + ylab("CO2 Concentration (ppm)") + #scale_x_continuous(breaks = trans_breaks(identity, identity, n = 10)) scale_y_continuous() + theme(axis.text.y = element_text(face = "bold", color = "#993333", size = 10, hjust = 1),axis.title.y = element_text(size = 10)) Now, sometimes it is nice as well to plot all Total data set, training, and test next to each other using the “patchwork” package: p1 <- ggplot(data_cc_sel,aes(Date, Co2_Con)) + geom_line(color='blue') + xlab("Year, Month") + scale_x_date(date_labels = "%Y-%m", date_breaks = "5 year") + theme(axis.text.x = element_text(face = "bold", color = "#993333", size = 12, angle = 45, hjust = 1)) + ylab("CO2 Concentration (ppm)") + #scale_x_continuous(breaks = trans_breaks(identity, identity, n = 10)) scale_y_continuous() + theme(axis.text.y = element_text(face = "bold", color = "#993333", size = 10, hjust = 1),axis.title.y = element_text(size = 8))p2 <- ggplot(data_cc_sel_train,aes(Date, Co2_Con)) + geom_line(color='blue') + xlab("Year, Month") + scale_x_date(date_labels = "%Y-%m", date_breaks = "5 year") + theme(axis.text.x = element_text(face = "bold", color = "#993333", size = 12, angle = 45, hjust = 1)) + ylab("CO2 Concentration (ppm)") + #scale_x_continuous(breaks = trans_breaks(identity, identity, n = 10)) scale_y_continuous() + theme(axis.text.y = element_text(face = "bold", color = "#993333", size = 10, hjust = 1), axis.title.y = element_text(size = 8))p3 <- ggplot(data_cc_sel_test,aes(Date, Co2_Con)) + geom_line(color='blue') + xlab("Year, Month") + scale_x_date(date_labels = "%Y-%m", date_breaks = "1 year") + theme(axis.text.x = element_text(face = "bold", color = "#993333", size = 12, angle = 45, hjust = 1)) + ylab("CO2 Concentration (ppm)") + #scale_x_continuous(breaks = trans_breaks(identity, identity, n = 10)) scale_y_continuous() + theme(axis.text.y = element_text(face = "bold", color = "#993333", size = 10, hjust = 1), axis.title.y = element_text(size = 8))(p2 | p3 ) / p1 In time series analysis, the first three things we need to know about the trends are: Is the data stationary? Answer: Not, we see the clear trend in the plot, so the properties of CO2 concentration depend on time (for example the mean of the data is time-dependent, sign of non -stationary). Is there any seasonality in data? Answer: Yes, we can definitely see the seasonality in the data. Now, knowing the non-stationary and seasonality of the data, it suggests using the seasonal differencing to model the data. To answer, How are the Autocorrelation function and Partial Autocorrelation? Here is the plot of ACF and PACF from the forecast package: Co2_train <- ts(data_cc_sel_train$Co2_Con, start = c(1958,3), frequency = 12)Co2_train %>% ggtsdisplay() Clearly, the data shows the need differencing (since ACF is not going down zero), now we make the ordinary differencing of the with the lag of 12: Co2_train %>% diff(lag=12) %>% diff() %>% ggtsdisplay() Now, it is better, we substantially removed the trend. We start the model with the d=D = 1 in the ARIMA(p,d,q)(P,D,Q)[12] (the reason we had differencing both seasonal and non-seasonal part in the above plot.) Now, we must have some starting parameters for p,q,P,Q . So, let’s look at the above ACF and PACF: In the seasonal lags, there is one significant spike in the ACF, suggesting a possible MA(1) term. so, the starting point is Q = 1 In the plots of the non-seasonal differenced data, there are three spikes at ACF plot, this may be suggestive of a seasonal MA(3) term, q=3. Consequently, we start to withe the ARIMA(0,1,3)(3,1,1)[12] and make variations in the AR and MA terms. Here, while keeping the order constant (d,D), we use the AICs values to judge the quality of models. (minimize the AICs) aicsvalue <- function(p,q,P,Q) { fit <- Arima(Co2_train, order=c(p,1,q),seasonal=list(order=c(P,1,Q),period=12), lambda = "auto" ) return(fit$aicc)}model_eva <- data.frame(Model_name=c("ARIMA(0,1,3)(3,1,1)[12]","ARIMA(0,1,1)(3,1,1)[12]","ARIMA(1,1,0)(1,1,0)[12]", "ARIMA(1,1,2)(1,1,0)[12]","ARIMA(1,1,3)(0,1,1)[12]","ARIMA(1,1,1)(1,1,0)[12]", "ARIMA(1,1,1)(1,1,0)[12]","ARIMA(1,1,0)(1,1,1)[12]","ARIMA(1,1,1)(0,1,1)[12]" ), AICc=c(aicsvalue(0,3,3,1),aicsvalue(0,1,3,1),aicsvalue(1,0,1,0), aicsvalue(1,2,1,0),aicsvalue(1,3,0,1),aicsvalue(1,1,1,0), aicsvalue(1,1,1,0),aicsvalue(1,0,1,1), aicsvalue(1,1,0,1))) Based on the above analysis, the ARIMA(1, 1, 1)(0, 1, 1)[12] will be selected, but we need to check the residual to avoid any over and underfitting as well, to see the Ljung-Box test whether the residuals resembles white noise or not. (fit_minaicc <- Arima(Co2_train, order=c(1,1,1),seasonal=list(order=c(0,1,1),period=12), lambda = "auto" ))checkresiduals(fit_minaicc, lag=36)fit_minaicc$aicc ## ## Ljung-Box test## ## data: Residuals from ARIMA(2,0,1)(1,1,1)[12] with drift## Q* = 32.406, df = 30, p-value = 0.3489## ## Model df: 6. Total lags used: 36 Now, we can see the residual sufficiently resembles the white noise also the p-value is high and the model passes the test for Ljong-Box test. (However it must be mentioned the some of the ACF are just reaching the boundary in the blue line, yet, I do not think it will affect the prediction substantially — sometimes it is difficult to have model pass all tests.) However, still, this is not the end of model selection. Here, compare the performance of the model on the Test data. We seek to find the model which minimizes the RMSE. Co2_test <- ts(data_cc_sel_test$Co2_Con, start = c(2017,1), frequency = 12)mm <- accuracy(forecast(fit_minaicc,h=35)$mean, Co2_test ) This section compares the RMSE values for the 9 models provided in the previous section. rmse_eva <- function(p,d,q,P,D,Q) { fit <- Arima(Co2_train, order=c(p,d,q),seasonal=list(order=c(P,D,Q),period=12), lambda = "auto", include.drift = T ) mm <- accuracy(forecast(fit,h=35)$mean, Co2_test) return(mm[2])}rmse_eva <- data.frame(Model_name=c("ARIMA(0,1,3)(3,1,1)[12]","ARIMA(0,1,1)(3,1,1)[12]","ARIMA(1,1,0)(1,1,0)[12]","ARIMA(1,1,2)(1,1,0)[12]","ARIMA(1,1,3)(0,1,1)[12]","ARIMA(1,1,1)(1,1,0)[12]","ARIMA(1,1,1)(1,1,0)[12]","ARIMA(1,1,0)(1,1,1)[12]","ARIMA(1,1,1)(0,1,1)[12]" ), RMSE=c( rmse_eva(0,1,3,3,1,1),rmse_eva(0,1,1,3,1,1),rmse_eva(1,1,0,1,1,0), rmse_eva(1,1,2,1,1,0),rmse_eva(1,1,3,0,1,1),rmse_eva(1,1,1,1,1,0), rmse_eva(1,1,1,1,1,0),rmse_eva(1,1,0,1,1,1),rmse_eva(1,1,1,0,1,1))) The results show that the model ARIMA(1,1,1)(0,1,1)[12] does not has the minimum RMSE value, yet it is very close to the minimum, however, it was minimum in the AICc values. At the end, knowing that the model residuals follow the white noise, the model ARIMA(1,1,1)(0,1,1)[12] is selected to forecast the package due to it’s fewer parameters and simplicity while keeping the minimum AICs. (Note: If the criteria were set to the RMSE, that may lead us very complex model with many parameters) Co2_train %>% Arima(order=c(1,1,1),seasonal=list(order=c(0,1,1),period=12), lambda = "auto" ) %>% forecast(h=400) %>% autoplot() + ylab("H02 sales (million scripts)") + xlab("Year") + autolayer(Co2_test) Let’s zoom in the model prediction and the test data to see the model performance visually: prediction <- forecast(fit_minaicc,h=35) data_cc_sel_test$prediction <- prediction$meandata_test_pre_tidy <- gather(data_cc_sel_test, "type", "Co2", -Year,-Month,-Date)## Warning: attributes are not identical across measure variables;## they will be droppedggplot(data_test_pre_tidy,aes(Date, Co2,color=type)) + geom_line() + xlab("Year, Month") + scale_x_date(date_labels = "%Y-%m", date_breaks = "1 year") + theme(axis.text.x = element_text(face = "bold", color = "#993333", size = 12, angle = 45, hjust = 1)) + ylab("CO2 Concentration (ppm)") + #scale_x_continuous(breaks = trans_breaks(identity, identity, n = 10)) scale_y_continuous() + theme(axis.text.y = element_text(face = "bold", color = "#993333", size = 10, hjust = 1), axis.title.y = element_text(size = 8)) Now, given the developed model the question we want to answer is: Given the developed model, what is the chance of reaching 460 ppm in 2050? To answer this question, we first need to build the cumulative distribution of the CO2 Concentration in 2050 : prediction1 <- forecast(fit_minaicc,h=396, level = c(80,90)) p10 <- prediction1$upper[396,2]p50 <- prediction1$mean[396]sd_calc <- (p10-p50)/1.28Co2_con_2050 <- rnorm(10^6,p50,sd_calc)cdf_co2_con_2050 <- ecdf(Co2_con_2050)cdf_co2_con_2050_data <- data.frame(Co2_con_2050)ggplot(cdf_co2_con_2050_data, aes(Co2_con_2050)) + stat_ecdf(geom = "step", color='blue') + geom_vline(xintercept = 460, color='red') + geom_hline(yintercept = cdf_co2_con_2050(460), color='red') + theme(axis.text.x = element_text(face = "bold", color = "#993333", size = 12, angle = 0, hjust = 1)) + scale_x_continuous(breaks=c(400,425,450, 460,475,500,525, 550), limits = c(425,525)) + scale_y_continuous(breaks=c(seq(0,1,0.1)), limits = c(0,1)) + ylab('Cumulative Distribution') + xlab("Co2 Concentraion(ppm) at 2050")## Warning: Removed 238 rows containing non-finite values (stat_ecdf). Now, having the cumulative distribution, we could ask this question: What is the probability the CO2 concentration (ppm) will stay below 460 level by 2050? cdf_co2_con_2050(460)## [1] 0.089823 As you can see, the answer is around 9%.
[ { "code": null, "e": 635, "s": 171, "text": "In this post, I will go through the Time Series Modeling for historical CO2 Concentration (1958–2019) in R. The Seasonal ARIMA modeling will be used to build the model. The source code in the Rmarkdown format could be found in the author’s GitHub link here. Knowing that it has often been stated that the CO2 concentration should be attained below 460 ppm before the start of the second half of this century, specifically, this post seeks to answer this question:" }, { "code": null, "e": 795, "s": 635, "text": "If the current trend in Co2 Concentration continues (Business as usual) what is the chance to reach 460 ppm at the beginning of the second half of the century?" }, { "code": null, "e": 815, "s": 795, "text": "Ok, Let’s go start!" }, { "code": null, "e": 967, "s": 815, "text": "The first things to do is to import the required packages in this analysis (if you have not installed them, install these package in the R beforehand):" }, { "code": null, "e": 1085, "s": 967, "text": "library(tidyverse)library(forecast)library(lubridate)library(car)library(scales)library(patchwork)library(kableExtra)" }, { "code": null, "e": 1287, "s": 1085, "text": "The data of monthly CO2 Concentration in (ppm) over the period of the “1960/3–2019/12” measured at Mauna Loa Observatory, Hawaii will be used in this analysis. The link for this data is available here:" }, { "code": null, "e": 1339, "s": 1287, "text": "https://www.esrl.noaa.gov/gmd/ccgg/trends/data.html" }, { "code": null, "e": 1410, "s": 1339, "text": "Now, to read this data in the R, couples of points must be considered:" }, { "code": null, "e": 1528, "s": 1410, "text": "The data has the comments, which is not our interest in analysis. Therefore, we show that with *comment.char = ‘#’ *," }, { "code": null, "e": 1746, "s": 1528, "text": "The data has 7 columns yet some of them like the Year and Month label have not been written in the data, so while importing we assign the following column names (Year, Month, Time, Co2_con, Interpolated, Trend, Days)." }, { "code": null, "e": 1847, "s": 1746, "text": "The columns were separated using the white space, therefore the sep =” ’’ will be added to the code." }, { "code": null, "e": 1922, "s": 1847, "text": "Since we are including the column names, the header = F could be included." }, { "code": null, "e": 2134, "s": 1922, "text": "data <- read.delim('ftp://aftp.cmdl.noaa.gov/products/trends/co2/co2_mm_mlo.txt', comment.char = '#', header = F, sep = '', col.names = c('Year','Month','Time','Co2_Concentration','Interpolated','Trend','Days'))" }, { "code": null, "e": 2157, "s": 2134, "text": "Look on any NA values:" }, { "code": null, "e": 2189, "s": 2157, "text": "which(is.na(data))## integer(0)" }, { "code": null, "e": 2485, "s": 2189, "text": "Good, we have the complete measured data! However, when reading the data we see some -99.99 values! — be careful, as was mentioned in the comments these values are when the measurement was not available — so for these points (which are 7 out of 741 measurements), we use the Interpolated column:" }, { "code": null, "e": 2650, "s": 2485, "text": "data_cc <- data %>% mutate( Co2_Con = case_when( Co2_Concentration == -99.99 ~ Interpolated, TRUE ~ Co2_Concentration ) )" }, { "code": null, "e": 2683, "s": 2650, "text": "Let’s have look on column types:" }, { "code": null, "e": 3005, "s": 2683, "text": "sapply(data_cc, class)## Year Month Time Co2_Concentration ## \"integer\" \"integer\" \"numeric\" \"numeric\" ## Interpolated Trend Days Co2_Con ## \"numeric\" \"numeric\" \"integer\" \"numeric\"" }, { "code": null, "e": 3177, "s": 3005, "text": "We can see that column types are in an appropriate format, yet we can add the new column named Date which gives the date of measurement in the standard time-series format." }, { "code": null, "e": 3270, "s": 3177, "text": "Here Lubridate package provides an easy method to convert our Year and Month column to date:" }, { "code": null, "e": 3337, "s": 3270, "text": "data_cc$Date <- ymd(paste0(data$Year, \" \", data$Month, \" \", \"15\"))" }, { "code": null, "e": 3476, "s": 3337, "text": "Also, we can see in the analysis we want to do, we do not need all columns, so we could select the required column needed in our analysis:" }, { "code": null, "e": 3543, "s": 3476, "text": "data_cc_sel <- data_cc %>% select(Year, Month, Date, Co2_Con )" }, { "code": null, "e": 3749, "s": 3543, "text": "Also, we need to have a portion of our data, to test the model we develop based on the training data- So, Here, we consider the data for 2017, 2018 and 2019 as the test data, the rest is the training data." }, { "code": null, "e": 3870, "s": 3749, "text": "data_cc_sel_test <- data_cc_sel %>% filter(Year > 2016)data_cc_sel_train <- data_cc_sel %>% filter(Year <= 2016)" }, { "code": null, "e": 3907, "s": 3870, "text": "Now, let’s visualize the data first," }, { "code": null, "e": 4497, "s": 3907, "text": "ggplot(data_cc_sel,aes(Date, Co2_Con)) + geom_line(color='blue') + xlab(\"Year, Month\") + scale_x_date(date_labels = \"%Y-%m\", date_breaks = \"5 year\") + theme(axis.text.x = element_text(face = \"bold\", color = \"#993333\", size = 12, angle = 45, hjust = 1)) + ylab(\"CO2 Concentration (ppm)\") + #scale_x_continuous(breaks = trans_breaks(identity, identity, n = 10)) scale_y_continuous() + theme(axis.text.y = element_text(face = \"bold\", color = \"#993333\", size = 10, hjust = 1),axis.title.y = element_text(size = 10))" }, { "code": null, "e": 4628, "s": 4497, "text": "Now, sometimes it is nice as well to plot all Total data set, training, and test next to each other using the “patchwork” package:" }, { "code": null, "e": 6444, "s": 4628, "text": "p1 <- ggplot(data_cc_sel,aes(Date, Co2_Con)) + geom_line(color='blue') + xlab(\"Year, Month\") + scale_x_date(date_labels = \"%Y-%m\", date_breaks = \"5 year\") + theme(axis.text.x = element_text(face = \"bold\", color = \"#993333\", size = 12, angle = 45, hjust = 1)) + ylab(\"CO2 Concentration (ppm)\") + #scale_x_continuous(breaks = trans_breaks(identity, identity, n = 10)) scale_y_continuous() + theme(axis.text.y = element_text(face = \"bold\", color = \"#993333\", size = 10, hjust = 1),axis.title.y = element_text(size = 8))p2 <- ggplot(data_cc_sel_train,aes(Date, Co2_Con)) + geom_line(color='blue') + xlab(\"Year, Month\") + scale_x_date(date_labels = \"%Y-%m\", date_breaks = \"5 year\") + theme(axis.text.x = element_text(face = \"bold\", color = \"#993333\", size = 12, angle = 45, hjust = 1)) + ylab(\"CO2 Concentration (ppm)\") + #scale_x_continuous(breaks = trans_breaks(identity, identity, n = 10)) scale_y_continuous() + theme(axis.text.y = element_text(face = \"bold\", color = \"#993333\", size = 10, hjust = 1), axis.title.y = element_text(size = 8))p3 <- ggplot(data_cc_sel_test,aes(Date, Co2_Con)) + geom_line(color='blue') + xlab(\"Year, Month\") + scale_x_date(date_labels = \"%Y-%m\", date_breaks = \"1 year\") + theme(axis.text.x = element_text(face = \"bold\", color = \"#993333\", size = 12, angle = 45, hjust = 1)) + ylab(\"CO2 Concentration (ppm)\") + #scale_x_continuous(breaks = trans_breaks(identity, identity, n = 10)) scale_y_continuous() + theme(axis.text.y = element_text(face = \"bold\", color = \"#993333\", size = 10, hjust = 1), axis.title.y = element_text(size = 8))(p2 | p3 ) / p1" }, { "code": null, "e": 6530, "s": 6444, "text": "In time series analysis, the first three things we need to know about the trends are:" }, { "code": null, "e": 6554, "s": 6530, "text": "Is the data stationary?" }, { "code": null, "e": 6736, "s": 6554, "text": "Answer: Not, we see the clear trend in the plot, so the properties of CO2 concentration depend on time (for example the mean of the data is time-dependent, sign of non -stationary)." }, { "code": null, "e": 6770, "s": 6736, "text": "Is there any seasonality in data?" }, { "code": null, "e": 6969, "s": 6770, "text": "Answer: Yes, we can definitely see the seasonality in the data. Now, knowing the non-stationary and seasonality of the data, it suggests using the seasonal differencing to model the data. To answer," }, { "code": null, "e": 7035, "s": 6969, "text": "How are the Autocorrelation function and Partial Autocorrelation?" }, { "code": null, "e": 7095, "s": 7035, "text": "Here is the plot of ACF and PACF from the forecast package:" }, { "code": null, "e": 7200, "s": 7095, "text": "Co2_train <- ts(data_cc_sel_train$Co2_Con, start = c(1958,3), frequency = 12)Co2_train %>% ggtsdisplay()" }, { "code": null, "e": 7347, "s": 7200, "text": "Clearly, the data shows the need differencing (since ACF is not going down zero), now we make the ordinary differencing of the with the lag of 12:" }, { "code": null, "e": 7403, "s": 7347, "text": "Co2_train %>% diff(lag=12) %>% diff() %>% ggtsdisplay()" }, { "code": null, "e": 7613, "s": 7403, "text": "Now, it is better, we substantially removed the trend. We start the model with the d=D = 1 in the ARIMA(p,d,q)(P,D,Q)[12] (the reason we had differencing both seasonal and non-seasonal part in the above plot.)" }, { "code": null, "e": 7712, "s": 7613, "text": "Now, we must have some starting parameters for p,q,P,Q . So, let’s look at the above ACF and PACF:" }, { "code": null, "e": 7843, "s": 7712, "text": "In the seasonal lags, there is one significant spike in the ACF, suggesting a possible MA(1) term. so, the starting point is Q = 1" }, { "code": null, "e": 7984, "s": 7843, "text": "In the plots of the non-seasonal differenced data, there are three spikes at ACF plot, this may be suggestive of a seasonal MA(3) term, q=3." }, { "code": null, "e": 8209, "s": 7984, "text": "Consequently, we start to withe the ARIMA(0,1,3)(3,1,1)[12] and make variations in the AR and MA terms. Here, while keeping the order constant (d,D), we use the AICs values to judge the quality of models. (minimize the AICs)" }, { "code": null, "e": 9037, "s": 8209, "text": "aicsvalue <- function(p,q,P,Q) { fit <- Arima(Co2_train, order=c(p,1,q),seasonal=list(order=c(P,1,Q),period=12), lambda = \"auto\" ) return(fit$aicc)}model_eva <- data.frame(Model_name=c(\"ARIMA(0,1,3)(3,1,1)[12]\",\"ARIMA(0,1,1)(3,1,1)[12]\",\"ARIMA(1,1,0)(1,1,0)[12]\", \"ARIMA(1,1,2)(1,1,0)[12]\",\"ARIMA(1,1,3)(0,1,1)[12]\",\"ARIMA(1,1,1)(1,1,0)[12]\", \"ARIMA(1,1,1)(1,1,0)[12]\",\"ARIMA(1,1,0)(1,1,1)[12]\",\"ARIMA(1,1,1)(0,1,1)[12]\" ), AICc=c(aicsvalue(0,3,3,1),aicsvalue(0,1,3,1),aicsvalue(1,0,1,0), aicsvalue(1,2,1,0),aicsvalue(1,3,0,1),aicsvalue(1,1,1,0), aicsvalue(1,1,1,0),aicsvalue(1,0,1,1), aicsvalue(1,1,0,1)))" }, { "code": null, "e": 9272, "s": 9037, "text": "Based on the above analysis, the ARIMA(1, 1, 1)(0, 1, 1)[12] will be selected, but we need to check the residual to avoid any over and underfitting as well, to see the Ljung-Box test whether the residuals resembles white noise or not." }, { "code": null, "e": 9461, "s": 9272, "text": "(fit_minaicc <- Arima(Co2_train, order=c(1,1,1),seasonal=list(order=c(0,1,1),period=12), lambda = \"auto\" ))checkresiduals(fit_minaicc, lag=36)fit_minaicc$aicc" }, { "code": null, "e": 9626, "s": 9461, "text": "## ## Ljung-Box test## ## data: Residuals from ARIMA(2,0,1)(1,1,1)[12] with drift## Q* = 32.406, df = 30, p-value = 0.3489## ## Model df: 6. Total lags used: 36" }, { "code": null, "e": 9991, "s": 9626, "text": "Now, we can see the residual sufficiently resembles the white noise also the p-value is high and the model passes the test for Ljong-Box test. (However it must be mentioned the some of the ACF are just reaching the boundary in the blue line, yet, I do not think it will affect the prediction substantially — sometimes it is difficult to have model pass all tests.)" }, { "code": null, "e": 10160, "s": 9991, "text": "However, still, this is not the end of model selection. Here, compare the performance of the model on the Test data. We seek to find the model which minimizes the RMSE." }, { "code": null, "e": 10294, "s": 10160, "text": "Co2_test <- ts(data_cc_sel_test$Co2_Con, start = c(2017,1), frequency = 12)mm <- accuracy(forecast(fit_minaicc,h=35)$mean, Co2_test )" }, { "code": null, "e": 10383, "s": 10294, "text": "This section compares the RMSE values for the 9 models provided in the previous section." }, { "code": null, "e": 11237, "s": 10383, "text": "rmse_eva <- function(p,d,q,P,D,Q) { fit <- Arima(Co2_train, order=c(p,d,q),seasonal=list(order=c(P,D,Q),period=12), lambda = \"auto\", include.drift = T ) mm <- accuracy(forecast(fit,h=35)$mean, Co2_test) return(mm[2])}rmse_eva <- data.frame(Model_name=c(\"ARIMA(0,1,3)(3,1,1)[12]\",\"ARIMA(0,1,1)(3,1,1)[12]\",\"ARIMA(1,1,0)(1,1,0)[12]\",\"ARIMA(1,1,2)(1,1,0)[12]\",\"ARIMA(1,1,3)(0,1,1)[12]\",\"ARIMA(1,1,1)(1,1,0)[12]\",\"ARIMA(1,1,1)(1,1,0)[12]\",\"ARIMA(1,1,0)(1,1,1)[12]\",\"ARIMA(1,1,1)(0,1,1)[12]\" ), RMSE=c( rmse_eva(0,1,3,3,1,1),rmse_eva(0,1,1,3,1,1),rmse_eva(1,1,0,1,1,0), rmse_eva(1,1,2,1,1,0),rmse_eva(1,1,3,0,1,1),rmse_eva(1,1,1,1,1,0), rmse_eva(1,1,1,1,1,0),rmse_eva(1,1,0,1,1,1),rmse_eva(1,1,1,0,1,1)))" }, { "code": null, "e": 11729, "s": 11237, "text": "The results show that the model ARIMA(1,1,1)(0,1,1)[12] does not has the minimum RMSE value, yet it is very close to the minimum, however, it was minimum in the AICc values. At the end, knowing that the model residuals follow the white noise, the model ARIMA(1,1,1)(0,1,1)[12] is selected to forecast the package due to it’s fewer parameters and simplicity while keeping the minimum AICs. (Note: If the criteria were set to the RMSE, that may lead us very complex model with many parameters)" }, { "code": null, "e": 11968, "s": 11729, "text": "Co2_train %>% Arima(order=c(1,1,1),seasonal=list(order=c(0,1,1),period=12), lambda = \"auto\" ) %>% forecast(h=400) %>% autoplot() + ylab(\"H02 sales (million scripts)\") + xlab(\"Year\") + autolayer(Co2_test)" }, { "code": null, "e": 12060, "s": 11968, "text": "Let’s zoom in the model prediction and the test data to see the model performance visually:" }, { "code": null, "e": 12909, "s": 12060, "text": "prediction <- forecast(fit_minaicc,h=35) data_cc_sel_test$prediction <- prediction$meandata_test_pre_tidy <- gather(data_cc_sel_test, \"type\", \"Co2\", -Year,-Month,-Date)## Warning: attributes are not identical across measure variables;## they will be droppedggplot(data_test_pre_tidy,aes(Date, Co2,color=type)) + geom_line() + xlab(\"Year, Month\") + scale_x_date(date_labels = \"%Y-%m\", date_breaks = \"1 year\") + theme(axis.text.x = element_text(face = \"bold\", color = \"#993333\", size = 12, angle = 45, hjust = 1)) + ylab(\"CO2 Concentration (ppm)\") + #scale_x_continuous(breaks = trans_breaks(identity, identity, n = 10)) scale_y_continuous() + theme(axis.text.y = element_text(face = \"bold\", color = \"#993333\", size = 10, hjust = 1), axis.title.y = element_text(size = 8))" }, { "code": null, "e": 12975, "s": 12909, "text": "Now, given the developed model the question we want to answer is:" }, { "code": null, "e": 13161, "s": 12975, "text": "Given the developed model, what is the chance of reaching 460 ppm in 2050? To answer this question, we first need to build the cumulative distribution of the CO2 Concentration in 2050 :" }, { "code": null, "e": 14058, "s": 13161, "text": "prediction1 <- forecast(fit_minaicc,h=396, level = c(80,90)) p10 <- prediction1$upper[396,2]p50 <- prediction1$mean[396]sd_calc <- (p10-p50)/1.28Co2_con_2050 <- rnorm(10^6,p50,sd_calc)cdf_co2_con_2050 <- ecdf(Co2_con_2050)cdf_co2_con_2050_data <- data.frame(Co2_con_2050)ggplot(cdf_co2_con_2050_data, aes(Co2_con_2050)) + stat_ecdf(geom = \"step\", color='blue') + geom_vline(xintercept = 460, color='red') + geom_hline(yintercept = cdf_co2_con_2050(460), color='red') + theme(axis.text.x = element_text(face = \"bold\", color = \"#993333\", size = 12, angle = 0, hjust = 1)) + scale_x_continuous(breaks=c(400,425,450, 460,475,500,525, 550), limits = c(425,525)) + scale_y_continuous(breaks=c(seq(0,1,0.1)), limits = c(0,1)) + ylab('Cumulative Distribution') + xlab(\"Co2 Concentraion(ppm) at 2050\")## Warning: Removed 238 rows containing non-finite values (stat_ecdf)." }, { "code": null, "e": 14127, "s": 14058, "text": "Now, having the cumulative distribution, we could ask this question:" }, { "code": null, "e": 14214, "s": 14127, "text": "What is the probability the CO2 concentration (ppm) will stay below 460 level by 2050?" }, { "code": null, "e": 14251, "s": 14214, "text": "cdf_co2_con_2050(460)## [1] 0.089823" } ]
What are the rules to declare variables in C++?
To declare a variable, you need to know what data type it is going to be of and what its name would be. The variable name has constraints on what you can name it. Following are the rules for naming variables − Variable names in C++ can range from 1 to 255 characters. All variable names must begin with a letter of the alphabet or an underscore(_). After the first initial letter, variable names can also contain letters and numbers. Variable names are case sensitive. No spaces or special characters are allowed. You cannot use a C++ keyword (a reserved word) as a variable name. Here are some examples of acceptable variable names − mohd Piyush abc move_name a_123 myname50 _temp j a23b9 retVal You can declare variables using the syntax − datatype variable_name; For example, int my_var; float my_float; ...
[ { "code": null, "e": 1272, "s": 1062, "text": "To declare a variable, you need to know what data type it is going to be of and what its name would be. The variable name has constraints on what you can name it. Following are the rules for naming variables −" }, { "code": null, "e": 1331, "s": 1272, "text": " Variable names in C++ can range from 1 to 255 characters." }, { "code": null, "e": 1413, "s": 1331, "text": " All variable names must begin with a letter of the alphabet or an underscore(_)." }, { "code": null, "e": 1501, "s": 1413, "text": " After the first initial letter, variable names can also contain letters and numbers. " }, { "code": null, "e": 1537, "s": 1501, "text": " Variable names are case sensitive." }, { "code": null, "e": 1583, "s": 1537, "text": " No spaces or special characters are allowed." }, { "code": null, "e": 1651, "s": 1583, "text": " You cannot use a C++ keyword (a reserved word) as a variable name." }, { "code": null, "e": 1705, "s": 1651, "text": "Here are some examples of acceptable variable names −" }, { "code": null, "e": 1798, "s": 1705, "text": "mohd Piyush abc move_name a_123\nmyname50 _temp j a23b9 retVal" }, { "code": null, "e": 1843, "s": 1798, "text": "You can declare variables using the syntax −" }, { "code": null, "e": 1867, "s": 1843, "text": "datatype variable_name;" }, { "code": null, "e": 1880, "s": 1867, "text": "For example," }, { "code": null, "e": 1912, "s": 1880, "text": "int my_var;\nfloat my_float;\n..." } ]
How to Install PHP 7 on Ubuntu Linux 14.04 LTS
PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. Originally created by Rasmus Lerdorf in 1994, the PHP reference implementation is now produced by The PHP Group. The latest version PHP is PHP7 and it provides 2x faster performance and 50% better memory consumption than PHP version 5.6. This article explains “How to install PHP7 on Ubuntu Linux”. Before installing PHP7, you should need to install a PPA called ondrej/php. This allows you to co-install PHP versions 5.6 and 7.0. To configure a PPA, use the following command – $ sudo add-apt-repository ppa:ondrej/php The sample output should be like this – Co-installable PHP versions: PHP 5.6, PHP 7.0 and batteries included. You can get more information about the packages at https://deb.sury.org For PHP 5.6 use: ppa:ondrej/php5-5.6 For PHP 5.5 use: ppa:ondrej/php5 For PHP 5.4 use: ppa:ondrej/php5-oldstable BUGS & FEATURES: This PPA now has a issue tracker: https://deb.sury.org/pages/bugreporting.html PLEASE READ: If you like my work and want to give me a little motivation, please consider donating: https://deb.sury.org/pages/donate.html WARNING: add-apt-repository is broken with non-UTF-8 locales, see https://github.com/oerdnj/deb.sury.org/issues/56 for workaround: # LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php ............................. To update the package index, use the following command – $ sudo apt-get update The sample output should be like this – Ign http://dl.google.com stable InRelease Get:1 http://security.ubuntu.com trusty-security InRelease [65.9 kB] Ign http://extras.ubuntu.com trusty InRelease Hit http://ppa.launchpad.net trusty InRelease Ign http://in.archive.ubuntu.com trusty InRelease Get:2 http://extras.ubuntu.com trusty Release.gpg [72 B] Hit http://dl.google.com stable Release.gpg Hit http://ppa.launchpad.net trusty InRelease Hit http://dl.google.com stable Release Hit http://extras.ubuntu.com trusty Release Get:3 http://in.archive.ubuntu.com trusty-updates InRelease [65.9 kB] Hit http://dl.google.com stable/main amd64 Packages Get:4 http://ppa.launchpad.net trusty InRelease [20.9 kB] Hit http://extras.ubuntu.com trusty/main Sources Get:5 http://security.ubuntu.com trusty-security/main Sources [106 kB] Hit http://extras.ubuntu.com trusty/main amd64 Packages Hit http://extras.ubuntu.com trusty/main i386 Packages .................................. For listing all PHP packages, use the following command – $sudo apt-cache search php7 The sample output should be like this – php7.0-common - documentation, examples and common module for PHP libapache2-mod-php7.0 - server-side, HTML-embedded scripting language (Apache 2 module) php7.0-cgi - server-side, HTML-embedded scripting language (CGI binary) php7.0-cli - command-line interpreter for the PHP scripting language php7.0-phpdbg - server-side, HTML-embedded scripting language (PHPDBG binary) php7.0-fpm - server-side, HTML-embedded scripting language (FPM-CGI binary) libphp7.0-embed - HTML-embedded scripting language (Embedded SAPI library) php7.0-dev - Files for PHP7.0 module development php7.0-curl - CURL module for PHP php7.0-enchant - Enchant module for PHP php7.0-gd - GD module for PHP php7.0-gmp - GMP module for PHP php7.0-imap - IMAP module for PHP php7.0-interbase - Interbase module for PHP php7.0-intl - Internationalisation module for PHP php7.0-ldap - LDAP module for PHP php7.0-mcrypt - libmcrypt module for PHP php7.0-readline - readline module for PHP php7.0-odbc - ODBC module for PHP php7.0-pgsql - PostgreSQL module for PHP php7.0-pspell - pspell module for PHP php7.0-recode - recode module for PHP php7.0-snmp - SNMP module for PHP php7.0-tidy - tidy module for PHP php7.0-xmlrpc - XMLRPC-EPI module for PHP php7.0-xsl - XSL module for PHP (dummy) php7.0 - server-side, HTML-embedded scripting language (metapackage) php7.0-json - JSON module for PHP php-all-dev - package depending on all supported PHP development packages php7.0-sybase - Sybase module for PHP php7.0-sqlite3 - SQLite3 module for PHP php7.0-mysql - MySQL module for PHP php7.0-opcache - Zend OpCache module for PHP php7.0-bz2 - bzip2 module for PHP php7.0-bcmath - Bcmath module for PHP php7.0-mbstring - MBSTRING module for PHP php7.0-soap - SOAP module for PHP php7.0-xml - DOM, SimpleXML, WDDX, XML, and XSL module for PHP php7.0-zip - Zip module for PHP To install PHP7, use the following command – $ sudo apt-get install php7.0 The sample output should be like this – Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: libapache2-mod-php5 linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic Use 'apt-get autoremove' to remove them. The following extra packages will be installed: libssl1.0.2 php-common php7.0-cli php7.0-common php7.0-fpm php7.0-json php7.0-opcache php7.0-readline Suggested packages: php-pear The following packages will be REMOVED: php5 php5-cli php5-readline The following NEW packages will be installed: libssl1.0.2 php-common php7.0 php7.0-cli php7.0-common php7.0-fpm php7.0-json php7.0-opcache php7.0-readline 0 upgraded, 9 newly installed, 3 to remove and 3 not upgraded. Need to get 4,383 kB of archives. After this operation, 8,056 kB of additional disk space will be used. Do you want to continue? [Y/n] y ................................ To configure Nginx and PHP 7, use the following command – $ sudo vi nginx.conf Append the code as follows- # Pass all .php files onto a php-fpm/php-fcgi server. location ~ [^/]\.php(/|$) { fastcgi_split_path_info ^(.+?\.php)(/.*)$; if (!-f $document_root$fastcgi_script_name) { return 404; } fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass unix:/run/php/php7.0-fpm.sock; fastcgi_index index.php; include fastcgi_params; } Save and close the file, To reload the nginx server, use the following command – $ sudo service nginx reload The sample output should be like this – * Reloading nginx configuration nginx [ OK ] Before reload nginx.you should verify nginx installed or not in your linux system. if not, then install as follows- $ sudo apt-get install -y nginx The sample output should be like this – Reading state information... Done The following packages were automatically installed and are no longer required: libapache2-mod-php5 linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic Use 'apt-get autoremove' to remove them. The following extra packages will be installed: nginx-common nginx-core Suggested packages: fcgiwrap nginx-doc The following NEW packages will be installed: nginx nginx-common nginx-core 0 upgraded, 3 newly installed, 0 to remove and 3 not upgraded. Need to get 349 kB of archives. After this operation, 1,297 kB of additional disk space will be used. Get:1 http://in.archive.ubuntu.com/ubuntu/ trusty-updates/main nginx-common all ............................. If nginx is already installed in Linux then reload nginx using the above command. To test new PHP 7 installation creates a file called test.php in /var/www/html/ directory. test.php should be like this – <?php phpinfo(); ?> Save and close the file. Run it as follows – http://localhost/test.php Congratulations! Now, you know “How to install PHP 7 on Ubuntu Linux 14.04 LTS”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1487, "s": 1062, "text": "PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. Originally created by Rasmus Lerdorf in 1994, the PHP reference implementation is now produced by The PHP Group. The latest version PHP is PHP7 and it provides 2x faster performance and 50% better memory consumption than PHP version 5.6. This article explains “How to install PHP7 on Ubuntu Linux”." }, { "code": null, "e": 1619, "s": 1487, "text": "Before installing PHP7, you should need to install a PPA called ondrej/php. This allows you to co-install PHP versions 5.6 and 7.0." }, { "code": null, "e": 1667, "s": 1619, "text": "To configure a PPA, use the following command –" }, { "code": null, "e": 1708, "s": 1667, "text": "$ sudo add-apt-repository ppa:ondrej/php" }, { "code": null, "e": 1748, "s": 1708, "text": "The sample output should be like this –" }, { "code": null, "e": 2456, "s": 1748, "text": "Co-installable PHP versions: PHP 5.6, PHP 7.0 and batteries included.\n\nYou can get more information about the packages at https://deb.sury.org\n\nFor PHP 5.6 use: ppa:ondrej/php5-5.6\nFor PHP 5.5 use: ppa:ondrej/php5\nFor PHP 5.4 use: ppa:ondrej/php5-oldstable\n\nBUGS & FEATURES: This PPA now has a issue tracker: https://deb.sury.org/pages/bugreporting.html\n\nPLEASE READ: If you like my work and want to give me a little motivation, please consider donating: https://deb.sury.org/pages/donate.html\n\nWARNING: add-apt-repository is broken with non-UTF-8 locales, see https://github.com/oerdnj/deb.sury.org/issues/56 for workaround:\n\n# LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php\n............................." }, { "code": null, "e": 2513, "s": 2456, "text": "To update the package index, use the following command –" }, { "code": null, "e": 2535, "s": 2513, "text": "$ sudo apt-get update" }, { "code": null, "e": 2575, "s": 2535, "text": "The sample output should be like this –" }, { "code": null, "e": 3505, "s": 2575, "text": "Ign http://dl.google.com stable InRelease\nGet:1 http://security.ubuntu.com trusty-security InRelease [65.9 kB]\nIgn http://extras.ubuntu.com trusty InRelease\nHit http://ppa.launchpad.net trusty InRelease\nIgn http://in.archive.ubuntu.com trusty InRelease\nGet:2 http://extras.ubuntu.com trusty Release.gpg [72 B]\nHit http://dl.google.com stable Release.gpg\nHit http://ppa.launchpad.net trusty InRelease\nHit http://dl.google.com stable Release\nHit http://extras.ubuntu.com trusty Release\nGet:3 http://in.archive.ubuntu.com trusty-updates InRelease [65.9 kB]\nHit http://dl.google.com stable/main amd64 Packages\nGet:4 http://ppa.launchpad.net trusty InRelease [20.9 kB]\nHit http://extras.ubuntu.com trusty/main Sources\nGet:5 http://security.ubuntu.com trusty-security/main Sources [106 kB]\nHit http://extras.ubuntu.com trusty/main amd64 Packages\nHit http://extras.ubuntu.com trusty/main i386 Packages\n.................................." }, { "code": null, "e": 3563, "s": 3505, "text": "For listing all PHP packages, use the following command –" }, { "code": null, "e": 3591, "s": 3563, "text": "$sudo apt-cache search php7" }, { "code": null, "e": 3631, "s": 3591, "text": "The sample output should be like this –" }, { "code": null, "e": 5465, "s": 3631, "text": "php7.0-common - documentation, examples and common module for PHP\nlibapache2-mod-php7.0 - server-side, HTML-embedded scripting language (Apache 2 module)\nphp7.0-cgi - server-side, HTML-embedded scripting language (CGI binary)\nphp7.0-cli - command-line interpreter for the PHP scripting language\nphp7.0-phpdbg - server-side, HTML-embedded scripting language (PHPDBG binary)\nphp7.0-fpm - server-side, HTML-embedded scripting language (FPM-CGI binary)\nlibphp7.0-embed - HTML-embedded scripting language (Embedded SAPI library)\nphp7.0-dev - Files for PHP7.0 module development\nphp7.0-curl - CURL module for PHP\nphp7.0-enchant - Enchant module for PHP\nphp7.0-gd - GD module for PHP\nphp7.0-gmp - GMP module for PHP\nphp7.0-imap - IMAP module for PHP\nphp7.0-interbase - Interbase module for PHP\nphp7.0-intl - Internationalisation module for PHP\nphp7.0-ldap - LDAP module for PHP\nphp7.0-mcrypt - libmcrypt module for PHP\nphp7.0-readline - readline module for PHP\nphp7.0-odbc - ODBC module for PHP\nphp7.0-pgsql - PostgreSQL module for PHP\nphp7.0-pspell - pspell module for PHP\nphp7.0-recode - recode module for PHP\nphp7.0-snmp - SNMP module for PHP\nphp7.0-tidy - tidy module for PHP\nphp7.0-xmlrpc - XMLRPC-EPI module for PHP\nphp7.0-xsl - XSL module for PHP (dummy)\nphp7.0 - server-side, HTML-embedded scripting language (metapackage)\nphp7.0-json - JSON module for PHP\nphp-all-dev - package depending on all supported PHP development packages\nphp7.0-sybase - Sybase module for PHP\nphp7.0-sqlite3 - SQLite3 module for PHP\nphp7.0-mysql - MySQL module for PHP\nphp7.0-opcache - Zend OpCache module for PHP\nphp7.0-bz2 - bzip2 module for PHP\nphp7.0-bcmath - Bcmath module for PHP\nphp7.0-mbstring - MBSTRING module for PHP\nphp7.0-soap - SOAP module for PHP\nphp7.0-xml - DOM, SimpleXML, WDDX, XML, and XSL module for PHP\nphp7.0-zip - Zip module for PHP" }, { "code": null, "e": 5510, "s": 5465, "text": "To install PHP7, use the following command –" }, { "code": null, "e": 5540, "s": 5510, "text": "$ sudo apt-get install php7.0" }, { "code": null, "e": 5580, "s": 5540, "text": "The sample output should be like this –" }, { "code": null, "e": 6626, "s": 5580, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\n libapache2-mod-php5 linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic\n linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic\n linux-signed-image-4.2.0-27-generic\nUse 'apt-get autoremove' to remove them.\nThe following extra packages will be installed:\n libssl1.0.2 php-common php7.0-cli php7.0-common php7.0-fpm php7.0-json\n php7.0-opcache php7.0-readline\nSuggested packages:\n php-pear\nThe following packages will be REMOVED:\n php5 php5-cli php5-readline\nThe following NEW packages will be installed:\n libssl1.0.2 php-common php7.0 php7.0-cli php7.0-common php7.0-fpm\n php7.0-json php7.0-opcache php7.0-readline\n0 upgraded, 9 newly installed, 3 to remove and 3 not upgraded.\nNeed to get 4,383 kB of archives.\nAfter this operation, 8,056 kB of additional disk space will be used.\nDo you want to continue? [Y/n] y\n................................" }, { "code": null, "e": 6684, "s": 6626, "text": "To configure Nginx and PHP 7, use the following command –" }, { "code": null, "e": 6705, "s": 6684, "text": "$ sudo vi nginx.conf" }, { "code": null, "e": 6733, "s": 6705, "text": "Append the code as follows-" }, { "code": null, "e": 7106, "s": 6733, "text": "# Pass all .php files onto a php-fpm/php-fcgi server.\nlocation ~ [^/]\\.php(/|$) {\n fastcgi_split_path_info ^(.+?\\.php)(/.*)$;\n if (!-f $document_root$fastcgi_script_name) {\n return 404;\n }\n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n fastcgi_pass unix:/run/php/php7.0-fpm.sock;\n fastcgi_index index.php;\n include fastcgi_params;\n}" }, { "code": null, "e": 7187, "s": 7106, "text": "Save and close the file, To reload the nginx server, use the following command –" }, { "code": null, "e": 7215, "s": 7187, "text": "$ sudo service nginx reload" }, { "code": null, "e": 7255, "s": 7215, "text": "The sample output should be like this –" }, { "code": null, "e": 7300, "s": 7255, "text": "* Reloading nginx configuration nginx [ OK ]" }, { "code": null, "e": 7416, "s": 7300, "text": "Before reload nginx.you should verify nginx installed or not in your linux system. if not, then install as follows-" }, { "code": null, "e": 7448, "s": 7416, "text": "$ sudo apt-get install -y nginx" }, { "code": null, "e": 7488, "s": 7448, "text": "The sample output should be like this –" }, { "code": null, "e": 8297, "s": 7488, "text": "Reading state information... Done\nThe following packages were automatically installed and are no longer required:\n libapache2-mod-php5 linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic\n linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic\n linux-signed-image-4.2.0-27-generic\nUse 'apt-get autoremove' to remove them.\nThe following extra packages will be installed:\n nginx-common nginx-core\nSuggested packages:\n fcgiwrap nginx-doc\nThe following NEW packages will be installed:\n nginx nginx-common nginx-core\n0 upgraded, 3 newly installed, 0 to remove and 3 not upgraded.\nNeed to get 349 kB of archives.\nAfter this operation, 1,297 kB of additional disk space will be used.\nGet:1 http://in.archive.ubuntu.com/ubuntu/ trusty-updates/main nginx-common all\n............................." }, { "code": null, "e": 8470, "s": 8297, "text": "If nginx is already installed in Linux then reload nginx using the above command. To test new PHP 7 installation creates a file called test.php in /var/www/html/ directory." }, { "code": null, "e": 8501, "s": 8470, "text": "test.php should be like this –" }, { "code": null, "e": 8524, "s": 8501, "text": "<?php\n phpinfo();\n?>" }, { "code": null, "e": 8569, "s": 8524, "text": "Save and close the file. Run it as follows –" }, { "code": null, "e": 8595, "s": 8569, "text": "http://localhost/test.php" }, { "code": null, "e": 8761, "s": 8595, "text": "Congratulations! Now, you know “How to install PHP 7 on Ubuntu Linux 14.04 LTS”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
Python - Largest number possible from list of given numbers
In this article, we are going to learn how to find the possible largest number from the given list of numbers. We will see two different ways to find to solve the problem. Follow the below steps to solve the problem. Import the itertools module for permutations method. Initialize the list with numbers and an empty list. Iterate over the permutations of the list.Join all the combinations and add the result to the empty list. Join all the combinations and add the result to the empty list. Find the max number from the result with max method and key as int. Convert the string to integer and print it. Let's see the code. Live Demo # importing the module import itertools # initializing the list numbers = [45, 35, 138, 43, 67] # result result = [] # permutations for permutation in itertools.permutations(str(number) for number in numbers): result.append(''.join(permutation)) # finding max maximum = max(result, key=int) # printing the max print(int(maximum)) If you run the above code, then you will get the following result. 67454335138 Let's see another way to solve the problem. We will sorted function to solve the problem. Follow the below steps to write the code. Pass the list to the sorted function. Write a function called get_key that accepts two arguments. Return -1 if the str(first) + str(second) > str(second) + str(first) else 1. Joining the list of elements using join method. Print the result by converting into an integer. As we are using a function as key, we have to convert it to the key using cmp_to_key method from functools. Let's see the code. Live Demo from functools import cmp_to_key # initializing the list numbers = [45, 35, 138, 43, 67] def get_key(first, second): if str(first) + str(second) > str(second) + str(first): return -1 return 1 # getting the result result = sorted(numbers, key=cmp_to_key(get_key)) # joining the result result = "".join(str(integer) for integer in result) # printing the result print(int(result)) If you run the above code, then you will get the following result. 67454335138 If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1279, "s": 1062, "text": "In this article, we are going to learn how to find the possible largest number from the given list of numbers. We will see two different ways to find to solve the problem. Follow the below steps to solve the problem." }, { "code": null, "e": 1332, "s": 1279, "text": "Import the itertools module for permutations method." }, { "code": null, "e": 1384, "s": 1332, "text": "Initialize the list with numbers and an empty list." }, { "code": null, "e": 1490, "s": 1384, "text": "Iterate over the permutations of the list.Join all the combinations and add the result to the empty list." }, { "code": null, "e": 1554, "s": 1490, "text": "Join all the combinations and add the result to the empty list." }, { "code": null, "e": 1622, "s": 1554, "text": "Find the max number from the result with max method and key as int." }, { "code": null, "e": 1666, "s": 1622, "text": "Convert the string to integer and print it." }, { "code": null, "e": 1686, "s": 1666, "text": "Let's see the code." }, { "code": null, "e": 1697, "s": 1686, "text": " Live Demo" }, { "code": null, "e": 2035, "s": 1697, "text": "# importing the module\nimport itertools\n\n# initializing the list\nnumbers = [45, 35, 138, 43, 67]\n\n# result\nresult = []\n\n# permutations\nfor permutation in itertools.permutations(str(number) for number in numbers):\n result.append(''.join(permutation))\n\n# finding max\nmaximum = max(result, key=int)\n\n# printing the max\nprint(int(maximum))" }, { "code": null, "e": 2102, "s": 2035, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 2115, "s": 2102, "text": "67454335138\n" }, { "code": null, "e": 2247, "s": 2115, "text": "Let's see another way to solve the problem. We will sorted function to solve the problem. Follow the below steps to write the code." }, { "code": null, "e": 2285, "s": 2247, "text": "Pass the list to the sorted function." }, { "code": null, "e": 2345, "s": 2285, "text": "Write a function called get_key that accepts two arguments." }, { "code": null, "e": 2422, "s": 2345, "text": "Return -1 if the str(first) + str(second) > str(second) + str(first) else 1." }, { "code": null, "e": 2470, "s": 2422, "text": "Joining the list of elements using join method." }, { "code": null, "e": 2518, "s": 2470, "text": "Print the result by converting into an integer." }, { "code": null, "e": 2646, "s": 2518, "text": "As we are using a function as key, we have to convert it to the key using cmp_to_key method from functools. Let's see the code." }, { "code": null, "e": 2657, "s": 2646, "text": " Live Demo" }, { "code": null, "e": 3052, "s": 2657, "text": "from functools import cmp_to_key\n\n# initializing the list\nnumbers = [45, 35, 138, 43, 67]\n\ndef get_key(first, second):\n if str(first) + str(second) > str(second) + str(first):\n return -1\n return 1\n\n# getting the result\nresult = sorted(numbers, key=cmp_to_key(get_key))\n\n# joining the result\nresult = \"\".join(str(integer) for integer in result)\n\n# printing the result\nprint(int(result))" }, { "code": null, "e": 3119, "s": 3052, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 3132, "s": 3119, "text": "67454335138\n" }, { "code": null, "e": 3210, "s": 3132, "text": "If you have any queries in the tutorial, mention them in the comment section." } ]
Partition negative and positive without comparison with 0 - GeeksforGeeks
24 May, 2021 Given an array of n integers, both negative and positive, partition them into two different arrays without comparing any element with 0. Examples: Input : arr[] = [1, -2, 6, -7, 8] Output : a[] = [1, 6, 8] b[] = [-2, -7] Algorithm: Initialize two empty vectors. Push the first element of the array into any of the two vectors. Suppose the first vector. Let it be denoted by x.For every other element, arr[1] to arr[n-1], check if its sign and the sign of x are the same or not. If the signs are the same, then push the element in the same vector. Else, push the element into the other vector.After the traversal of the two vectors has been completed, print both the vectors. Initialize two empty vectors. Push the first element of the array into any of the two vectors. Suppose the first vector. Let it be denoted by x. For every other element, arr[1] to arr[n-1], check if its sign and the sign of x are the same or not. If the signs are the same, then push the element in the same vector. Else, push the element into the other vector. After the traversal of the two vectors has been completed, print both the vectors. How to check if their signs are opposite or not? Let the integers be checked to be denoted by x and y. The sign bit is 1 in negative numbers, and 0 in positive numbers. The XOR of x and y will have the sign bit is 1 if and only if they have opposite signs. In other words, the XOR of x and y will be a negative number if and only if x and y have opposite signs. CPP Java Python3 C# Javascript // CPP program to rearrange positive and// negative numbers without comparison// with 0.#include <bits/stdc++.h>using namespace std; bool oppositeSigns(int x, int y){ return ((x ^ y) < 0);} void partitionNegPos(int arr[], int n){ vector<int> a, b; // Push first element to a. a.push_back(arr[0]); // Now put all elements of same sign // in a[] and opposite sign in b[] for (int i = 1; i < n; i++) { if (oppositeSigns(a[0], arr[i])) b.push_back(arr[i]); else a.push_back(arr[i]); } // Print a[] and b[] for (int i = 0; i < a.size(); i++) cout << a[i] << ' '; cout << '\n'; for (int i = 0; i < b.size(); i++) cout << b[i] << ' ';} int main(){ int arr[] = { 1, -2, 6, -7, 8 }; int n = sizeof(arr) / sizeof(arr[0]); partitionNegPos(arr, n); return 0;} // Java program to rearrange positive and// negative numbers without comparison// with 0.import java.util.*; class GFG{ static boolean oppositeSigns(int x, int y){ return ((x ^ y) < 0);} static void partitionNegPos(int arr[], int n){ Vector<Integer> a = new Vector<Integer>(); Vector<Integer> b = new Vector<Integer>(); // Push first element to a. a.add(arr[0]); // Now put all elements of same sign // in a[] and opposite sign in b[] for (int i = 1; i < n; i++) { if (oppositeSigns(a.get(0), arr[i])) b.add(arr[i]); else a.add(arr[i]); } // Print a[] and b[] for (int i = 0; i < a.size(); i++) System.out.print(a.get(i) + " "); System.out.println(""); for (int i = 0; i < b.size(); i++) System.out.print(b.get(i) + " ");} public static void main(String[] args){ int arr[] = { 1, -2, 6, -7, 8 }; int n = arr.length; partitionNegPos(arr, n);}} // This code has been contributed by 29AjayKumar # Python3 program to rearrange positive# and negative numbers without comparison# with 0. def oppositeSigns(x, y): return ((x ^ y) < 0) def partitionNegPos(arr, n): a = [] b = [] # Push first element to a. a = a + [arr[0]] # Now put all elements of same sign # in a[] and opposite sign in b[] for i in range(1, n) : if (oppositeSigns(a[0], arr[i])): b = b + [arr[i]] else: a = a + [arr[i]] # Print a[] and b[] for i in range(0, len(a)): print(a[i], end = ' ') print("") for i in range(0, len(b)): print(b[i], end = ' ') # Driver codearr = [1, -2, 6, -7, 8 ]n = len(arr)partitionNegPos(arr, n) # This code is contributed by Smitha // C# program to rearrange positive and// negative numbers without comparison// with 0.using System;using System.Collections.Generic; class GFG{ static bool oppositeSigns(int x, int y){ return ((x ^ y) < 0);} static void partitionNegPos(int []arr, int n){ List<int> a = new List<int> (); List<int> b = new List<int> (); // Push first element to a. a.Add(arr[0]); // Now put all elements of same sign // in a[] and opposite sign in b[] for (int i = 1; i < n; i++) { if (oppositeSigns(a[0], arr[i])) b.Add(arr[i]); else a.Add(arr[i]); } // Print a[] and b[] for (int i = 0; i < a.Count; i++) Console.Write(a[i] + " "); Console.WriteLine(""); for (int i = 0; i < b.Count; i++) Console.Write(b[i] + " ");} // Driver codepublic static void Main(){ int []arr = { 1, -2, 6, -7, 8 }; int n = arr.Length; partitionNegPos(arr, n);}} /* This code contributed by PrinciRaj1992 */ <script> // Javascript program to rearrange positive and// negative numbers without comparison// with 0. function oppositeSigns(x, y){ return ((x ^ y) < 0);} function partitionNegPos(arr, n){ var a = [], b = []; // Push first element to a. a.push(arr[0]); // Now put all elements of same sign // in a[] and opposite sign in b[] for (var i = 1; i < n; i++) { if (oppositeSigns(a[0], arr[i])) b.push(arr[i]); else a.push(arr[i]); } // Print a[] and b[] for (var i = 0; i < a.length; i++) document.write( a[i] + ' '); document.write( "<br>" ); for (var i = 0; i < b.length; i++) document.write( b[i] + ' ');} var arr = [1, -2, 6, -7, 8];var n = arr.length;partitionNegPos(arr, n); </script> Output: 1 6 8 -2 -7 Smitha Dinesh Semwal 29AjayKumar princiraj1992 rrrtnx array-rearrange cpp-vector programming-puzzle Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Remove duplicates from sorted array Building Heap from Array Find subarray with given sum | Set 1 (Nonnegative Numbers) Counting frequencies of array elements Move all negative numbers to beginning and positive to end with constant extra space
[ { "code": null, "e": 24429, "s": 24401, "text": "\n24 May, 2021" }, { "code": null, "e": 24566, "s": 24429, "text": "Given an array of n integers, both negative and positive, partition them into two different arrays without comparing any element with 0." }, { "code": null, "e": 24578, "s": 24566, "text": "Examples: " }, { "code": null, "e": 24662, "s": 24578, "text": "Input : arr[] = [1, -2, 6, -7, 8]\nOutput : a[] = [1, 6, 8] \n b[] = [-2, -7]" }, { "code": null, "e": 24675, "s": 24662, "text": "Algorithm: " }, { "code": null, "e": 25120, "s": 24675, "text": "Initialize two empty vectors. Push the first element of the array into any of the two vectors. Suppose the first vector. Let it be denoted by x.For every other element, arr[1] to arr[n-1], check if its sign and the sign of x are the same or not. If the signs are the same, then push the element in the same vector. Else, push the element into the other vector.After the traversal of the two vectors has been completed, print both the vectors. " }, { "code": null, "e": 25265, "s": 25120, "text": "Initialize two empty vectors. Push the first element of the array into any of the two vectors. Suppose the first vector. Let it be denoted by x." }, { "code": null, "e": 25482, "s": 25265, "text": "For every other element, arr[1] to arr[n-1], check if its sign and the sign of x are the same or not. If the signs are the same, then push the element in the same vector. Else, push the element into the other vector." }, { "code": null, "e": 25567, "s": 25482, "text": "After the traversal of the two vectors has been completed, print both the vectors. " }, { "code": null, "e": 25931, "s": 25567, "text": "How to check if their signs are opposite or not? Let the integers be checked to be denoted by x and y. The sign bit is 1 in negative numbers, and 0 in positive numbers. The XOR of x and y will have the sign bit is 1 if and only if they have opposite signs. In other words, the XOR of x and y will be a negative number if and only if x and y have opposite signs. " }, { "code": null, "e": 25935, "s": 25931, "text": "CPP" }, { "code": null, "e": 25940, "s": 25935, "text": "Java" }, { "code": null, "e": 25948, "s": 25940, "text": "Python3" }, { "code": null, "e": 25951, "s": 25948, "text": "C#" }, { "code": null, "e": 25962, "s": 25951, "text": "Javascript" }, { "code": "// CPP program to rearrange positive and// negative numbers without comparison// with 0.#include <bits/stdc++.h>using namespace std; bool oppositeSigns(int x, int y){ return ((x ^ y) < 0);} void partitionNegPos(int arr[], int n){ vector<int> a, b; // Push first element to a. a.push_back(arr[0]); // Now put all elements of same sign // in a[] and opposite sign in b[] for (int i = 1; i < n; i++) { if (oppositeSigns(a[0], arr[i])) b.push_back(arr[i]); else a.push_back(arr[i]); } // Print a[] and b[] for (int i = 0; i < a.size(); i++) cout << a[i] << ' '; cout << '\\n'; for (int i = 0; i < b.size(); i++) cout << b[i] << ' ';} int main(){ int arr[] = { 1, -2, 6, -7, 8 }; int n = sizeof(arr) / sizeof(arr[0]); partitionNegPos(arr, n); return 0;}", "e": 26811, "s": 25962, "text": null }, { "code": "// Java program to rearrange positive and// negative numbers without comparison// with 0.import java.util.*; class GFG{ static boolean oppositeSigns(int x, int y){ return ((x ^ y) < 0);} static void partitionNegPos(int arr[], int n){ Vector<Integer> a = new Vector<Integer>(); Vector<Integer> b = new Vector<Integer>(); // Push first element to a. a.add(arr[0]); // Now put all elements of same sign // in a[] and opposite sign in b[] for (int i = 1; i < n; i++) { if (oppositeSigns(a.get(0), arr[i])) b.add(arr[i]); else a.add(arr[i]); } // Print a[] and b[] for (int i = 0; i < a.size(); i++) System.out.print(a.get(i) + \" \"); System.out.println(\"\"); for (int i = 0; i < b.size(); i++) System.out.print(b.get(i) + \" \");} public static void main(String[] args){ int arr[] = { 1, -2, 6, -7, 8 }; int n = arr.length; partitionNegPos(arr, n);}} // This code has been contributed by 29AjayKumar", "e": 27811, "s": 26811, "text": null }, { "code": "# Python3 program to rearrange positive# and negative numbers without comparison# with 0. def oppositeSigns(x, y): return ((x ^ y) < 0) def partitionNegPos(arr, n): a = [] b = [] # Push first element to a. a = a + [arr[0]] # Now put all elements of same sign # in a[] and opposite sign in b[] for i in range(1, n) : if (oppositeSigns(a[0], arr[i])): b = b + [arr[i]] else: a = a + [arr[i]] # Print a[] and b[] for i in range(0, len(a)): print(a[i], end = ' ') print(\"\") for i in range(0, len(b)): print(b[i], end = ' ') # Driver codearr = [1, -2, 6, -7, 8 ]n = len(arr)partitionNegPos(arr, n) # This code is contributed by Smitha", "e": 28565, "s": 27811, "text": null }, { "code": "// C# program to rearrange positive and// negative numbers without comparison// with 0.using System;using System.Collections.Generic; class GFG{ static bool oppositeSigns(int x, int y){ return ((x ^ y) < 0);} static void partitionNegPos(int []arr, int n){ List<int> a = new List<int> (); List<int> b = new List<int> (); // Push first element to a. a.Add(arr[0]); // Now put all elements of same sign // in a[] and opposite sign in b[] for (int i = 1; i < n; i++) { if (oppositeSigns(a[0], arr[i])) b.Add(arr[i]); else a.Add(arr[i]); } // Print a[] and b[] for (int i = 0; i < a.Count; i++) Console.Write(a[i] + \" \"); Console.WriteLine(\"\"); for (int i = 0; i < b.Count; i++) Console.Write(b[i] + \" \");} // Driver codepublic static void Main(){ int []arr = { 1, -2, 6, -7, 8 }; int n = arr.Length; partitionNegPos(arr, n);}} /* This code contributed by PrinciRaj1992 */", "e": 29541, "s": 28565, "text": null }, { "code": "<script> // Javascript program to rearrange positive and// negative numbers without comparison// with 0. function oppositeSigns(x, y){ return ((x ^ y) < 0);} function partitionNegPos(arr, n){ var a = [], b = []; // Push first element to a. a.push(arr[0]); // Now put all elements of same sign // in a[] and opposite sign in b[] for (var i = 1; i < n; i++) { if (oppositeSigns(a[0], arr[i])) b.push(arr[i]); else a.push(arr[i]); } // Print a[] and b[] for (var i = 0; i < a.length; i++) document.write( a[i] + ' '); document.write( \"<br>\" ); for (var i = 0; i < b.length; i++) document.write( b[i] + ' ');} var arr = [1, -2, 6, -7, 8];var n = arr.length;partitionNegPos(arr, n); </script>", "e": 30319, "s": 29541, "text": null }, { "code": null, "e": 30329, "s": 30319, "text": "Output: " }, { "code": null, "e": 30341, "s": 30329, "text": "1 6 8\n-2 -7" }, { "code": null, "e": 30364, "s": 30343, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 30376, "s": 30364, "text": "29AjayKumar" }, { "code": null, "e": 30390, "s": 30376, "text": "princiraj1992" }, { "code": null, "e": 30397, "s": 30390, "text": "rrrtnx" }, { "code": null, "e": 30413, "s": 30397, "text": "array-rearrange" }, { "code": null, "e": 30424, "s": 30413, "text": "cpp-vector" }, { "code": null, "e": 30443, "s": 30424, "text": "programming-puzzle" }, { "code": null, "e": 30450, "s": 30443, "text": "Arrays" }, { "code": null, "e": 30457, "s": 30450, "text": "Arrays" }, { "code": null, "e": 30555, "s": 30457, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30564, "s": 30555, "text": "Comments" }, { "code": null, "e": 30577, "s": 30564, "text": "Old Comments" }, { "code": null, "e": 30598, "s": 30577, "text": "Next Greater Element" }, { "code": null, "e": 30623, "s": 30598, "text": "Window Sliding Technique" }, { "code": null, "e": 30650, "s": 30623, "text": "Count pairs with given sum" }, { "code": null, "e": 30699, "s": 30650, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30737, "s": 30699, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30773, "s": 30737, "text": "Remove duplicates from sorted array" }, { "code": null, "e": 30798, "s": 30773, "text": "Building Heap from Array" }, { "code": null, "e": 30857, "s": 30798, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 30896, "s": 30857, "text": "Counting frequencies of array elements" } ]
Auto insert values into a MySQL table in a range?
For this, you can create a stored procedure. Let us first create a table. mysql> create table DemoTable -> ( -> Value int -> ); Query OK, 0 rows affected (0.55 sec) Following is the query to create a stored procedure to auto insert values to a table from range 10 to 20 − mysql> DELIMITER // mysql> CREATE PROCEDURE AutoInsertValuesToTable() -> BEGIN -> DECLARE startingRange INT DEFAULT 10; -> WHILE startingRange <= 20 DO -> INSERT DemoTable(Value) VALUES (startingRange ); -> SET startingRange = startingRange + 1; -> END WHILE; -> END -> // Query OK, 0 rows affected (0.23 sec) mysql> DELIMITER ; Here is the query to call the stored procedure − mysql> call AutoInsertValuesToTable(); Query OK, 1 row affected (1.10 sec) Now you can check the value is inserted into the above table or not − mysql> select *from DemoTable; This will produce the following output − +-------+ | Value | +-------+ | 10 | | 11 | | 12 | | 13 | | 14 | | 15 | | 16 | | 17 | | 18 | | 19 | | 20 | +-------+ 11 rows in set (0.00 sec) The value inserted into the above table successfully from range 10 to 20.
[ { "code": null, "e": 1136, "s": 1062, "text": "For this, you can create a stored procedure. Let us first create a table." }, { "code": null, "e": 1236, "s": 1136, "text": "mysql> create table DemoTable\n -> (\n -> Value int\n -> );\nQuery OK, 0 rows affected (0.55 sec)" }, { "code": null, "e": 1343, "s": 1236, "text": "Following is the query to create a stored procedure to auto insert values to a table from range 10 to 20 −" }, { "code": null, "e": 1717, "s": 1343, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE AutoInsertValuesToTable()\n -> BEGIN\n -> DECLARE startingRange INT DEFAULT 10;\n -> WHILE startingRange <= 20 DO\n -> INSERT DemoTable(Value) VALUES (startingRange );\n -> SET startingRange = startingRange + 1;\n -> END WHILE;\n -> END\n -> //\nQuery OK, 0 rows affected (0.23 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 1766, "s": 1717, "text": "Here is the query to call the stored procedure −" }, { "code": null, "e": 1841, "s": 1766, "text": "mysql> call AutoInsertValuesToTable();\nQuery OK, 1 row affected (1.10 sec)" }, { "code": null, "e": 1911, "s": 1841, "text": "Now you can check the value is inserted into the above table or not −" }, { "code": null, "e": 1942, "s": 1911, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1983, "s": 1942, "text": "This will produce the following output −" }, { "code": null, "e": 2159, "s": 1983, "text": "+-------+\n| Value |\n+-------+\n| 10 |\n| 11 |\n| 12 |\n| 13 |\n| 14 |\n| 15 |\n| 16 |\n| 17 |\n| 18 |\n| 19 |\n| 20 |\n+-------+\n11 rows in set (0.00 sec)" }, { "code": null, "e": 2233, "s": 2159, "text": "The value inserted into the above table successfully from range 10 to 20." } ]
Pascal - Nested Loops
Pascal allows using one loop inside another loop. Following section shows few examples to illustrate the concept. The syntax for a nested for-do loop statement in Pascal is as follows − for variable1:=initial_value1 to [downto] final_value1 do begin for variable2:=initial_value2 to [downto] final_value2 do begin statement(s); end; end; The syntax for a nested while-do loop statement in Pascal is as follows − while(condition1)do begin while(condition2) do begin statement(s); end; statement(s); end; The syntax for a nested repeat ... until loop Pascal is as follows − repeat statement(s); repeat statement(s); until(condition2); until(condition1); A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa. The following program uses a nested for loop to find the prime numbers from 2 to 50 − program nestedPrime; var i, j:integer; begin for i := 2 to 50 do begin for j := 2 to i do if (i mod j)=0 then break; {* if factor found, not prime *} if(j = i) then writeln(i , ' is prime' ); end; end. When the above code is compiled and executed, it produces the following result − 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2197, "s": 2083, "text": "Pascal allows using one loop inside another loop. Following section shows few examples to illustrate the concept." }, { "code": null, "e": 2269, "s": 2197, "text": "The syntax for a nested for-do loop statement in Pascal is as follows −" }, { "code": null, "e": 2447, "s": 2269, "text": "for variable1:=initial_value1 to [downto] final_value1 do\n\nbegin\n for variable2:=initial_value2 to [downto] final_value2 do\n \n begin \n statement(s);\n end;\nend; " }, { "code": null, "e": 2521, "s": 2447, "text": "The syntax for a nested while-do loop statement in Pascal is as follows −" }, { "code": null, "e": 2635, "s": 2521, "text": "while(condition1)do\n\nbegin\n while(condition2) do\n \n begin\n statement(s);\n end;\n statement(s);\nend;" }, { "code": null, "e": 2704, "s": 2635, "text": "The syntax for a nested repeat ... until loop Pascal is as follows −" }, { "code": null, "e": 2799, "s": 2704, "text": "repeat\n statement(s);\n repeat\n statement(s);\n until(condition2);\nuntil(condition1);" }, { "code": null, "e": 2965, "s": 2799, "text": "A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa." }, { "code": null, "e": 3051, "s": 2965, "text": "The following program uses a nested for loop to find the prime numbers from 2 to 50 −" }, { "code": null, "e": 3320, "s": 3051, "text": "program nestedPrime;\nvar\n i, j:integer;\n\nbegin\n for i := 2 to 50 do\n \n begin\n for j := 2 to i do\n if (i mod j)=0 then\n break; {* if factor found, not prime *}\n \n if(j = i) then\n writeln(i , ' is prime' );\n end;\nend." }, { "code": null, "e": 3401, "s": 3320, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3578, "s": 3401, "text": "2 is prime\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime\n31 is prime\n37 is prime\n41 is prime\n43 is prime\n47 is prime\n" }, { "code": null, "e": 3613, "s": 3578, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3636, "s": 3613, "text": " Stone River ELearning" }, { "code": null, "e": 3643, "s": 3636, "text": " Print" }, { "code": null, "e": 3654, "s": 3643, "text": " Add Notes" } ]
How to save a plot in pdf in R?
To save a plot in pdf, we can use the pdf function in base R. For example, if we want to save a plot with the name PDF then it can be done using the below command − pdf("PDF.pdf") After this we can create the plot and use dev.off(). pdf("pdfExample.pdf") plot(1:10) Live Demo dev.off() To check where it is saved, find the working directory using getwd().
[ { "code": null, "e": 1227, "s": 1062, "text": "To save a plot in pdf, we can use the pdf function in base R. For example, if we want to save a plot with the name PDF then it can be done using the below command −" }, { "code": null, "e": 1242, "s": 1227, "text": "pdf(\"PDF.pdf\")" }, { "code": null, "e": 1295, "s": 1242, "text": "After this we can create the plot and use dev.off()." }, { "code": null, "e": 1328, "s": 1295, "text": "pdf(\"pdfExample.pdf\")\nplot(1:10)" }, { "code": null, "e": 1339, "s": 1328, "text": " Live Demo" }, { "code": null, "e": 1349, "s": 1339, "text": "dev.off()" }, { "code": null, "e": 1419, "s": 1349, "text": "To check where it is saved, find the working directory using getwd()." } ]
Find the minimum number of elements that should be removed to make an array good - GeeksforGeeks
26 Aug, 2021 Given an array of size N and an integer K. The array consists of only digits {0, 1, 2, 3, ...k-1}. The task is to make array good by removing some of the elements. The array of length x is called good if x is divisible by k and one can split the given array into x/k subsequences and each of form {0, 1, 2, 3, ...k-1}.Note: An empty array is also a good arrayExamples: Input : a[] = {0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4}, K = 5 Output : 2 First sequence is formed from first, second, third, fourth and fifth element and second sequence is formed from eighth, ninth tenth, eleventh and twelfth. so, remove last fifth and sixth elements.Input : a[] = {0, 2, 1, 3}, k = 4 Output : 4 Remove all elements. One can’t make subsequence of the form {0, 1, 2, 3} Approach: Let cnt0 be the number of subsequences of [0], cnt1 be the number of subsequences [0, 1], cnt2 — the number of subsequences [0, 1, 2] and so on, and cntk-1 is the number of completed subsequences [0, 1, 2, 3, ...k-1]. Iterate over all elements of arr in order from left to right.If the current element in the array is zero then increase the count of cnt0 by 1. If the current element in the array is not zero then check if its previous element in the sequence count is greater than zero or not. If its previous element in the sequence is greater than zero then decrement the count of the previous element by one and increment count of the current element by one. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to remove minimum elements to// make the given array good#include <bits/stdc++.h>using namespace std; // Function to remove minimum elements to// make the given array goodint MinRemove(int a[], int n, int k){ // To store count of each subsequence vector<int> cnt(k, 0); for (int i = 0; i < n; i++) { // Increase the count of subsequence [0] if (a[i] == 0) cnt[0]++; // If Previous element subsequence count // is greater than zero then increment // subsequence count of current element // and decrement subsequence count of // the previous element. else if (cnt[a[i] - 1] > 0) { cnt[a[i] - 1]--; cnt[a[i]]++; } } // Return the required answer return n - (k * cnt[k - 1]);} // Driver codeint main(){ int a[] = { 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4 }, k = 5; int n = sizeof(a) / sizeof(a[0]); // Function call cout << MinRemove(a, n, k); return 0;} // Java program to remove minimum elements to// make the given array goodimport java.util.Collections;import java.util.Vector; class GFG{ // Function to remove minimum elements to // make the given array good static int MinRemove(int[] a, int n, int k) { // To store count of each subsequence int []cnt = new int[n]; for (int i = 0; i < n; i++) { // Increase the count of subsequence [0] if (a[i] == 0) cnt[0]++; // If Previous element subsequence count // is greater than zero then increment // subsequence count of current element // and decrement subsequence count of // the previous element. else if (cnt[a[i] - 1] > 0) { cnt[a[i] - 1]--; cnt[a[i]]++; } } // Return the required answer return n - (k * cnt[k - 1]); } // Driver code public static void main(String[] args) { int a[] = { 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4 }; int k = 5; int n = a.length; // Function call System.out.println(MinRemove(a, n, k)); }} // This code contributed by Rajput-Ji # Python3 program to remove minimum elements to# make the given array good # Function to remove minimum elements to# make the given array gooddef MinRemove(a, n, k) : # To store count of each subsequence cnt = [0] * k for i in range(n) : # Increase the count of subsequence [0] if (a[i] == 0) : cnt[0] += 1; # If Previous element subsequence count # is greater than zero then increment # subsequence count of current element # and decrement subsequence count of # the previous element. elif (cnt[a[i] - 1] > 0) : cnt[a[i] - 1] -= 1; cnt[a[i]] += 1; # Return the required answer return n - (k * cnt[k - 1]); # Driver codeif __name__ == "__main__" : a = [ 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4 ] k = 5; n = len(a); # Function call print(MinRemove(a, n, k)); # This code is contributed by AnkitRai01 // C# program to remove minimum elements to// make the given array goodusing System; class GFG{ // Function to remove minimum elements to // make the given array good static int MinRemove(int[] a, int n, int k) { // To store count of each subsequence int []cnt = new int[n]; for (int i = 0; i < n; i++) { // Increase the count of subsequence [0] if (a[i] == 0) cnt[0]++; // If Previous element subsequence count // is greater than zero then increment // subsequence count of current element // and decrement subsequence count of // the previous element. else if (cnt[a[i] - 1] > 0) { cnt[a[i] - 1]--; cnt[a[i]]++; } } // Return the required answer return n - (k * cnt[k - 1]); } // Driver code public static void Main(String[] args) { int []a = { 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4 }; int k = 5; int n = a.Length; // Function call Console.WriteLine(MinRemove(a, n, k)); }} // This code is contributed by 29AjayKumar <script> // Javascript program to remove minimum elements to// make the given array good // Function to remove minimum elements to// make the given array goodfunction MinRemove(a, n, k){ // To store count of each subsequence let cnt = new Array(k).fill(0); for (let i = 0; i < n; i++) { // Increase the count of subsequence [0] if (a[i] == 0) cnt[0]++; // If Previous element subsequence count // is greater than zero then increment // subsequence count of current element // and decrement subsequence count of // the previous element. else if (cnt[a[i] - 1] > 0) { cnt[a[i] - 1]--; cnt[a[i]]++; } } // Return the required answer return n - (k * cnt[k - 1]);} // Driver code let a = [ 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4 ], k = 5; let n = a.length; // Function call document.write(MinRemove(a, n, k)); </script> 2 Time Complexity : O(N) Rajput-Ji ankthon 29AjayKumar singhtejasv9 subham348 khushboogoyal499 subsequence Arrays Competitive Programming Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Multidimensional Arrays in Java Introduction to Arrays Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Top 15 Websites for Coding Challenges and Competitions Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 25528, "s": 25500, "text": "\n26 Aug, 2021" }, { "code": null, "e": 25897, "s": 25528, "text": "Given an array of size N and an integer K. The array consists of only digits {0, 1, 2, 3, ...k-1}. The task is to make array good by removing some of the elements. The array of length x is called good if x is divisible by k and one can split the given array into x/k subsequences and each of form {0, 1, 2, 3, ...k-1}.Note: An empty array is also a good arrayExamples:" }, { "code": null, "e": 26280, "s": 25897, "text": "Input : a[] = {0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4}, K = 5 Output : 2 First sequence is formed from first, second, third, fourth and fifth element and second sequence is formed from eighth, ninth tenth, eleventh and twelfth. so, remove last fifth and sixth elements.Input : a[] = {0, 2, 1, 3}, k = 4 Output : 4 Remove all elements. One can’t make subsequence of the form {0, 1, 2, 3}" }, { "code": null, "e": 26290, "s": 26280, "text": "Approach:" }, { "code": null, "e": 26508, "s": 26290, "text": "Let cnt0 be the number of subsequences of [0], cnt1 be the number of subsequences [0, 1], cnt2 — the number of subsequences [0, 1, 2] and so on, and cntk-1 is the number of completed subsequences [0, 1, 2, 3, ...k-1]." }, { "code": null, "e": 26651, "s": 26508, "text": "Iterate over all elements of arr in order from left to right.If the current element in the array is zero then increase the count of cnt0 by 1." }, { "code": null, "e": 26785, "s": 26651, "text": "If the current element in the array is not zero then check if its previous element in the sequence count is greater than zero or not." }, { "code": null, "e": 26953, "s": 26785, "text": "If its previous element in the sequence is greater than zero then decrement the count of the previous element by one and increment count of the current element by one." }, { "code": null, "e": 27004, "s": 26953, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27008, "s": 27004, "text": "C++" }, { "code": null, "e": 27013, "s": 27008, "text": "Java" }, { "code": null, "e": 27021, "s": 27013, "text": "Python3" }, { "code": null, "e": 27024, "s": 27021, "text": "C#" }, { "code": null, "e": 27035, "s": 27024, "text": "Javascript" }, { "code": "// C++ program to remove minimum elements to// make the given array good#include <bits/stdc++.h>using namespace std; // Function to remove minimum elements to// make the given array goodint MinRemove(int a[], int n, int k){ // To store count of each subsequence vector<int> cnt(k, 0); for (int i = 0; i < n; i++) { // Increase the count of subsequence [0] if (a[i] == 0) cnt[0]++; // If Previous element subsequence count // is greater than zero then increment // subsequence count of current element // and decrement subsequence count of // the previous element. else if (cnt[a[i] - 1] > 0) { cnt[a[i] - 1]--; cnt[a[i]]++; } } // Return the required answer return n - (k * cnt[k - 1]);} // Driver codeint main(){ int a[] = { 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4 }, k = 5; int n = sizeof(a) / sizeof(a[0]); // Function call cout << MinRemove(a, n, k); return 0;}", "e": 28054, "s": 27035, "text": null }, { "code": "// Java program to remove minimum elements to// make the given array goodimport java.util.Collections;import java.util.Vector; class GFG{ // Function to remove minimum elements to // make the given array good static int MinRemove(int[] a, int n, int k) { // To store count of each subsequence int []cnt = new int[n]; for (int i = 0; i < n; i++) { // Increase the count of subsequence [0] if (a[i] == 0) cnt[0]++; // If Previous element subsequence count // is greater than zero then increment // subsequence count of current element // and decrement subsequence count of // the previous element. else if (cnt[a[i] - 1] > 0) { cnt[a[i] - 1]--; cnt[a[i]]++; } } // Return the required answer return n - (k * cnt[k - 1]); } // Driver code public static void main(String[] args) { int a[] = { 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4 }; int k = 5; int n = a.length; // Function call System.out.println(MinRemove(a, n, k)); }} // This code contributed by Rajput-Ji", "e": 29300, "s": 28054, "text": null }, { "code": "# Python3 program to remove minimum elements to# make the given array good # Function to remove minimum elements to# make the given array gooddef MinRemove(a, n, k) : # To store count of each subsequence cnt = [0] * k for i in range(n) : # Increase the count of subsequence [0] if (a[i] == 0) : cnt[0] += 1; # If Previous element subsequence count # is greater than zero then increment # subsequence count of current element # and decrement subsequence count of # the previous element. elif (cnt[a[i] - 1] > 0) : cnt[a[i] - 1] -= 1; cnt[a[i]] += 1; # Return the required answer return n - (k * cnt[k - 1]); # Driver codeif __name__ == \"__main__\" : a = [ 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4 ] k = 5; n = len(a); # Function call print(MinRemove(a, n, k)); # This code is contributed by AnkitRai01", "e": 30240, "s": 29300, "text": null }, { "code": "// C# program to remove minimum elements to// make the given array goodusing System; class GFG{ // Function to remove minimum elements to // make the given array good static int MinRemove(int[] a, int n, int k) { // To store count of each subsequence int []cnt = new int[n]; for (int i = 0; i < n; i++) { // Increase the count of subsequence [0] if (a[i] == 0) cnt[0]++; // If Previous element subsequence count // is greater than zero then increment // subsequence count of current element // and decrement subsequence count of // the previous element. else if (cnt[a[i] - 1] > 0) { cnt[a[i] - 1]--; cnt[a[i]]++; } } // Return the required answer return n - (k * cnt[k - 1]); } // Driver code public static void Main(String[] args) { int []a = { 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4 }; int k = 5; int n = a.Length; // Function call Console.WriteLine(MinRemove(a, n, k)); }} // This code is contributed by 29AjayKumar", "e": 31445, "s": 30240, "text": null }, { "code": "<script> // Javascript program to remove minimum elements to// make the given array good // Function to remove minimum elements to// make the given array goodfunction MinRemove(a, n, k){ // To store count of each subsequence let cnt = new Array(k).fill(0); for (let i = 0; i < n; i++) { // Increase the count of subsequence [0] if (a[i] == 0) cnt[0]++; // If Previous element subsequence count // is greater than zero then increment // subsequence count of current element // and decrement subsequence count of // the previous element. else if (cnt[a[i] - 1] > 0) { cnt[a[i] - 1]--; cnt[a[i]]++; } } // Return the required answer return n - (k * cnt[k - 1]);} // Driver code let a = [ 0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4 ], k = 5; let n = a.length; // Function call document.write(MinRemove(a, n, k)); </script>", "e": 32410, "s": 31445, "text": null }, { "code": null, "e": 32412, "s": 32410, "text": "2" }, { "code": null, "e": 32436, "s": 32412, "text": "Time Complexity : O(N) " }, { "code": null, "e": 32446, "s": 32436, "text": "Rajput-Ji" }, { "code": null, "e": 32454, "s": 32446, "text": "ankthon" }, { "code": null, "e": 32466, "s": 32454, "text": "29AjayKumar" }, { "code": null, "e": 32479, "s": 32466, "text": "singhtejasv9" }, { "code": null, "e": 32489, "s": 32479, "text": "subham348" }, { "code": null, "e": 32506, "s": 32489, "text": "khushboogoyal499" }, { "code": null, "e": 32518, "s": 32506, "text": "subsequence" }, { "code": null, "e": 32525, "s": 32518, "text": "Arrays" }, { "code": null, "e": 32549, "s": 32525, "text": "Competitive Programming" }, { "code": null, "e": 32562, "s": 32549, "text": "Mathematical" }, { "code": null, "e": 32569, "s": 32562, "text": "Arrays" }, { "code": null, "e": 32582, "s": 32569, "text": "Mathematical" }, { "code": null, "e": 32680, "s": 32582, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32748, "s": 32680, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32792, "s": 32748, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32840, "s": 32792, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32872, "s": 32840, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32895, "s": 32872, "text": "Introduction to Arrays" }, { "code": null, "e": 32938, "s": 32895, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 32981, "s": 32938, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 33022, "s": 32981, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 33077, "s": 33022, "text": "Top 15 Websites for Coding Challenges and Competitions" } ]
Count of AP (Arithmetic Progression) Subsequences in an array - GeeksforGeeks
21 May, 2021 Given an array of n positive integers. The task is to count the number of Arithmetic Progression subsequence in the array. Note: Empty sequence or single element sequence is Arithmetic Progression. 1 <= arr[i] <= 1000000.Examples: Input : arr[] = { 1, 2, 3 } Output : 8 Arithmetic Progression subsequence from the given array are: {}, { 1 }, { 2 }, { 3 }, { 1, 2 }, { 2, 3 }, { 1, 3 }, { 1, 2, 3 }. Input : arr[] = { 10, 20, 30, 45 } Output : 12 Input : arr[] = { 1, 2, 3, 4, 5 } Output : 23 Since empty sequence and single element sequence is also arithmetic progression, so we initialize the answer with n(number of element in the array) + 1. Now, we need to find the arithmetic progression subsequence of length greater than or equal to 2. Let minimum and maximum of the array be minarr and maxarr respectively. Observe, in all the arithmetic progression subsequences, the range of common difference will be from (minarr – maxarr) to (maxarr – minarr). Now, for each common difference, say d, calculate the subsequence of length greater than or equal to 2 using dynamic programming. Let dp[i] be the number of subsequence that end with arr[i] and have common difference of d. So, The number of subsequence of length greater than or equal to 2 with common difference d is sum of dp[i] – 1, 0 <= i = 2 with difference d. To speed up, store the sum of dp[j] with arr[j] + d = arr[i] and j < i.Below is implementation of above idea : C++ Java Python3 C# Javascript // C++ program to find number of AP// subsequences in the given array#include<bits/stdc++.h>#define MAX 1000001using namespace std; int numofAP(int a[], int n){ // initializing the minimum value and // maximum value of the array. int minarr = INT_MAX, maxarr = INT_MIN; // Finding the minimum and maximum // value of the array. for (int i = 0; i < n; i++) { minarr = min(minarr, a[i]); maxarr = max(maxarr, a[i]); } // dp[i] is going to store count of APs ending // with arr[i]. // sum[j] is going to store sun of all dp[]'s // with j as an AP element. int dp[n], sum[MAX]; // Initialize answer with n + 1 as single elements // and empty array are also DP. int ans = n + 1; // Traversing with all common difference. for (int d=(minarr-maxarr); d<=(maxarr-minarr); d++) { memset(sum, 0, sizeof sum); // Traversing all the element of the array. for (int i = 0; i < n; i++) { // Initialize dp[i] = 1. dp[i] = 1; // Adding counts of APs with given differences // and a[i] is last element. // We consider all APs where an array element // is previous element of AP with a particular // difference if (a[i] - d >= 1 && a[i] - d <= 1000000) dp[i] += sum[a[i] - d]; ans += dp[i] - 1; sum[a[i]] += dp[i]; } } return ans;} // Driver codeint main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr)/sizeof(arr[0]); cout << numofAP(arr, n) << endl; return 0;} // Java program to find number of AP// subsequences in the given arrayimport java.util.Arrays; class GFG { static final int MAX = 1000001; static int numofAP(int a[], int n) { // initializing the minimum value and // maximum value of the array. int minarr = +2147483647; int maxarr = -2147483648; // Finding the minimum and maximum // value of the array. for (int i = 0; i < n; i++) { minarr = Math.min(minarr, a[i]); maxarr = Math.max(maxarr, a[i]); } // dp[i] is going to store count of // APs ending with arr[i]. // sum[j] is going to store sun of // all dp[]'s with j as an AP element. int dp[] = new int[n]; int sum[] = new int[MAX]; // Initialize answer with n + 1 as // single elements and empty array // are also DP. int ans = n + 1; // Traversing with all common // difference. for (int d = (minarr - maxarr); d <= (maxarr - minarr); d++) { Arrays.fill(sum, 0); // Traversing all the element // of the array. for (int i = 0; i < n; i++) { // Initialize dp[i] = 1. dp[i] = 1; // Adding counts of APs with // given differences and a[i] // is last element. // We consider all APs where // an array element is previous // element of AP with a particular // difference if (a[i] - d >= 1 && a[i] - d <= 1000000) dp[i] += sum[a[i] - d]; ans += dp[i] - 1; sum[a[i]] += dp[i]; } } return ans; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3 }; int n = arr.length; System.out.println(numofAP(arr, n)); }} // This code is contributed by Anant Agarwal. # Python program to find number of AP# subsequences in the given array MAX = 1000001 def numofAP(a, n): # initializing the minimum value and # maximum value of the array. minarr = +2147483647 maxarr = -2147483648 # Finding the minimum and # maximum value of the array. for i in range(n): minarr = min(minarr, a[i]) maxarr = max(maxarr, a[i]) # dp[i] is going to store count of APs ending # with arr[i]. # sum[j] is going to store sun of all dp[]'s # with j as an AP element. dp = [0 for i in range(n + 1)] # Initialize answer with n + 1 as single # elements and empty array are also DP. ans = n + 1 # Traversing with all common difference. for d in range((minarr - maxarr), (maxarr - minarr) + 1): sum = [0 for i in range(MAX + 1)] # Traversing all the element of the array. for i in range(n): # Initialize dp[i] = 1. dp[i] = 1 # Adding counts of APs with given differences # and a[i] is last element. # We consider all APs where an array element # is previous element of AP with a particular # difference if (a[i] - d >= 1 and a[i] - d <= 1000000): dp[i] += sum[a[i] - d] ans += dp[i] - 1 sum[a[i]] += dp[i] return ans # Driver codearr = [ 1, 2, 3 ]n = len(arr) print(numofAP(arr, n)) # This code is contributed by Anant Agarwal. // C# program to find number of AP// subsequences in the given arrayusing System; class GFG { static int MAX = 1000001; // Function to find number of AP // subsequences in the given array static int numofAP(int []a, int n) { // initializing the minimum value and // maximum value of the array. int minarr = +2147483647; int maxarr = -2147483648; int i; // Finding the minimum and maximum // value of the array. for (i = 0; i < n; i++) { minarr = Math.Min(minarr, a[i]); maxarr = Math.Max(maxarr, a[i]); } // dp[i] is going to store count of // APs ending with arr[i]. // sum[j] is going to store sun of // all dp[]'s with j as an AP element. int []dp = new int[n]; int []sum = new int[MAX]; // Initialize answer with n + 1 as // single elements and empty array // are also DP. int ans = n + 1; // Traversing with all common // difference. for (int d = (minarr - maxarr); d <= (maxarr - minarr); d++) { for(i = 0; i < MAX; i++) sum[i]= 0; // Traversing all the element // of the array. for ( i = 0; i < n; i++) { // Initialize dp[i] = 1. dp[i] = 1; // Adding counts of APs with // given differences and a[i] // is last element. // We consider all APs where // an array element is previous // element of AP with a particular // difference if (a[i] - d >= 1 && a[i] - d <= 1000000) dp[i] += sum[a[i] - d]; ans += dp[i] - 1; sum[a[i]] += dp[i]; } } return ans; } // Driver code public static void Main() { int []arr = {1, 2, 3}; int n = arr.Length; Console.WriteLine(numofAP(arr, n)); }} // This code is contributed by vt_m. <script> // Javascript program to find number of AP // subsequences in the given array let MAX = 1000001; function numofAP(a, n) { // initializing the minimum value and // maximum value of the array. let minarr = +2147483647; let maxarr = -2147483648; // Finding the minimum and maximum // value of the array. for (let i = 0; i < n; i++) { minarr = Math.min(minarr, a[i]); maxarr = Math.max(maxarr, a[i]); } // dp[i] is going to store count of // APs ending with arr[i]. // sum[j] is going to store sun of // all dp[]'s with j as an AP element. let dp = new Array(n); let sum = new Array(MAX); // Initialize answer with n + 1 as // single elements and empty array // are also DP. let ans = n + 1; // Traversing with all common // difference. for (let d = (minarr - maxarr); d <= (maxarr - minarr); d++) { sum.fill(0); // Traversing all the element // of the array. for (let i = 0; i < n; i++) { // Initialize dp[i] = 1. dp[i] = 1; // Adding counts of APs with // given differences and a[i] // is last element. // We consider all APs where // an array element is previous // element of AP with a particular // difference if (a[i] - d >= 1 && a[i] - d <= 1000000) dp[i] += sum[a[i] - d]; ans += dp[i] - 1; sum[a[i]] += dp[i]; } } return ans; } let arr = [ 1, 2, 3 ]; let n = arr.length; document.write(numofAP(arr, n)); </script> Output : 8 This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m mukesh07 arithmetic progression Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Coin Change | DP-7 Sieve of Eratosthenes Overlapping Subproblems Property in Dynamic Programming | DP-1 Edit Distance | DP-5
[ { "code": null, "e": 25300, "s": 25272, "text": "\n21 May, 2021" }, { "code": null, "e": 25533, "s": 25300, "text": "Given an array of n positive integers. The task is to count the number of Arithmetic Progression subsequence in the array. Note: Empty sequence or single element sequence is Arithmetic Progression. 1 <= arr[i] <= 1000000.Examples: " }, { "code": null, "e": 25797, "s": 25533, "text": "Input : arr[] = { 1, 2, 3 }\nOutput : 8\nArithmetic Progression subsequence from the \ngiven array are: {}, { 1 }, { 2 }, { 3 }, { 1, 2 },\n{ 2, 3 }, { 1, 3 }, { 1, 2, 3 }.\n\nInput : arr[] = { 10, 20, 30, 45 }\nOutput : 12\n\nInput : arr[] = { 1, 2, 3, 4, 5 }\nOutput : 23" }, { "code": null, "e": 26492, "s": 25799, "text": "Since empty sequence and single element sequence is also arithmetic progression, so we initialize the answer with n(number of element in the array) + 1. Now, we need to find the arithmetic progression subsequence of length greater than or equal to 2. Let minimum and maximum of the array be minarr and maxarr respectively. Observe, in all the arithmetic progression subsequences, the range of common difference will be from (minarr – maxarr) to (maxarr – minarr). Now, for each common difference, say d, calculate the subsequence of length greater than or equal to 2 using dynamic programming. Let dp[i] be the number of subsequence that end with arr[i] and have common difference of d. So, " }, { "code": null, "e": 26743, "s": 26492, "text": "The number of subsequence of length greater than or equal to 2 with common difference d is sum of dp[i] – 1, 0 <= i = 2 with difference d. To speed up, store the sum of dp[j] with arr[j] + d = arr[i] and j < i.Below is implementation of above idea : " }, { "code": null, "e": 26747, "s": 26743, "text": "C++" }, { "code": null, "e": 26752, "s": 26747, "text": "Java" }, { "code": null, "e": 26760, "s": 26752, "text": "Python3" }, { "code": null, "e": 26763, "s": 26760, "text": "C#" }, { "code": null, "e": 26774, "s": 26763, "text": "Javascript" }, { "code": "// C++ program to find number of AP// subsequences in the given array#include<bits/stdc++.h>#define MAX 1000001using namespace std; int numofAP(int a[], int n){ // initializing the minimum value and // maximum value of the array. int minarr = INT_MAX, maxarr = INT_MIN; // Finding the minimum and maximum // value of the array. for (int i = 0; i < n; i++) { minarr = min(minarr, a[i]); maxarr = max(maxarr, a[i]); } // dp[i] is going to store count of APs ending // with arr[i]. // sum[j] is going to store sun of all dp[]'s // with j as an AP element. int dp[n], sum[MAX]; // Initialize answer with n + 1 as single elements // and empty array are also DP. int ans = n + 1; // Traversing with all common difference. for (int d=(minarr-maxarr); d<=(maxarr-minarr); d++) { memset(sum, 0, sizeof sum); // Traversing all the element of the array. for (int i = 0; i < n; i++) { // Initialize dp[i] = 1. dp[i] = 1; // Adding counts of APs with given differences // and a[i] is last element. // We consider all APs where an array element // is previous element of AP with a particular // difference if (a[i] - d >= 1 && a[i] - d <= 1000000) dp[i] += sum[a[i] - d]; ans += dp[i] - 1; sum[a[i]] += dp[i]; } } return ans;} // Driver codeint main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr)/sizeof(arr[0]); cout << numofAP(arr, n) << endl; return 0;}", "e": 28376, "s": 26774, "text": null }, { "code": "// Java program to find number of AP// subsequences in the given arrayimport java.util.Arrays; class GFG { static final int MAX = 1000001; static int numofAP(int a[], int n) { // initializing the minimum value and // maximum value of the array. int minarr = +2147483647; int maxarr = -2147483648; // Finding the minimum and maximum // value of the array. for (int i = 0; i < n; i++) { minarr = Math.min(minarr, a[i]); maxarr = Math.max(maxarr, a[i]); } // dp[i] is going to store count of // APs ending with arr[i]. // sum[j] is going to store sun of // all dp[]'s with j as an AP element. int dp[] = new int[n]; int sum[] = new int[MAX]; // Initialize answer with n + 1 as // single elements and empty array // are also DP. int ans = n + 1; // Traversing with all common // difference. for (int d = (minarr - maxarr); d <= (maxarr - minarr); d++) { Arrays.fill(sum, 0); // Traversing all the element // of the array. for (int i = 0; i < n; i++) { // Initialize dp[i] = 1. dp[i] = 1; // Adding counts of APs with // given differences and a[i] // is last element. // We consider all APs where // an array element is previous // element of AP with a particular // difference if (a[i] - d >= 1 && a[i] - d <= 1000000) dp[i] += sum[a[i] - d]; ans += dp[i] - 1; sum[a[i]] += dp[i]; } } return ans; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3 }; int n = arr.length; System.out.println(numofAP(arr, n)); }} // This code is contributed by Anant Agarwal.", "e": 30444, "s": 28376, "text": null }, { "code": "# Python program to find number of AP# subsequences in the given array MAX = 1000001 def numofAP(a, n): # initializing the minimum value and # maximum value of the array. minarr = +2147483647 maxarr = -2147483648 # Finding the minimum and # maximum value of the array. for i in range(n): minarr = min(minarr, a[i]) maxarr = max(maxarr, a[i]) # dp[i] is going to store count of APs ending # with arr[i]. # sum[j] is going to store sun of all dp[]'s # with j as an AP element. dp = [0 for i in range(n + 1)] # Initialize answer with n + 1 as single # elements and empty array are also DP. ans = n + 1 # Traversing with all common difference. for d in range((minarr - maxarr), (maxarr - minarr) + 1): sum = [0 for i in range(MAX + 1)] # Traversing all the element of the array. for i in range(n): # Initialize dp[i] = 1. dp[i] = 1 # Adding counts of APs with given differences # and a[i] is last element. # We consider all APs where an array element # is previous element of AP with a particular # difference if (a[i] - d >= 1 and a[i] - d <= 1000000): dp[i] += sum[a[i] - d] ans += dp[i] - 1 sum[a[i]] += dp[i] return ans # Driver codearr = [ 1, 2, 3 ]n = len(arr) print(numofAP(arr, n)) # This code is contributed by Anant Agarwal.", "e": 31925, "s": 30444, "text": null }, { "code": "// C# program to find number of AP// subsequences in the given arrayusing System; class GFG { static int MAX = 1000001; // Function to find number of AP // subsequences in the given array static int numofAP(int []a, int n) { // initializing the minimum value and // maximum value of the array. int minarr = +2147483647; int maxarr = -2147483648; int i; // Finding the minimum and maximum // value of the array. for (i = 0; i < n; i++) { minarr = Math.Min(minarr, a[i]); maxarr = Math.Max(maxarr, a[i]); } // dp[i] is going to store count of // APs ending with arr[i]. // sum[j] is going to store sun of // all dp[]'s with j as an AP element. int []dp = new int[n]; int []sum = new int[MAX]; // Initialize answer with n + 1 as // single elements and empty array // are also DP. int ans = n + 1; // Traversing with all common // difference. for (int d = (minarr - maxarr); d <= (maxarr - minarr); d++) { for(i = 0; i < MAX; i++) sum[i]= 0; // Traversing all the element // of the array. for ( i = 0; i < n; i++) { // Initialize dp[i] = 1. dp[i] = 1; // Adding counts of APs with // given differences and a[i] // is last element. // We consider all APs where // an array element is previous // element of AP with a particular // difference if (a[i] - d >= 1 && a[i] - d <= 1000000) dp[i] += sum[a[i] - d]; ans += dp[i] - 1; sum[a[i]] += dp[i]; } } return ans; } // Driver code public static void Main() { int []arr = {1, 2, 3}; int n = arr.Length; Console.WriteLine(numofAP(arr, n)); }} // This code is contributed by vt_m.", "e": 34095, "s": 31925, "text": null }, { "code": "<script> // Javascript program to find number of AP // subsequences in the given array let MAX = 1000001; function numofAP(a, n) { // initializing the minimum value and // maximum value of the array. let minarr = +2147483647; let maxarr = -2147483648; // Finding the minimum and maximum // value of the array. for (let i = 0; i < n; i++) { minarr = Math.min(minarr, a[i]); maxarr = Math.max(maxarr, a[i]); } // dp[i] is going to store count of // APs ending with arr[i]. // sum[j] is going to store sun of // all dp[]'s with j as an AP element. let dp = new Array(n); let sum = new Array(MAX); // Initialize answer with n + 1 as // single elements and empty array // are also DP. let ans = n + 1; // Traversing with all common // difference. for (let d = (minarr - maxarr); d <= (maxarr - minarr); d++) { sum.fill(0); // Traversing all the element // of the array. for (let i = 0; i < n; i++) { // Initialize dp[i] = 1. dp[i] = 1; // Adding counts of APs with // given differences and a[i] // is last element. // We consider all APs where // an array element is previous // element of AP with a particular // difference if (a[i] - d >= 1 && a[i] - d <= 1000000) dp[i] += sum[a[i] - d]; ans += dp[i] - 1; sum[a[i]] += dp[i]; } } return ans; } let arr = [ 1, 2, 3 ]; let n = arr.length; document.write(numofAP(arr, n)); </script>", "e": 36009, "s": 34095, "text": null }, { "code": null, "e": 36020, "s": 36009, "text": "Output : " }, { "code": null, "e": 36022, "s": 36020, "text": "8" }, { "code": null, "e": 36443, "s": 36022, "text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 36448, "s": 36443, "text": "vt_m" }, { "code": null, "e": 36457, "s": 36448, "text": "mukesh07" }, { "code": null, "e": 36480, "s": 36457, "text": "arithmetic progression" }, { "code": null, "e": 36500, "s": 36480, "text": "Dynamic Programming" }, { "code": null, "e": 36520, "s": 36500, "text": "Dynamic Programming" }, { "code": null, "e": 36618, "s": 36520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36649, "s": 36618, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 36682, "s": 36649, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 36717, "s": 36682, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 36785, "s": 36717, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 36812, "s": 36785, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 36850, "s": 36812, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 36869, "s": 36850, "text": "Coin Change | DP-7" }, { "code": null, "e": 36891, "s": 36869, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 36954, "s": 36891, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" } ]
spaCy Basics: NLP in Python | Towards Data Science
A major challenge of text data is extracting meaningful patterns and using those patterns to find actionable insights. NLP can be thought of as a two part problem: Processing. Converting the text data from its original form into a form the computer can understand. This includes data cleaning and feature extraction.Analysis. Using the processed data to extract insights and make predictions. Processing. Converting the text data from its original form into a form the computer can understand. This includes data cleaning and feature extraction. Analysis. Using the processed data to extract insights and make predictions. Here we will focus on the processing step. We’ll use a dataset created by scraping Twitter for Donald Trump tweets. A tutorial for creating your own Twitter dataset can be found here: towardsdatascience.com And we will focus exclusively on spaCy “a free, open-source library for advanced Natural Language Processing (NLP) in Python.” spaCy is a great choice for NLP tasks, especially for the processing text and has a ton of features and capabilities, many of which we’ll discuss below. The full notebook can be found here. A good definition of a token, according to researchgate.net, is “a string of contiguous characters between two spaces, or between a space and punctuation marks.” In English, tokens are usually individual words, but can also be punctuation marks and numbers. First we use the spacy.load() method to load a model package by and return the nlp object. Next we call nlp() on a string and spaCy tokenizes the text and creates a document object: # Load model to return language objectnlp = spacy.load('en')# Calling nlp on our tweet texts to return a processed Doc for eachdf['doc'] = [nlp(text) for text in df.text]df.sample(3) After tokenizing, we can do all sorts of things. We could do something basic like count the number of tokens per document and visualize it with a histogram: # Sum the number of tokens in each Docdf['num_tokens'] = [len(token) for token in df.doc]# Visualize histogram of tokens per tweetg = sns.distplot(df.num_tokens) Or we can utilize some of the many available token attributes spaCy has to offer. Spacy makes it easy to get part-of-speech tags using token attributes: # Print sample of part-of-speech tagsfor token in sample_doc[0:10]: print (token.text, token.pos_) In addition to the part-of-speech tags, we can also predict named entities that appear in our documents. According to Wikipedia, a named entity “is a real-world object, such as persons, locations, organizations, products, etc., that can be denoted with a proper name.” for ent in sample_doc.ents: print(ent.text, ent.label_) And, if we don’t know what the output means, spaCy has print(spacy.explain('NORP')) to learn that NORP stands for Nationalities or religious or political groups. In this case, the model is correctly predicts that “Democrats” is a NORP, but is incorrect in classifying “The Oval Office” as an organization. We can visualize named entities using spaCy’s visualizer displaCy: # Visualize named entities with displacyspacy.displacy.render(sample_doc, style='ent', jupyter=True) Lemmatization is the reduction of each word to its root, or lemma. For example, talk, talks, and talking are forms of the same word. They all share the same root word: talk. In spaCy we call token.lemma_ to get the lemmas for each word. Here we explored some of spaCy’s basic functionality, including tokenization, part-of-speech tagging, and lemmatization. These are just a few of the many tools the library has to offer. In future articles we will explore using some of the above methods to gain insights from text data.
[ { "code": null, "e": 291, "s": 172, "text": "A major challenge of text data is extracting meaningful patterns and using those patterns to find actionable insights." }, { "code": null, "e": 336, "s": 291, "text": "NLP can be thought of as a two part problem:" }, { "code": null, "e": 565, "s": 336, "text": "Processing. Converting the text data from its original form into a form the computer can understand. This includes data cleaning and feature extraction.Analysis. Using the processed data to extract insights and make predictions." }, { "code": null, "e": 718, "s": 565, "text": "Processing. Converting the text data from its original form into a form the computer can understand. This includes data cleaning and feature extraction." }, { "code": null, "e": 795, "s": 718, "text": "Analysis. Using the processed data to extract insights and make predictions." }, { "code": null, "e": 838, "s": 795, "text": "Here we will focus on the processing step." }, { "code": null, "e": 979, "s": 838, "text": "We’ll use a dataset created by scraping Twitter for Donald Trump tweets. A tutorial for creating your own Twitter dataset can be found here:" }, { "code": null, "e": 1002, "s": 979, "text": "towardsdatascience.com" }, { "code": null, "e": 1129, "s": 1002, "text": "And we will focus exclusively on spaCy “a free, open-source library for advanced Natural Language Processing (NLP) in Python.”" }, { "code": null, "e": 1282, "s": 1129, "text": "spaCy is a great choice for NLP tasks, especially for the processing text and has a ton of features and capabilities, many of which we’ll discuss below." }, { "code": null, "e": 1319, "s": 1282, "text": "The full notebook can be found here." }, { "code": null, "e": 1577, "s": 1319, "text": "A good definition of a token, according to researchgate.net, is “a string of contiguous characters between two spaces, or between a space and punctuation marks.” In English, tokens are usually individual words, but can also be punctuation marks and numbers." }, { "code": null, "e": 1759, "s": 1577, "text": "First we use the spacy.load() method to load a model package by and return the nlp object. Next we call nlp() on a string and spaCy tokenizes the text and creates a document object:" }, { "code": null, "e": 1942, "s": 1759, "text": "# Load model to return language objectnlp = spacy.load('en')# Calling nlp on our tweet texts to return a processed Doc for eachdf['doc'] = [nlp(text) for text in df.text]df.sample(3)" }, { "code": null, "e": 1991, "s": 1942, "text": "After tokenizing, we can do all sorts of things." }, { "code": null, "e": 2099, "s": 1991, "text": "We could do something basic like count the number of tokens per document and visualize it with a histogram:" }, { "code": null, "e": 2261, "s": 2099, "text": "# Sum the number of tokens in each Docdf['num_tokens'] = [len(token) for token in df.doc]# Visualize histogram of tokens per tweetg = sns.distplot(df.num_tokens)" }, { "code": null, "e": 2343, "s": 2261, "text": "Or we can utilize some of the many available token attributes spaCy has to offer." }, { "code": null, "e": 2414, "s": 2343, "text": "Spacy makes it easy to get part-of-speech tags using token attributes:" }, { "code": null, "e": 2516, "s": 2414, "text": "# Print sample of part-of-speech tagsfor token in sample_doc[0:10]: print (token.text, token.pos_)" }, { "code": null, "e": 2621, "s": 2516, "text": "In addition to the part-of-speech tags, we can also predict named entities that appear in our documents." }, { "code": null, "e": 2785, "s": 2621, "text": "According to Wikipedia, a named entity “is a real-world object, such as persons, locations, organizations, products, etc., that can be denoted with a proper name.”" }, { "code": null, "e": 2844, "s": 2785, "text": "for ent in sample_doc.ents: print(ent.text, ent.label_)" }, { "code": null, "e": 3006, "s": 2844, "text": "And, if we don’t know what the output means, spaCy has print(spacy.explain('NORP')) to learn that NORP stands for Nationalities or religious or political groups." }, { "code": null, "e": 3150, "s": 3006, "text": "In this case, the model is correctly predicts that “Democrats” is a NORP, but is incorrect in classifying “The Oval Office” as an organization." }, { "code": null, "e": 3217, "s": 3150, "text": "We can visualize named entities using spaCy’s visualizer displaCy:" }, { "code": null, "e": 3318, "s": 3217, "text": "# Visualize named entities with displacyspacy.displacy.render(sample_doc, style='ent', jupyter=True)" }, { "code": null, "e": 3385, "s": 3318, "text": "Lemmatization is the reduction of each word to its root, or lemma." }, { "code": null, "e": 3492, "s": 3385, "text": "For example, talk, talks, and talking are forms of the same word. They all share the same root word: talk." }, { "code": null, "e": 3555, "s": 3492, "text": "In spaCy we call token.lemma_ to get the lemmas for each word." }, { "code": null, "e": 3741, "s": 3555, "text": "Here we explored some of spaCy’s basic functionality, including tokenization, part-of-speech tagging, and lemmatization. These are just a few of the many tools the library has to offer." } ]
D3.js | d3.scaleIdentity() Function - GeeksforGeeks
12 Feb, 2021 The d3.scaleIdentity() function in D3.js is used to construct a new identity scale with the unit domain [0, 1] and the unit range [0, 1].Syntax: d3.scaleIdentity().domain(array of values).range(array of values); Parameters: This function does not accept any parameters.Return Value: This function returns the corresponding range for the domain’s value. Below program illustrate the d3.scaleIdentity() function in D3.js:Example: javascript <!DOCTYPE html><html> <head> <title></title> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> // Calling the scaleIdentity() function var A = d3.scaleIdentity() .domain([0, 1]) .range([0, 1]); // Getting the corresponding range for // the domain value console.log(A('0')); console.log(A('1')); </script></body> </html> Output: 0 1 Reference: https://devdocs.io/d3~5/d3-scale#scaleBand arorakashish0911 D3.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 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 Differences between Functional Components and Class Components in React How to redirect to another page in ReactJS ? Top 10 Angular Libraries For Web Developers How to Insert Form Data into Database using PHP ? How to execute PHP code using command line ? How to pass data from child component to its parent in ReactJS ?
[ { "code": null, "e": 24916, "s": 24888, "text": "\n12 Feb, 2021" }, { "code": null, "e": 25063, "s": 24916, "text": "The d3.scaleIdentity() function in D3.js is used to construct a new identity scale with the unit domain [0, 1] and the unit range [0, 1].Syntax: " }, { "code": null, "e": 25130, "s": 25063, "text": "d3.scaleIdentity().domain(array of values).range(array of values);" }, { "code": null, "e": 25348, "s": 25130, "text": "Parameters: This function does not accept any parameters.Return Value: This function returns the corresponding range for the domain’s value. Below program illustrate the d3.scaleIdentity() function in D3.js:Example: " }, { "code": null, "e": 25359, "s": 25348, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <head> <title></title> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> // Calling the scaleIdentity() function var A = d3.scaleIdentity() .domain([0, 1]) .range([0, 1]); // Getting the corresponding range for // the domain value console.log(A('0')); console.log(A('1')); </script></body> </html>", "e": 25786, "s": 25359, "text": null }, { "code": null, "e": 25796, "s": 25786, "text": "Output: " }, { "code": null, "e": 25800, "s": 25796, "text": "0\n1" }, { "code": null, "e": 25855, "s": 25800, "text": "Reference: https://devdocs.io/d3~5/d3-scale#scaleBand " }, { "code": null, "e": 25872, "s": 25855, "text": "arorakashish0911" }, { "code": null, "e": 25878, "s": 25872, "text": "D3.js" }, { "code": null, "e": 25895, "s": 25878, "text": "Web Technologies" }, { "code": null, "e": 25993, "s": 25895, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26002, "s": 25993, "text": "Comments" }, { "code": null, "e": 26015, "s": 26002, "text": "Old Comments" }, { "code": null, "e": 26057, "s": 26015, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26100, "s": 26057, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26145, "s": 26100, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26206, "s": 26145, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26278, "s": 26206, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26323, "s": 26278, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 26367, "s": 26323, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 26417, "s": 26367, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26462, "s": 26417, "text": "How to execute PHP code using command line ?" } ]
How to Build a Movie Recommendation System | by Ramya Vidiyala | Towards Data Science
Have you ever wondered how YouTube recommends content, or how Facebook recommends you, new friends? Perhaps you’ve noticed similar recommendations with LinkedIn connections, or how Amazon will recommend similar products while you’re browsing. All of these recommendations are made possible by the implementation of recommender systems. Recommender systems encompass a class of techniques and algorithms that can suggest “relevant” items to users. They predict future behavior based on past data through a multitude of techniques including matrix factorization. In this article, I’ll look at why we need recommender systems and the different types of users online. Then, I’ll show you how to build your own movie recommendation system using an open-source dataset. Why Do We Need Recommender Systems? Types of Recommender SystemsA) Content-Based Movie Recommendation SystemsB) Collaborative Filtering Movie Recommendation Systems The Dataset Designing a Movie Recommendation System ImplementationStep 1: Matrix Factorization-based AlgorithmStep 2: Creating Handcrafted FeaturesStep 3: Creating a Final Model for our Movie Recommendation System Performance Metrics Summary We now live in what some call the “era of abundance”. For any given product, there are sometimes thousands of options to choose from. Think of the examples above: streaming videos, social networking, online shopping; the list goes on. Recommender systems help to personalize a platform and help the user find something they like. The easiest and simplest way to do this is to recommend the most popular items. However, to really enhance the user experience through personalized recommendations, we need dedicated recommender systems. From a business standpoint, the more relevant products a user finds on the platform, the higher their engagement. This often results in increased revenue for the platform itself. Various sources say that as much as 35–40% of tech giants’ revenue comes from recommendations alone. Now that we understand the importance of recommender systems, let’s have a look at types of recommendation systems, then build our own with open-sourced data! Machine learning algorithms in recommender systems typically fit into two categories: content-based systems and collaborative filtering systems. Modern recommender systems combine both approaches. Let’s have a look at how they work using movie recommendation systems as a base. Content-based methods are based on the similarity of movie attributes. Using this type of recommender system, if a user watches one movie, similar movies are recommended. For example, if a user watches a comedy movie starring Adam Sandler, the system will recommend them movies in the same genre or starring the same actor, or both. With this in mind, the input for building a content-based recommender system is movie attributes. With collaborative filtering, the system is based on past interactions between users and movies. With this in mind, the input for a collaborative filtering system is made up of past data of user interactions with the movies they watch. For example, if user A watches M1, M2, and M3, and user B watches M1, M3, M4, we recommend M1 and M3 to a similar user C. You can see how this looks in the figure below for clearer reference. This data is stored in a matrix called the user-movie interactions matrix, where the rows are the users and the columns are the movies. Now, let’s implement our own movie recommendation system using the concepts discussed above. For our own system, we’ll use the open-source MovieLens dataset from GroupLens. This dataset contains 100K data points of various movies and users. We will use three columns from the data: userId movieId rating You can see a snapshot of the data in figure 3, below: To obtain recommendations for our users, we will predict their ratings for movies they haven’t watched yet. Movies are then indexed and suggested to users based on these predicted ratings. To do this, we will use past records of movies and user ratings to predict their future ratings. At this point, it’s worth mentioning that in the real world, we will likely encounter new users or movies without a history. Such situations are called cold start problems. Let’s take a brief look at how cold start problems can be addressed. Cold start problems can be handled by recommendations based on meta-information, such as: For new users, we can use their location, age, gender, browser, and user device to predict recommendations. For new movies, we can use genre, cast, and crew to recommend it to target users. For our recommender system, we’ll use both of the techniques mentioned above: content-based and collaborative filtering. To find the similarity between movies for our content based method, we’ll use a cosine similarity function. For our collaborative filtering method, we’ll use a matrix factorization technique. The first step towards this is creating a matrix factorization based model. We’ll use the output of this model and a few handcrafted features to provide inputs to the final model. The basic process will look like this: Step 1: Build a matrix factorization-based model Step 2: Create handcrafted features Step 3: Implement the final model We’ll look at these steps in greater detail below. Matrix factorization is a class of collaborative filtering algorithms used in recommender systems. This family of methods became widely known during the Netflix prize challenge due to how effective it was. Matrix factorization algorithms work by decomposing the user-movie interaction matrix into the product of two lower dimensionality rectangular matrices, say U and M. The decomposition is done in such a way that the product results in almost similar values to the user-movie interaction matrix. Here, U represents the user matrix, M represents the movie matrix, n is the number of users, and m is the number of movies. Each row of the user matrix represents a user and each column of the movie matrix represents a movie. Once we obtain the U and M matrices, based on the non-empty cells in the user-movie interaction matrix, we perform the product of U and M and predict the values of non-empty cells in the user-movie interaction matrix. To implement matrix factorization, we use a simple Python library named Surprise, which is for building and testing recommender systems. The data frame is converted into a train set, a format of data set to be accepted by the Surprise library. from surprise import SVDimport numpy as npimport surprisefrom surprise import Reader, Dataset# It is to specify how to read the data frame.reader = Reader(rating_scale=(1,5))# create the traindata from the data frametrain_data_mf = Dataset.load_from_df(train_data[['userId', 'movieId', 'rating']], reader)# build the train set from traindata. #It is of dataset format from surprise librarytrainset = train_data_mf.build_full_trainset()svd = SVD(n_factors=100, biased=True, random_state=15, verbose=True)svd.fit(trainset) Now the model is ready. We’ll store these predictions to pass to the final model as an additional feature. This will help us incorporate collaborative filtering into our system. #getting predictions of train settrain_preds = svd.test(trainset.build_testset())train_pred_mf = np.array([pred.est for pred in train_preds]) Note that we have to perform the above steps for test data also. Let’s convert the data in the data frame format into a user-movie interaction matrix. Matrices used in this type of problem are generally sparse because there’s a high chance users may only rate a few movies. The advantages of the sparse matrix format of data, also called CSR format, are as follows: efficient arithmetic operations: CSR + CSR, CSR * CSR, etc. efficient row slicing fast matrix-vector products scipy.sparse.csr_matrix is a utility function that efficiently converts the data frame into a sparse matrix. # Creating a sparse matrixtrain_sparse_matrix = sparse.csr_matrix((train_data.rating.values, (train_data.userId.values, train_data.movieId.values))) ‘train_sparse_matrix’ is the sparse matrix representation of the train_data data frame. We’ll create 3 sets of features using this sparse matrix: Features which represent global averagesFeatures which represent the top five similar usersFeatures which represent the top five similar movies Features which represent global averages Features which represent the top five similar users Features which represent the top five similar movies Let’s take a look at how to prepare each in more detail. The three global averages we’ll employ are: The average ratings of all movies given by all usersThe average ratings of a particular movie given by all usersThe average ratings of all movies given by a particular user The average ratings of all movies given by all users The average ratings of a particular movie given by all users The average ratings of all movies given by a particular user train_averages = dict()# get the global average of ratings in our train set.train_global_average = train_sparse_matrix.sum()/train_sparse_matrix.count_nonzero()train_averages['global'] = train_global_averagetrain_averagesOutput: {‘global’: 3.5199769425298757}Next, let’s create a function which takes the sparse matrix as input and gives the average ratings of a movie given by all users, and the average rating of all movies given by a single user.# get the user averages in dictionary (key: user_id/movie_id, value: avg rating)def get_average_ratings(sparse_matrix, of_users):# average ratings of user/axesax = 1 if of_users else 0 # 1 - User axes,0 - Movie axes# ".A1" is for converting Column_Matrix to 1-D numpy arraysum_of_ratings = sparse_matrix.sum(axis=ax).A1# Boolean matrix of ratings ( whether a user rated that movie or not)is_rated = sparse_matrix!=0# no of ratings that each user OR movie..no_of_ratings = is_rated.sum(axis=ax).A1# max_user and max_movie ids in sparse matrixu,m = sparse_matrix.shape# create a dictionary of users and their average ratings..average_ratings = { i : sum_of_ratings[i]/no_of_ratings[i]for i in range(u if of_users else m)if no_of_ratings[i] !=0}#return that dictionary of average ratingsreturn average_ratings The average rating is given by a user: train_averages['user'] = get_average_ratings(train_sparse_matrix, of_users=True) Average ratings are given for a movie: train_averages['movie'] = get_average_ratings(train_sparse_matrix, of_users=False) In this set of features, we will create the top 5 similar users who rated a particular movie. The similarity is calculated using the cosine similarity between the users. # compute the similar Users of the "user"user_sim = cosine_similarity(train_sparse_matrix[user], train_sparse_matrix).ravel()top_sim_users = user_sim.argsort()[::-1][1:] # we are ignoring 'The User' from its similar users.# get the ratings of most similar users for this movietop_ratings = train_sparse_matrix[top_sim_users, movie].toarray().ravel()# we will make it's length "5" by adding movie averages totop_sim_users_ratings = list(top_ratings[top_ratings != 0][:5])top_sim_users_ratings.extend([train_averages['movie'][movie]]*(5 -len(top_sim_users_ratings))) In this set of features, we obtain the top 5 similar movies rated by a particular user. This similarity is calculated using the cosine similarity between the movies. # compute the similar movies of the "movie"movie_sim = cosine_similarity(train_sparse_matrix[:,movie].T,train_sparse_matrix.T).ravel()top_sim_movies = movie_sim.argsort()[::-1][1:]# we are ignoring 'The User' from its similar users.# get the ratings of most similar movie rated by this usertop_ratings = train_sparse_matrix[user, top_sim_movies].toarray().ravel()# we will make it's length "5" by adding user averages totop_sim_movies_ratings = list(top_ratings[top_ratings != 0][:5])top_sim_movies_ratings.extend([train_averages['user'][user]]*(5-len(top_sim_movies_ratings))) We append all these features for each movie-user pair and create a data frame. Figure 5 is a snapshot of our data frame. Here’s a more detailed breakdown of its contents: GAvg: Average rating of all the ratings Similar users rating of this movie: sur1, sur2, sur3, sur4, sur5 ( top 5 similar users who rated that movie ) Similar movies rated by this user: smr1, smr2, smr3, smr4, smr5 ( top 5 similar movies rated by user) UAvg: User AVerage rating MAvg: Average rating of this movie rating: Rating of this movie by this user. Once we have these 13 features ready, we’ll add the Matrix Factorization output as the 14th feature. In Figure 6 you can see a snapshot of our data after adding the output from Step 1. The last column, named, mf_svd, is the additional column that contains the output of the model performed in Step 1. To create our final model, let’s use XGBoost, an optimized distributed gradient boosting library. # prepare train datax_train = final_data.drop(['user', 'movie','rating'], axis=1)y_train = final_data['rating']# initialize XGBoost modelxgb_model = xgb.XGBRegressor(silent=False, n_jobs=13,random_state=15,n_estimators=100)# fit the modelxgb_model.fit(x_train, y_train, eval_metric = 'rmse') There are two main ways to evaluate a recommender system’s performance: Root Mean Squared Error (RMSE) and Mean Absolute Percentage Error (MAPE). RMSE measures the squared loss, while MAPE measures the absolute loss. Lower values mean lower error rates and thus better performance. Both are good as they allow for easy interpretation. Let’s take a look at what each of them is: RMSE is the square root of the average of squared errors and is given by the below formula. Where:r is the actual rating,r^ is the predicted ratings andN is the total number of predictions MAPE measures the error in percentage terms. It is given by the formula below: Where:r is the actual rating,r^ is the predicted ratings andN is the total number of predictions #dictionaries for storing train and test resultstest_results = dict()# from the trained model, get the predictionsy_est_pred = xgb_model.predict(x_test)# get the rmse and mape of train datarmse = np.sqrt(np.mean([ (y_test.values[i] - y_test_pred[i])**2 for i inrange(len(y_test_pred)) ]))mape = np.mean(np.abs( (y_test.values- y_test_pred)/y_true.values )) * 100# store the results in train_results dictionarytest_results = {'rmse': rmse_test, 'mape' : mape_test, 'predictions' : y_test_pred} Our model resulted in 0.67 RMSE, and 19.86 MAPE on the unseen test data, which is a good-to-go model. An RMSE value of less than 2 is considered good, and a MAPE less than 25 is excellent. That said, this model can be further enhanced by adding features that would be recommended based on the top picks dependent on location or genre. We could also test the efficacy of our various models in real-time through A/B testing. In this article, we learned the importance of recommender systems, the types of recommender systems being implemented, and how to use matrix factorization to enhance a system. We then built a movie recommendation system that considers user-user similarity, movie-movie similarity, global averages, and matrix factorization. These concepts can be applied to any other user-item interactions systems. Thanks for reading! If you would like to experiment with this custom dataset yourself, you can download the annotated data on GroupLens and see my code at Github. Thanks for the read. This article is originally published here. I am going to write more beginner-friendly posts in the future too. Follow me up on Medium to be informed about them. I welcome feedback and can be reached out on Twitter ramya_vidiyala and LinkedIn RamyaVidiyala. Happy learning!
[ { "code": null, "e": 507, "s": 171, "text": "Have you ever wondered how YouTube recommends content, or how Facebook recommends you, new friends? Perhaps you’ve noticed similar recommendations with LinkedIn connections, or how Amazon will recommend similar products while you’re browsing. All of these recommendations are made possible by the implementation of recommender systems." }, { "code": null, "e": 732, "s": 507, "text": "Recommender systems encompass a class of techniques and algorithms that can suggest “relevant” items to users. They predict future behavior based on past data through a multitude of techniques including matrix factorization." }, { "code": null, "e": 935, "s": 732, "text": "In this article, I’ll look at why we need recommender systems and the different types of users online. Then, I’ll show you how to build your own movie recommendation system using an open-source dataset." }, { "code": null, "e": 971, "s": 935, "text": "Why Do We Need Recommender Systems?" }, { "code": null, "e": 1100, "s": 971, "text": "Types of Recommender SystemsA) Content-Based Movie Recommendation SystemsB) Collaborative Filtering Movie Recommendation Systems" }, { "code": null, "e": 1112, "s": 1100, "text": "The Dataset" }, { "code": null, "e": 1152, "s": 1112, "text": "Designing a Movie Recommendation System" }, { "code": null, "e": 1314, "s": 1152, "text": "ImplementationStep 1: Matrix Factorization-based AlgorithmStep 2: Creating Handcrafted FeaturesStep 3: Creating a Final Model for our Movie Recommendation System" }, { "code": null, "e": 1334, "s": 1314, "text": "Performance Metrics" }, { "code": null, "e": 1342, "s": 1334, "text": "Summary" }, { "code": null, "e": 1672, "s": 1342, "text": "We now live in what some call the “era of abundance”. For any given product, there are sometimes thousands of options to choose from. Think of the examples above: streaming videos, social networking, online shopping; the list goes on. Recommender systems help to personalize a platform and help the user find something they like." }, { "code": null, "e": 1876, "s": 1672, "text": "The easiest and simplest way to do this is to recommend the most popular items. However, to really enhance the user experience through personalized recommendations, we need dedicated recommender systems." }, { "code": null, "e": 2156, "s": 1876, "text": "From a business standpoint, the more relevant products a user finds on the platform, the higher their engagement. This often results in increased revenue for the platform itself. Various sources say that as much as 35–40% of tech giants’ revenue comes from recommendations alone." }, { "code": null, "e": 2315, "s": 2156, "text": "Now that we understand the importance of recommender systems, let’s have a look at types of recommendation systems, then build our own with open-sourced data!" }, { "code": null, "e": 2512, "s": 2315, "text": "Machine learning algorithms in recommender systems typically fit into two categories: content-based systems and collaborative filtering systems. Modern recommender systems combine both approaches." }, { "code": null, "e": 2593, "s": 2512, "text": "Let’s have a look at how they work using movie recommendation systems as a base." }, { "code": null, "e": 3024, "s": 2593, "text": "Content-based methods are based on the similarity of movie attributes. Using this type of recommender system, if a user watches one movie, similar movies are recommended. For example, if a user watches a comedy movie starring Adam Sandler, the system will recommend them movies in the same genre or starring the same actor, or both. With this in mind, the input for building a content-based recommender system is movie attributes." }, { "code": null, "e": 3260, "s": 3024, "text": "With collaborative filtering, the system is based on past interactions between users and movies. With this in mind, the input for a collaborative filtering system is made up of past data of user interactions with the movies they watch." }, { "code": null, "e": 3452, "s": 3260, "text": "For example, if user A watches M1, M2, and M3, and user B watches M1, M3, M4, we recommend M1 and M3 to a similar user C. You can see how this looks in the figure below for clearer reference." }, { "code": null, "e": 3588, "s": 3452, "text": "This data is stored in a matrix called the user-movie interactions matrix, where the rows are the users and the columns are the movies." }, { "code": null, "e": 3681, "s": 3588, "text": "Now, let’s implement our own movie recommendation system using the concepts discussed above." }, { "code": null, "e": 3829, "s": 3681, "text": "For our own system, we’ll use the open-source MovieLens dataset from GroupLens. This dataset contains 100K data points of various movies and users." }, { "code": null, "e": 3870, "s": 3829, "text": "We will use three columns from the data:" }, { "code": null, "e": 3877, "s": 3870, "text": "userId" }, { "code": null, "e": 3885, "s": 3877, "text": "movieId" }, { "code": null, "e": 3892, "s": 3885, "text": "rating" }, { "code": null, "e": 3947, "s": 3892, "text": "You can see a snapshot of the data in figure 3, below:" }, { "code": null, "e": 4136, "s": 3947, "text": "To obtain recommendations for our users, we will predict their ratings for movies they haven’t watched yet. Movies are then indexed and suggested to users based on these predicted ratings." }, { "code": null, "e": 4406, "s": 4136, "text": "To do this, we will use past records of movies and user ratings to predict their future ratings. At this point, it’s worth mentioning that in the real world, we will likely encounter new users or movies without a history. Such situations are called cold start problems." }, { "code": null, "e": 4475, "s": 4406, "text": "Let’s take a brief look at how cold start problems can be addressed." }, { "code": null, "e": 4565, "s": 4475, "text": "Cold start problems can be handled by recommendations based on meta-information, such as:" }, { "code": null, "e": 4673, "s": 4565, "text": "For new users, we can use their location, age, gender, browser, and user device to predict recommendations." }, { "code": null, "e": 4755, "s": 4673, "text": "For new movies, we can use genre, cast, and crew to recommend it to target users." }, { "code": null, "e": 5068, "s": 4755, "text": "For our recommender system, we’ll use both of the techniques mentioned above: content-based and collaborative filtering. To find the similarity between movies for our content based method, we’ll use a cosine similarity function. For our collaborative filtering method, we’ll use a matrix factorization technique." }, { "code": null, "e": 5287, "s": 5068, "text": "The first step towards this is creating a matrix factorization based model. We’ll use the output of this model and a few handcrafted features to provide inputs to the final model. The basic process will look like this:" }, { "code": null, "e": 5336, "s": 5287, "text": "Step 1: Build a matrix factorization-based model" }, { "code": null, "e": 5372, "s": 5336, "text": "Step 2: Create handcrafted features" }, { "code": null, "e": 5406, "s": 5372, "text": "Step 3: Implement the final model" }, { "code": null, "e": 5457, "s": 5406, "text": "We’ll look at these steps in greater detail below." }, { "code": null, "e": 5663, "s": 5457, "text": "Matrix factorization is a class of collaborative filtering algorithms used in recommender systems. This family of methods became widely known during the Netflix prize challenge due to how effective it was." }, { "code": null, "e": 6081, "s": 5663, "text": "Matrix factorization algorithms work by decomposing the user-movie interaction matrix into the product of two lower dimensionality rectangular matrices, say U and M. The decomposition is done in such a way that the product results in almost similar values to the user-movie interaction matrix. Here, U represents the user matrix, M represents the movie matrix, n is the number of users, and m is the number of movies." }, { "code": null, "e": 6183, "s": 6081, "text": "Each row of the user matrix represents a user and each column of the movie matrix represents a movie." }, { "code": null, "e": 6401, "s": 6183, "text": "Once we obtain the U and M matrices, based on the non-empty cells in the user-movie interaction matrix, we perform the product of U and M and predict the values of non-empty cells in the user-movie interaction matrix." }, { "code": null, "e": 6645, "s": 6401, "text": "To implement matrix factorization, we use a simple Python library named Surprise, which is for building and testing recommender systems. The data frame is converted into a train set, a format of data set to be accepted by the Surprise library." }, { "code": null, "e": 7166, "s": 6645, "text": "from surprise import SVDimport numpy as npimport surprisefrom surprise import Reader, Dataset# It is to specify how to read the data frame.reader = Reader(rating_scale=(1,5))# create the traindata from the data frametrain_data_mf = Dataset.load_from_df(train_data[['userId', 'movieId', 'rating']], reader)# build the train set from traindata. #It is of dataset format from surprise librarytrainset = train_data_mf.build_full_trainset()svd = SVD(n_factors=100, biased=True, random_state=15, verbose=True)svd.fit(trainset)" }, { "code": null, "e": 7344, "s": 7166, "text": "Now the model is ready. We’ll store these predictions to pass to the final model as an additional feature. This will help us incorporate collaborative filtering into our system." }, { "code": null, "e": 7486, "s": 7344, "text": "#getting predictions of train settrain_preds = svd.test(trainset.build_testset())train_pred_mf = np.array([pred.est for pred in train_preds])" }, { "code": null, "e": 7551, "s": 7486, "text": "Note that we have to perform the above steps for test data also." }, { "code": null, "e": 7760, "s": 7551, "text": "Let’s convert the data in the data frame format into a user-movie interaction matrix. Matrices used in this type of problem are generally sparse because there’s a high chance users may only rate a few movies." }, { "code": null, "e": 7852, "s": 7760, "text": "The advantages of the sparse matrix format of data, also called CSR format, are as follows:" }, { "code": null, "e": 7912, "s": 7852, "text": "efficient arithmetic operations: CSR + CSR, CSR * CSR, etc." }, { "code": null, "e": 7934, "s": 7912, "text": "efficient row slicing" }, { "code": null, "e": 7962, "s": 7934, "text": "fast matrix-vector products" }, { "code": null, "e": 8071, "s": 7962, "text": "scipy.sparse.csr_matrix is a utility function that efficiently converts the data frame into a sparse matrix." }, { "code": null, "e": 8220, "s": 8071, "text": "# Creating a sparse matrixtrain_sparse_matrix = sparse.csr_matrix((train_data.rating.values, (train_data.userId.values, train_data.movieId.values)))" }, { "code": null, "e": 8308, "s": 8220, "text": "‘train_sparse_matrix’ is the sparse matrix representation of the train_data data frame." }, { "code": null, "e": 8366, "s": 8308, "text": "We’ll create 3 sets of features using this sparse matrix:" }, { "code": null, "e": 8510, "s": 8366, "text": "Features which represent global averagesFeatures which represent the top five similar usersFeatures which represent the top five similar movies" }, { "code": null, "e": 8551, "s": 8510, "text": "Features which represent global averages" }, { "code": null, "e": 8603, "s": 8551, "text": "Features which represent the top five similar users" }, { "code": null, "e": 8656, "s": 8603, "text": "Features which represent the top five similar movies" }, { "code": null, "e": 8713, "s": 8656, "text": "Let’s take a look at how to prepare each in more detail." }, { "code": null, "e": 8757, "s": 8713, "text": "The three global averages we’ll employ are:" }, { "code": null, "e": 8930, "s": 8757, "text": "The average ratings of all movies given by all usersThe average ratings of a particular movie given by all usersThe average ratings of all movies given by a particular user" }, { "code": null, "e": 8983, "s": 8930, "text": "The average ratings of all movies given by all users" }, { "code": null, "e": 9044, "s": 8983, "text": "The average ratings of a particular movie given by all users" }, { "code": null, "e": 9105, "s": 9044, "text": "The average ratings of all movies given by a particular user" }, { "code": null, "e": 10361, "s": 9105, "text": "train_averages = dict()# get the global average of ratings in our train set.train_global_average = train_sparse_matrix.sum()/train_sparse_matrix.count_nonzero()train_averages['global'] = train_global_averagetrain_averagesOutput: {‘global’: 3.5199769425298757}Next, let’s create a function which takes the sparse matrix as input and gives the average ratings of a movie given by all users, and the average rating of all movies given by a single user.# get the user averages in dictionary (key: user_id/movie_id, value: avg rating)def get_average_ratings(sparse_matrix, of_users):# average ratings of user/axesax = 1 if of_users else 0 # 1 - User axes,0 - Movie axes# \".A1\" is for converting Column_Matrix to 1-D numpy arraysum_of_ratings = sparse_matrix.sum(axis=ax).A1# Boolean matrix of ratings ( whether a user rated that movie or not)is_rated = sparse_matrix!=0# no of ratings that each user OR movie..no_of_ratings = is_rated.sum(axis=ax).A1# max_user and max_movie ids in sparse matrixu,m = sparse_matrix.shape# create a dictionary of users and their average ratings..average_ratings = { i : sum_of_ratings[i]/no_of_ratings[i]for i in range(u if of_users else m)if no_of_ratings[i] !=0}#return that dictionary of average ratingsreturn average_ratings" }, { "code": null, "e": 10400, "s": 10361, "text": "The average rating is given by a user:" }, { "code": null, "e": 10481, "s": 10400, "text": "train_averages['user'] = get_average_ratings(train_sparse_matrix, of_users=True)" }, { "code": null, "e": 10520, "s": 10481, "text": "Average ratings are given for a movie:" }, { "code": null, "e": 10603, "s": 10520, "text": "train_averages['movie'] = get_average_ratings(train_sparse_matrix, of_users=False)" }, { "code": null, "e": 10773, "s": 10603, "text": "In this set of features, we will create the top 5 similar users who rated a particular movie. The similarity is calculated using the cosine similarity between the users." }, { "code": null, "e": 11338, "s": 10773, "text": "# compute the similar Users of the \"user\"user_sim = cosine_similarity(train_sparse_matrix[user], train_sparse_matrix).ravel()top_sim_users = user_sim.argsort()[::-1][1:] # we are ignoring 'The User' from its similar users.# get the ratings of most similar users for this movietop_ratings = train_sparse_matrix[top_sim_users, movie].toarray().ravel()# we will make it's length \"5\" by adding movie averages totop_sim_users_ratings = list(top_ratings[top_ratings != 0][:5])top_sim_users_ratings.extend([train_averages['movie'][movie]]*(5 -len(top_sim_users_ratings)))" }, { "code": null, "e": 11504, "s": 11338, "text": "In this set of features, we obtain the top 5 similar movies rated by a particular user. This similarity is calculated using the cosine similarity between the movies." }, { "code": null, "e": 12082, "s": 11504, "text": "# compute the similar movies of the \"movie\"movie_sim = cosine_similarity(train_sparse_matrix[:,movie].T,train_sparse_matrix.T).ravel()top_sim_movies = movie_sim.argsort()[::-1][1:]# we are ignoring 'The User' from its similar users.# get the ratings of most similar movie rated by this usertop_ratings = train_sparse_matrix[user, top_sim_movies].toarray().ravel()# we will make it's length \"5\" by adding user averages totop_sim_movies_ratings = list(top_ratings[top_ratings != 0][:5])top_sim_movies_ratings.extend([train_averages['user'][user]]*(5-len(top_sim_movies_ratings)))" }, { "code": null, "e": 12203, "s": 12082, "text": "We append all these features for each movie-user pair and create a data frame. Figure 5 is a snapshot of our data frame." }, { "code": null, "e": 12253, "s": 12203, "text": "Here’s a more detailed breakdown of its contents:" }, { "code": null, "e": 12293, "s": 12253, "text": "GAvg: Average rating of all the ratings" }, { "code": null, "e": 12403, "s": 12293, "text": "Similar users rating of this movie: sur1, sur2, sur3, sur4, sur5 ( top 5 similar users who rated that movie )" }, { "code": null, "e": 12505, "s": 12403, "text": "Similar movies rated by this user: smr1, smr2, smr3, smr4, smr5 ( top 5 similar movies rated by user)" }, { "code": null, "e": 12531, "s": 12505, "text": "UAvg: User AVerage rating" }, { "code": null, "e": 12566, "s": 12531, "text": "MAvg: Average rating of this movie" }, { "code": null, "e": 12609, "s": 12566, "text": "rating: Rating of this movie by this user." }, { "code": null, "e": 12794, "s": 12609, "text": "Once we have these 13 features ready, we’ll add the Matrix Factorization output as the 14th feature. In Figure 6 you can see a snapshot of our data after adding the output from Step 1." }, { "code": null, "e": 12910, "s": 12794, "text": "The last column, named, mf_svd, is the additional column that contains the output of the model performed in Step 1." }, { "code": null, "e": 13008, "s": 12910, "text": "To create our final model, let’s use XGBoost, an optimized distributed gradient boosting library." }, { "code": null, "e": 13300, "s": 13008, "text": "# prepare train datax_train = final_data.drop(['user', 'movie','rating'], axis=1)y_train = final_data['rating']# initialize XGBoost modelxgb_model = xgb.XGBRegressor(silent=False, n_jobs=13,random_state=15,n_estimators=100)# fit the modelxgb_model.fit(x_train, y_train, eval_metric = 'rmse')" }, { "code": null, "e": 13582, "s": 13300, "text": "There are two main ways to evaluate a recommender system’s performance: Root Mean Squared Error (RMSE) and Mean Absolute Percentage Error (MAPE). RMSE measures the squared loss, while MAPE measures the absolute loss. Lower values mean lower error rates and thus better performance." }, { "code": null, "e": 13678, "s": 13582, "text": "Both are good as they allow for easy interpretation. Let’s take a look at what each of them is:" }, { "code": null, "e": 13770, "s": 13678, "text": "RMSE is the square root of the average of squared errors and is given by the below formula." }, { "code": null, "e": 13867, "s": 13770, "text": "Where:r is the actual rating,r^ is the predicted ratings andN is the total number of predictions" }, { "code": null, "e": 13946, "s": 13867, "text": "MAPE measures the error in percentage terms. It is given by the formula below:" }, { "code": null, "e": 14043, "s": 13946, "text": "Where:r is the actual rating,r^ is the predicted ratings andN is the total number of predictions" }, { "code": null, "e": 14536, "s": 14043, "text": "#dictionaries for storing train and test resultstest_results = dict()# from the trained model, get the predictionsy_est_pred = xgb_model.predict(x_test)# get the rmse and mape of train datarmse = np.sqrt(np.mean([ (y_test.values[i] - y_test_pred[i])**2 for i inrange(len(y_test_pred)) ]))mape = np.mean(np.abs( (y_test.values- y_test_pred)/y_true.values )) * 100# store the results in train_results dictionarytest_results = {'rmse': rmse_test, 'mape' : mape_test, 'predictions' : y_test_pred}" }, { "code": null, "e": 14959, "s": 14536, "text": "Our model resulted in 0.67 RMSE, and 19.86 MAPE on the unseen test data, which is a good-to-go model. An RMSE value of less than 2 is considered good, and a MAPE less than 25 is excellent. That said, this model can be further enhanced by adding features that would be recommended based on the top picks dependent on location or genre. We could also test the efficacy of our various models in real-time through A/B testing." }, { "code": null, "e": 15358, "s": 14959, "text": "In this article, we learned the importance of recommender systems, the types of recommender systems being implemented, and how to use matrix factorization to enhance a system. We then built a movie recommendation system that considers user-user similarity, movie-movie similarity, global averages, and matrix factorization. These concepts can be applied to any other user-item interactions systems." }, { "code": null, "e": 15521, "s": 15358, "text": "Thanks for reading! If you would like to experiment with this custom dataset yourself, you can download the annotated data on GroupLens and see my code at Github." } ]
Tryit Editor v3.7
CSS Media Queries Tryit: Simple example of using media queries
[ { "code": null, "e": 27, "s": 9, "text": "CSS Media Queries" } ]
How to set the default value for an HTML <select> element ? - GeeksforGeeks
22 Nov, 2021 In this article, we will learn about setting the default value for the HTML select element, & will also understand their implementation through the examples. The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the ‘selected’ attribute on the required option. This is a boolean attribute. The option that is having the ‘selected’ attribute will be displayed by default on the dropdown list. We can even set the selected attribute after the page is loaded with the help of Javascript. Syntax: <option value="value" selected>Option Name</option> Example 1: This example illustrates the use of the selected attribute by specifying the pre-selected option that will be displayed first from the drop-down list. HTML <!DOCTYPE html><html> <head> <title>Set the default value for <select> element</title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b> How to set the default value for an HTML <select> element? </b> <p>The Starter option will be selected by default</p> <p>Choose your plan below:</p> <select name="plan" id="plan"> <option value="free">Free</option> <option value="starter" selected>Starter </option> <option value="professional">Professional</option> <option value="corporate">Corporate</option> </select></body> </html> Output: selected Attribute Example 2: This can also be used to add messages like ‘Select an Option’ in the list. This option would have the hidden and disabled attribute in addition to selected. HTML <!DOCTYPE html><html> <head> <title>Set the default value for <select> element</title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b>How to set the default value for an HTML <select> element? </b> <p>The Select an Option would be shown by default.</p> <p>Choose your plan below:</p> <select name="plan" id="plan"> <option value="none" selected disabled hidden>Select an Option</option> <option value="free">Free</option> <option value="starter">Starter </option> <option value="professional">Professional</option> <option value="corporate">Corporate</option> </select></body> </html> Output: Disabled selected Attribute HTML is the foundation of web pages, is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. bhaskargeeksforgeeks HTML-Questions Picked HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) How to Insert Form Data into Database using PHP ? HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS HTTP headers | Content-Type Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26261, "s": 26233, "text": "\n22 Nov, 2021" }, { "code": null, "e": 26419, "s": 26261, "text": "In this article, we will learn about setting the default value for the HTML select element, & will also understand their implementation through the examples." }, { "code": null, "e": 26910, "s": 26419, "text": "The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the ‘selected’ attribute on the required option. This is a boolean attribute. The option that is having the ‘selected’ attribute will be displayed by default on the dropdown list. We can even set the selected attribute after the page is loaded with the help of Javascript." }, { "code": null, "e": 26918, "s": 26910, "text": "Syntax:" }, { "code": null, "e": 26970, "s": 26918, "text": "<option value=\"value\" selected>Option Name</option>" }, { "code": null, "e": 27132, "s": 26970, "text": "Example 1: This example illustrates the use of the selected attribute by specifying the pre-selected option that will be displayed first from the drop-down list." }, { "code": null, "e": 27137, "s": 27132, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Set the default value for <select> element</title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b> How to set the default value for an HTML <select> element? </b> <p>The Starter option will be selected by default</p> <p>Choose your plan below:</p> <select name=\"plan\" id=\"plan\"> <option value=\"free\">Free</option> <option value=\"starter\" selected>Starter </option> <option value=\"professional\">Professional</option> <option value=\"corporate\">Corporate</option> </select></body> </html>", "e": 27747, "s": 27137, "text": null }, { "code": null, "e": 27755, "s": 27747, "text": "Output:" }, { "code": null, "e": 27774, "s": 27755, "text": "selected Attribute" }, { "code": null, "e": 27942, "s": 27774, "text": "Example 2: This can also be used to add messages like ‘Select an Option’ in the list. This option would have the hidden and disabled attribute in addition to selected." }, { "code": null, "e": 27947, "s": 27942, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Set the default value for <select> element</title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>How to set the default value for an HTML <select> element? </b> <p>The Select an Option would be shown by default.</p> <p>Choose your plan below:</p> <select name=\"plan\" id=\"plan\"> <option value=\"none\" selected disabled hidden>Select an Option</option> <option value=\"free\">Free</option> <option value=\"starter\">Starter </option> <option value=\"professional\">Professional</option> <option value=\"corporate\">Corporate</option> </select></body> </html>", "e": 28619, "s": 27947, "text": null }, { "code": null, "e": 28627, "s": 28619, "text": "Output:" }, { "code": null, "e": 28655, "s": 28627, "text": "Disabled selected Attribute" }, { "code": null, "e": 28851, "s": 28655, "text": "HTML is the foundation of web pages, is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 28872, "s": 28851, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28887, "s": 28872, "text": "HTML-Questions" }, { "code": null, "e": 28894, "s": 28887, "text": "Picked" }, { "code": null, "e": 28899, "s": 28894, "text": "HTML" }, { "code": null, "e": 28916, "s": 28899, "text": "Web Technologies" }, { "code": null, "e": 28943, "s": 28916, "text": "Web technologies Questions" }, { "code": null, "e": 28948, "s": 28943, "text": "HTML" }, { "code": null, "e": 29046, "s": 28948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29070, "s": 29046, "text": "REST API (Introduction)" }, { "code": null, "e": 29120, "s": 29070, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29161, "s": 29120, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 29198, "s": 29161, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29226, "s": 29198, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 29266, "s": 29226, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29299, "s": 29266, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29344, "s": 29299, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29387, "s": 29344, "text": "How to fetch data from an API in ReactJS ?" } ]
How to add a foreign key using ALTER in MySQL - GeeksforGeeks
08 Apr, 2021 In this article, we will discuss the overview of foreign keys and will discuss how to add a foreign key using ALTER in MySQL step by step. Let’s discuss it one by one. Foreign key : If an attribute is a primary key in one table but was not used as a primary key in another table then the attribute which is not a primary key in the other table is called a foreign key. If the changes made or any data is manipulated in any of the tables the changes get reflected in both the tables with the help of foreign key constraint. Steps to add a foreign key using ALTER in MySQL :Here let us see how to add an attribute of student which is the primary key in the student table as a foreign key in another table exam as follows. Step-1: Creating a database university :Here, you will see how to create a database in MySQL as follows. CREATE DATABASE university; Output : Step-2: Using the database university :Here, you will see how you can use the existing database which you have already created as follows. USE university; Output : Step-3: Creating a table student :Here, you will see how to create a table in MySQL as follows. CREATE TABLE student ( student_id INT PRIMARY KEY, student_name varchar, student_branch varchar ); Output : Step-4: Viewing the description of the table :Here, you will see how to verify the table as follows. DESCRIBE student; Output :Here, as you can see in the description the key column of student_id is PRI which means it is the primary key in that table student. Step-5: Creating another table exam :In this step, you will see one more table for reference. CREATE TABLE exam ( exam_id INT PRIMARY KEY, exam_name varchar(20) ); Output : Step-6: Viewing the description of the table :In this step, you can verify the table you have created. DESCRIBE exam; Output : Step-7: Adding another column student_id into the exam table :Here, you will see how to add another column student_id into the exam table as follows. ALTER TABLE exam ADD COLUMN student_id INT; Output : Step-8: Making a foreign key :Here, you will see how to make the student_id attribute foreign key in the exam table which is the primary key in the student table as follows. Syntax – ALTER TABLE table_name ADD FOREIGN KEY (column_name) REFERENCE table_name(Referencing column_name in table_name); Query – ALTER TABLE exam ADD FOREIGN KEY(student_id) REFERENCES student(student_id); Output : Step-9: Verifying the exam table : Here, you will see the description of the exam table as follows. DESCRIBE exam; Output :Now as you can see in the description of the table exam one more column student_id is added and in the Key column of description, the student_id has MUL which means it is a foreign key. DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n08 Apr, 2021" }, { "code": null, "e": 25681, "s": 25513, "text": "In this article, we will discuss the overview of foreign keys and will discuss how to add a foreign key using ALTER in MySQL step by step. Let’s discuss it one by one." }, { "code": null, "e": 26036, "s": 25681, "text": "Foreign key : If an attribute is a primary key in one table but was not used as a primary key in another table then the attribute which is not a primary key in the other table is called a foreign key. If the changes made or any data is manipulated in any of the tables the changes get reflected in both the tables with the help of foreign key constraint." }, { "code": null, "e": 26233, "s": 26036, "text": "Steps to add a foreign key using ALTER in MySQL :Here let us see how to add an attribute of student which is the primary key in the student table as a foreign key in another table exam as follows." }, { "code": null, "e": 26338, "s": 26233, "text": "Step-1: Creating a database university :Here, you will see how to create a database in MySQL as follows." }, { "code": null, "e": 26366, "s": 26338, "text": "CREATE DATABASE university;" }, { "code": null, "e": 26375, "s": 26366, "text": "Output :" }, { "code": null, "e": 26514, "s": 26375, "text": "Step-2: Using the database university :Here, you will see how you can use the existing database which you have already created as follows." }, { "code": null, "e": 26530, "s": 26514, "text": "USE university;" }, { "code": null, "e": 26539, "s": 26530, "text": "Output :" }, { "code": null, "e": 26635, "s": 26539, "text": "Step-3: Creating a table student :Here, you will see how to create a table in MySQL as follows." }, { "code": null, "e": 26752, "s": 26635, "text": " CREATE TABLE student\n (\n student_id INT PRIMARY KEY,\n student_name varchar,\n student_branch varchar\n );" }, { "code": null, "e": 26761, "s": 26752, "text": "Output :" }, { "code": null, "e": 26862, "s": 26761, "text": "Step-4: Viewing the description of the table :Here, you will see how to verify the table as follows." }, { "code": null, "e": 26880, "s": 26862, "text": "DESCRIBE student;" }, { "code": null, "e": 27021, "s": 26880, "text": "Output :Here, as you can see in the description the key column of student_id is PRI which means it is the primary key in that table student." }, { "code": null, "e": 27115, "s": 27021, "text": "Step-5: Creating another table exam :In this step, you will see one more table for reference." }, { "code": null, "e": 27195, "s": 27115, "text": "CREATE TABLE exam\n (\n exam_id INT PRIMARY KEY,\n exam_name varchar(20)\n );" }, { "code": null, "e": 27204, "s": 27195, "text": "Output :" }, { "code": null, "e": 27307, "s": 27204, "text": "Step-6: Viewing the description of the table :In this step, you can verify the table you have created." }, { "code": null, "e": 27322, "s": 27307, "text": "DESCRIBE exam;" }, { "code": null, "e": 27331, "s": 27322, "text": "Output :" }, { "code": null, "e": 27481, "s": 27331, "text": "Step-7: Adding another column student_id into the exam table :Here, you will see how to add another column student_id into the exam table as follows." }, { "code": null, "e": 27527, "s": 27481, "text": " ALTER TABLE exam\n ADD COLUMN student_id INT;" }, { "code": null, "e": 27536, "s": 27527, "text": "Output :" }, { "code": null, "e": 27710, "s": 27536, "text": "Step-8: Making a foreign key :Here, you will see how to make the student_id attribute foreign key in the exam table which is the primary key in the student table as follows." }, { "code": null, "e": 27719, "s": 27710, "text": "Syntax –" }, { "code": null, "e": 27833, "s": 27719, "text": "ALTER TABLE table_name\nADD FOREIGN KEY (column_name)\nREFERENCE table_name(Referencing column_name in table_name);" }, { "code": null, "e": 27841, "s": 27833, "text": "Query –" }, { "code": null, "e": 27918, "s": 27841, "text": "ALTER TABLE exam\nADD FOREIGN KEY(student_id)\nREFERENCES student(student_id);" }, { "code": null, "e": 27927, "s": 27918, "text": "Output :" }, { "code": null, "e": 28028, "s": 27927, "text": "Step-9: Verifying the exam table : Here, you will see the description of the exam table as follows. " }, { "code": null, "e": 28043, "s": 28028, "text": "DESCRIBE exam;" }, { "code": null, "e": 28237, "s": 28043, "text": "Output :Now as you can see in the description of the table exam one more column student_id is added and in the Key column of description, the student_id has MUL which means it is a foreign key." }, { "code": null, "e": 28246, "s": 28237, "text": "DBMS-SQL" }, { "code": null, "e": 28252, "s": 28246, "text": "mysql" }, { "code": null, "e": 28256, "s": 28252, "text": "SQL" }, { "code": null, "e": 28260, "s": 28256, "text": "SQL" }, { "code": null, "e": 28358, "s": 28260, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28424, "s": 28358, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28439, "s": 28424, "text": "SQL | Subquery" }, { "code": null, "e": 28496, "s": 28439, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28528, "s": 28496, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28606, "s": 28528, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 28623, "s": 28606, "text": "SQL using Python" }, { "code": null, "e": 28659, "s": 28623, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 28725, "s": 28659, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 28787, "s": 28725, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Python | Convert string enclosed list to list - GeeksforGeeks
20 May, 2019 Given a list enclosed within string (or quotes), write a Python program to convert the given string to list type. Examples: Input : "[0, 2, 9, 4, 8]" Output : [0, 2, 9, 4, 8] Input : "['x', 'y', 'z']" Output : ['x', 'y', 'z'] Approach #1 : Python eval() The eval() method parses the expression passed to this method and runs python expression (code) within the program. Here it takes the list enclosed within quotes as expression and runs it, and finally returns the list. # Python3 program to ways to convert # list enclosed within string to list def convert(lst): return eval(lst) # Driver codelst = "[0, 2, 9, 4, 8]"print(convert(lst)) [0, 2, 9, 4, 8] Approach #2 : Using literal_eval() literal_eval() function works same as eval() with the only difference that it raises an exception if the input isn’t a valid Python datatype, the code won’t be executed. # Python3 program to ways to convert # list enclosed within string to listfrom ast import literal_eval def convert(lst): return literal_eval(lst) # Driver codelst = "[0, 2, 9, 4, 8]"print(convert(lst)) [0, 2, 9, 4, 8] Approach #3 : Using json.loads() # Python3 program to ways to convert # list enclosed within string to listfrom json import loads def convert(lst): return loads(lst) # Driver codelst = "[0, 2, 9, 4, 8]"print(convert(lst)) [0, 2, 9, 4, 8] 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n20 May, 2019" }, { "code": null, "e": 25651, "s": 25537, "text": "Given a list enclosed within string (or quotes), write a Python program to convert the given string to list type." }, { "code": null, "e": 25661, "s": 25651, "text": "Examples:" }, { "code": null, "e": 25765, "s": 25661, "text": "Input : \"[0, 2, 9, 4, 8]\"\nOutput : [0, 2, 9, 4, 8]\n\nInput : \"['x', 'y', 'z']\"\nOutput : ['x', 'y', 'z']\n" }, { "code": null, "e": 25794, "s": 25765, "text": " Approach #1 : Python eval()" }, { "code": null, "e": 26013, "s": 25794, "text": "The eval() method parses the expression passed to this method and runs python expression (code) within the program. Here it takes the list enclosed within quotes as expression and runs it, and finally returns the list." }, { "code": "# Python3 program to ways to convert # list enclosed within string to list def convert(lst): return eval(lst) # Driver codelst = \"[0, 2, 9, 4, 8]\"print(convert(lst))", "e": 26188, "s": 26013, "text": null }, { "code": null, "e": 26205, "s": 26188, "text": "[0, 2, 9, 4, 8]\n" }, { "code": null, "e": 26241, "s": 26205, "text": " Approach #2 : Using literal_eval()" }, { "code": null, "e": 26411, "s": 26241, "text": "literal_eval() function works same as eval() with the only difference that it raises an exception if the input isn’t a valid Python datatype, the code won’t be executed." }, { "code": "# Python3 program to ways to convert # list enclosed within string to listfrom ast import literal_eval def convert(lst): return literal_eval(lst) # Driver codelst = \"[0, 2, 9, 4, 8]\"print(convert(lst))", "e": 26622, "s": 26411, "text": null }, { "code": null, "e": 26639, "s": 26622, "text": "[0, 2, 9, 4, 8]\n" }, { "code": null, "e": 26673, "s": 26639, "text": " Approach #3 : Using json.loads()" }, { "code": "# Python3 program to ways to convert # list enclosed within string to listfrom json import loads def convert(lst): return loads(lst) # Driver codelst = \"[0, 2, 9, 4, 8]\"print(convert(lst))", "e": 26871, "s": 26673, "text": null }, { "code": null, "e": 26888, "s": 26871, "text": "[0, 2, 9, 4, 8]\n" }, { "code": null, "e": 26909, "s": 26888, "text": "Python list-programs" }, { "code": null, "e": 26916, "s": 26909, "text": "Python" }, { "code": null, "e": 26932, "s": 26916, "text": "Python Programs" }, { "code": null, "e": 27030, "s": 26932, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27062, "s": 27030, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27104, "s": 27062, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27146, "s": 27104, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27173, "s": 27146, "text": "Python Classes and Objects" }, { "code": null, "e": 27229, "s": 27173, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27251, "s": 27229, "text": "Defaultdict in Python" }, { "code": null, "e": 27290, "s": 27251, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27336, "s": 27290, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27374, "s": 27336, "text": "Python | Convert a list to dictionary" } ]
Get the substring of the column in Pandas-Python - GeeksforGeeks
10 Jul, 2020 Now, we’ll see how we can get the substring for all the values of a column in a Pandas dataframe. This extraction can be very useful when working with data. For example, we have the first name and last name of different people in a column and we need to extract the first 3 letters of their name to create their username. Example 1:We can loop through the range of the column and calculate the substring for each value in the column. # importing pandas as pdimport pandas as pd # creating a dictionarydict = {'Name':["John Smith", "Mark Wellington", "Rosie Bates", "Emily Edward"]} # converting the dictionary to a# dataframedf = pd.DataFrame.from_dict(dict) # storing first 3 letters of namefor i in range(0, len(df)): df.iloc[i].Name = df.iloc[i].Name[:3] df Output: Note: For more information, refer Python Extracting Rows Using Pandas Example 2: In this example we’ll use str.slice(). # importing pandas as pdimport pandas as pd # creating a dictionarydict = {'Name':["John Smith", "Mark Wellington", "Rosie Bates", "Emily Edward"]} # converting the dictionary to a # dataframedf = pd.DataFrame.from_dict(dict) # storing first 3 letters of name as usernamedf['UserName'] = df['Name'].str.slice(0, 3) df Output: Example 3: We can also use the str accessor in a different way by using square brackets. # importing pandas as pdimport pandas as pd # creating a dictionarydict = {'Name':["John Smith", "Mark Wellington", "Rosie Bates", "Emily Edward"]} # converting the dictionary to a dataframedf = pd.DataFrame.from_dict(dict) # storing first 3 letters of name as usernamedf['UserName'] = df['Name'].str[:3] df Output: Example 4: We can also use str.extract for this task. In this example we’ll store last name of each person in “LastName” column. # importing pandas as pdimport pandas as pd # creating a dictionarydict = {'Name':["John Smith", "Mark Wellington", "Rosie Bates", "Emily Edward"]} # converting the dictionary to a dataframedf = pd.DataFrame.from_dict(dict) # storing lastname of each persondf['LastName'] = df.Name.str.extract(r'\b(\w+)$', expand = True) df Output: Python pandas-dataFrame Python-pandas 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 *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 26093, "s": 26065, "text": "\n10 Jul, 2020" }, { "code": null, "e": 26415, "s": 26093, "text": "Now, we’ll see how we can get the substring for all the values of a column in a Pandas dataframe. This extraction can be very useful when working with data. For example, we have the first name and last name of different people in a column and we need to extract the first 3 letters of their name to create their username." }, { "code": null, "e": 26527, "s": 26415, "text": "Example 1:We can loop through the range of the column and calculate the substring for each value in the column." }, { "code": "# importing pandas as pdimport pandas as pd # creating a dictionarydict = {'Name':[\"John Smith\", \"Mark Wellington\", \"Rosie Bates\", \"Emily Edward\"]} # converting the dictionary to a# dataframedf = pd.DataFrame.from_dict(dict) # storing first 3 letters of namefor i in range(0, len(df)): df.iloc[i].Name = df.iloc[i].Name[:3] df", "e": 26878, "s": 26527, "text": null }, { "code": null, "e": 26886, "s": 26878, "text": "Output:" }, { "code": null, "e": 26956, "s": 26886, "text": "Note: For more information, refer Python Extracting Rows Using Pandas" }, { "code": null, "e": 27006, "s": 26956, "text": "Example 2: In this example we’ll use str.slice()." }, { "code": "# importing pandas as pdimport pandas as pd # creating a dictionarydict = {'Name':[\"John Smith\", \"Mark Wellington\", \"Rosie Bates\", \"Emily Edward\"]} # converting the dictionary to a # dataframedf = pd.DataFrame.from_dict(dict) # storing first 3 letters of name as usernamedf['UserName'] = df['Name'].str.slice(0, 3) df", "e": 27344, "s": 27006, "text": null }, { "code": null, "e": 27352, "s": 27344, "text": "Output:" }, { "code": null, "e": 27441, "s": 27352, "text": "Example 3: We can also use the str accessor in a different way by using square brackets." }, { "code": "# importing pandas as pdimport pandas as pd # creating a dictionarydict = {'Name':[\"John Smith\", \"Mark Wellington\", \"Rosie Bates\", \"Emily Edward\"]} # converting the dictionary to a dataframedf = pd.DataFrame.from_dict(dict) # storing first 3 letters of name as usernamedf['UserName'] = df['Name'].str[:3] df", "e": 27770, "s": 27441, "text": null }, { "code": null, "e": 27778, "s": 27770, "text": "Output:" }, { "code": null, "e": 27907, "s": 27778, "text": "Example 4: We can also use str.extract for this task. In this example we’ll store last name of each person in “LastName” column." }, { "code": "# importing pandas as pdimport pandas as pd # creating a dictionarydict = {'Name':[\"John Smith\", \"Mark Wellington\", \"Rosie Bates\", \"Emily Edward\"]} # converting the dictionary to a dataframedf = pd.DataFrame.from_dict(dict) # storing lastname of each persondf['LastName'] = df.Name.str.extract(r'\\b(\\w+)$', expand = True) df", "e": 28289, "s": 27907, "text": null }, { "code": null, "e": 28297, "s": 28289, "text": "Output:" }, { "code": null, "e": 28321, "s": 28297, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28335, "s": 28321, "text": "Python-pandas" }, { "code": null, "e": 28342, "s": 28335, "text": "Python" }, { "code": null, "e": 28440, "s": 28342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28458, "s": 28440, "text": "Python Dictionary" }, { "code": null, "e": 28493, "s": 28458, "text": "Read a file line by line in Python" }, { "code": null, "e": 28525, "s": 28493, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28547, "s": 28525, "text": "Enumerate() in Python" }, { "code": null, "e": 28589, "s": 28547, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28619, "s": 28589, "text": "Iterate over a list in Python" }, { "code": null, "e": 28648, "s": 28619, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28692, "s": 28648, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28729, "s": 28692, "text": "Create a Pandas DataFrame from Lists" } ]
What is Elastic Stack and Elasticsearch? - GeeksforGeeks
28 Jul, 2020 Elastic Stack is a group of products that can reliably and securely take data from any source, in any format, then search, analyze, and visualize it in real-time. Elasticsearch is a distributed, RESTful search and analytics engine that can address a huge number of use cases. Also considered as the heart of the Elastic Stack, it centrally stores user data for high-efficiency search, excellent relevancy, and powerful analytics that is highly scalable. The core products that define an Elastic stack are listed below: Elastic Search – Search and analytics engine. Logstash – Data processing pipeline. Kibana – Dashboard to visualize data. All these three have their own significance and by combing these three you’ll get analysis and analytics of your data. As per the survey, Facebook generates 4 Petabytes data every day i.e 40 million GB. The Data, Now it’s a world of data. So We need a system that analyzes our data. There are two terms to understand: Analysis – In the analysis part, You’ll get results from the past data or the existing data that you have. Analytics – When you want to predict user requirements, You want graphs based visualization for better business clarity and also want to understand Data patterns. So these two most important tools for any business. You can achieve these by your Data. And with the help of these two, you can grow your business and clear business insights. Now, it’s How? Because to analyze this large data in less amount of time is not an easy task. Challenges and Solutions: What happens in very large companies you get data from different places in different formats. It can be JSON or XML whatever. So we need one mechanism to get whole data in one place and also in one format. So for that, we use Logstash. Now when we get data we need to arrange data in a systematic order, so we can evaluate the things very easily. Also, we want to analyze the data, in that case, First, go through with data very quickly. For that we have Elasticsearch. Elasticsearch is developed in Java and is released as open-source under the terms of the Apache License. Now after completing this, we need a visualization platform where we can show our data analytics. There Kibana comes into the picture. That is how the whole Elastic stack worked. For better Business insights. At first let’s download the three open-source software from their respective links [elasticsearch], [logstash], and [kibana]. Unzip the files and put all three in the project folder. Firstly, set up Kibana and Elasticsearch on the local system. We run Kibana by the following command in the bin folder of Kibana. bin\kibana Similarly, Elasticsearch is set up like this: bin\elasticsearch Now, in the two separate terminals, we can see both of the modules running. In order to check that the services are running open localhost:5621 for Kibana and localhost:9600 for Elasticsearch. Here, we are ready with set up for elastic stack. Now go to localhost:5621 and open dev tools here in the console. It is the place where you can write Elasticsearch queries. As we will talk more on Elasticsearch this time. Now we’ll see how exactly Elasticsearch Works. Before any operation, we have to index our Data. Once indexed in Elasticsearch, users can run complex queries against their data and use aggregations to retrieve complex summaries of their data. Elasticsearch stores data as JSON documents and uses Data structure as called an inverted index, which is designed to allow very fast full-text searches. An inverted index lists every unique word that appears in any document and identifies all of the documents each word occurs in. For a better understanding, we’ll divide Elasticsearch into several topics. Managing Documents Mappings Analysis Search Methodology Aggregation and Filters Cluster: In Elasticserach, we store our data in nodes, there can be n number of nodes in a machine. And each node is related to the cluster. So the Cluster is a set of nodes. Documents: You store your data as documents which are JSON objects. So how these data organized in the cluster? The answer is indices. In the world of relational databases, documents can be compared to a row in a table. Index: Elasticsearch Indices are logical partitions of documents and can be compared to a database in the world of relational databases. Types: Each index has one or more mapping types that are used to divide documents into a logical group. It can be compared to a table in the world of relational databases. Every document is stored as an index. The index you can say is the collection of documents. That has similar characteristics for instance, the Department will have A index, and Employees have B index i.e they are logically related. Sharding a) Sharding is just a way to divided index into smaller pieces. b) Each piece is known as a shard. c) Sharding is done at an index level.Shard is just like an index. For scalability. With sharding, you can store billions of documents within the one index. There are also Replicas as well but for now, it is well enough for us to start and understand Elasticsearch. So let’s move further towards building and search engine. Before that, get the Elasticserach package manager. npm -i elasticsearch Step 1: Link Your application to Elasticsearch by following. javascript var elasticsearch = require('elasticsearch');var client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace', // use the same version // of your Elasticsearch instance apiVersion: '7.2', }); module.exports = client; Step 2: Create Index for an eg We create an index as gov. javascript // Write Javascript code herevar client = require('./connection.js'); client.indices.create({ index: 'gov'},function(err,resp,status) { if(err) { console.log(err); } else { console.log("create",resp); }}); Step 3: Now we will add documents to index gov and in index gov, there is a type called constituencies. You can relate as there is a database called gov and the table is constituencies. javascript // Write Javascript code herevar client = require('./connection.js'); client.index({ index: 'gov', id: '1', type: 'constituencies', body: { "ConstituencyName": "Ipswich", "ConstituencyID": "E14000761", "ConstituencyType": "Borough", "Electorate": 74499, "ValidVotes": 48694, }},function(err,resp,status) { console.log(resp);}); Mapping is the process of defining document, and its fields. Just like defining table-schema in RDBMS. Step 4: Now we will define mappings to index gov type constituencies. javascript var client = require('./connection.js'); <code>client.indices.putMapping({ index: 'gov', type: 'constituencies', body: { properties: { 'constituencyname': { // type is a required // attribute if index // is specified 'type': 'string', 'index': false }, 'electorate': { 'type': 'integer' }, 'validvotes': { 'type': 'integer' } } }},function(err,resp,status){ if (err) { console.log(err); } else { console.log(resp); }}); Text analysis is the process of converting unstructured text, like the body of an email or a product description, into a structured format that’s optimized for search. Elasticsearch performs text analysis when indexing or searching text fields. That we have defined in mappings. This is the key factor for the Search-engine. By default, Elasticsearch uses the standard analyzer for all text analysis. The standard analyzer gives you out-of-the-box support for most natural languages and use cases. If you choose to use the standard analyzer as-is, no further configuration is needed. You can also create your own custom analyzer. There are different types of queries that you can apply to Elasticsearch. By that, you will get results accordingly. Here I’ll give a basic example of a query. Simplest query, which matches all documents. javascript // Write Javascript code herevar client = require('./connection.js'); client.search({ index: 'gov', type: 'constituencies', body: { query: { match: { "constituencyname": "Harwich" } }, }},function (error, response,status) { if (error){ console.log("search error: "+error) } else { console.log("--- Response ---"); console.log(response); console.log("--- Hits ---"); response.hits.hits.forEach(function(hit){ console.log(hit); }) }}); client.search({ index: 'gov', type: 'petitions', body: { query: { match: { 'action': 'Ipswich' } }, },function (error, response,status) { if (error){ console.log("search error: "+error) } else { console.log("--- Response ---"); console.log(response); console.log("--- Hits ---"); response.hits.hits.forEach(function(hit){ console.log(hit); }) } }); Compound queries: Compound queries wrap other compound or leaf queries, either to combine their results and scores, to change their behavior, or to switch from query to filter context. The default query for combining multiple leaf or compound query clauses, as must, should, must_not, or filter clauses. The must and should clauses have their scores combined. Full-text queries: The full-text queries enable you to search analyzed text fields such as the body of an email. The query string is processed using the same analyzer that was applied to the field during indexing. It will analyze your input. If the given input is not exact but still, you’ll get a result. Joining queries: Performing full SQL-style joins in a distributed system like Elasticsearch is prohibitively expensive. Instead, Elasticsearch offers two forms of join which are designed to scale horizontally. a) nested query b) has_child and has_parent queries Specialized queries: This group contains queries which do not fit into the other groups, It’s found that documents which are similar in nature, pinned queries also there are many more please check out its documentation. Term-level queries: You can use term-level queries to find documents based on precise values in structured data. Examples of structured data include date ranges, IP addresses, prices, or product IDs.Unlike full-text queries, term-level queries do not analyze search terms. Instead, term-level queries match the exact terms stored in a field. It will find the exact match of input whereas in full-text first it will be analyzed then search so that is a big difference between Term-level and Full-text query. In a filter context, a query clause answers the question “Does this document match this query clause?” The answer is a simple Yes or No – no scores are calculated. Filter context is mostly used for filtering structured data, e.g. Does this timestamp fall into the range of 2015 to 2016? Is the status field set to “published”? Frequently used filters will be cached automatically by Elasticsearch, to speed up performance. Filter context is in effect whenever a query clause is passed to a filter parameter, such as the filter or must_not parameters in the bool query, the filter parameter in the constant_score query, or the filter aggregation. With aggregation is more like as it is in RDBMS you will find Avg, Sum, and much data insights using complex queries. Elastic Stack is a very important Tech to learn. You will apply this in any of your projects and the ELK Stack is most commonly used as a log analytics tool. Its popularity lies in the fact that it provides a reliable and relatively scalable way to aggregate data from multiple sources, there are still Many things remain but after this, you can start with Elasticsearch. Advanced Computer Subject GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Markov Decision Process Fuzzy Logic | Introduction Q-Learning in Python Principal Component Analysis with Python Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... DSA Sheet by Love Babbar Socket Programming in C/C++ GET and POST requests using Python Must Do Coding Questions for Product Based Companies
[ { "code": null, "e": 25493, "s": 25465, "text": "\n28 Jul, 2020" }, { "code": null, "e": 25947, "s": 25493, "text": "Elastic Stack is a group of products that can reliably and securely take data from any source, in any format, then search, analyze, and visualize it in real-time. Elasticsearch is a distributed, RESTful search and analytics engine that can address a huge number of use cases. Also considered as the heart of the Elastic Stack, it centrally stores user data for high-efficiency search, excellent relevancy, and powerful analytics that is highly scalable." }, { "code": null, "e": 26012, "s": 25947, "text": "The core products that define an Elastic stack are listed below:" }, { "code": null, "e": 26058, "s": 26012, "text": "Elastic Search – Search and analytics engine." }, { "code": null, "e": 26095, "s": 26058, "text": "Logstash – Data processing pipeline." }, { "code": null, "e": 26135, "s": 26095, "text": "Kibana – Dashboard to visualize data. " }, { "code": null, "e": 26254, "s": 26135, "text": "All these three have their own significance and by combing these three you’ll get analysis and analytics of your data." }, { "code": null, "e": 26453, "s": 26254, "text": "As per the survey, Facebook generates 4 Petabytes data every day i.e 40 million GB. The Data, Now it’s a world of data. So We need a system that analyzes our data. There are two terms to understand:" }, { "code": null, "e": 26560, "s": 26453, "text": "Analysis – In the analysis part, You’ll get results from the past data or the existing data that you have." }, { "code": null, "e": 26724, "s": 26560, "text": "Analytics – When you want to predict user requirements, You want graphs based visualization for better business clarity and also want to understand Data patterns. " }, { "code": null, "e": 26995, "s": 26724, "text": "So these two most important tools for any business. You can achieve these by your Data. And with the help of these two, you can grow your business and clear business insights. Now, it’s How? Because to analyze this large data in less amount of time is not an easy task. " }, { "code": null, "e": 27022, "s": 26995, "text": "Challenges and Solutions: " }, { "code": null, "e": 27259, "s": 27022, "text": "What happens in very large companies you get data from different places in different formats. It can be JSON or XML whatever. So we need one mechanism to get whole data in one place and also in one format. So for that, we use Logstash. " }, { "code": null, "e": 27599, "s": 27259, "text": "Now when we get data we need to arrange data in a systematic order, so we can evaluate the things very easily. Also, we want to analyze the data, in that case, First, go through with data very quickly. For that we have Elasticsearch. Elasticsearch is developed in Java and is released as open-source under the terms of the Apache License. " }, { "code": null, "e": 27809, "s": 27599, "text": "Now after completing this, we need a visualization platform where we can show our data analytics. There Kibana comes into the picture. That is how the whole Elastic stack worked. For better Business insights. " }, { "code": null, "e": 28122, "s": 27809, "text": "At first let’s download the three open-source software from their respective links [elasticsearch], [logstash], and [kibana]. Unzip the files and put all three in the project folder. Firstly, set up Kibana and Elasticsearch on the local system. We run Kibana by the following command in the bin folder of Kibana." }, { "code": null, "e": 28133, "s": 28122, "text": "bin\\kibana" }, { "code": null, "e": 28180, "s": 28133, "text": "Similarly, Elasticsearch is set up like this: " }, { "code": null, "e": 28199, "s": 28180, "text": "bin\\elasticsearch\n" }, { "code": null, "e": 28393, "s": 28199, "text": "Now, in the two separate terminals, we can see both of the modules running. In order to check that the services are running open localhost:5621 for Kibana and localhost:9600 for Elasticsearch. " }, { "code": null, "e": 28663, "s": 28393, "text": "Here, we are ready with set up for elastic stack. Now go to localhost:5621 and open dev tools here in the console. It is the place where you can write Elasticsearch queries. As we will talk more on Elasticsearch this time. Now we’ll see how exactly Elasticsearch Works." }, { "code": null, "e": 29216, "s": 28663, "text": "Before any operation, we have to index our Data. Once indexed in Elasticsearch, users can run complex queries against their data and use aggregations to retrieve complex summaries of their data. Elasticsearch stores data as JSON documents and uses Data structure as called an inverted index, which is designed to allow very fast full-text searches. An inverted index lists every unique word that appears in any document and identifies all of the documents each word occurs in. For a better understanding, we’ll divide Elasticsearch into several topics." }, { "code": null, "e": 29236, "s": 29216, "text": "Managing Documents " }, { "code": null, "e": 29246, "s": 29236, "text": "Mappings " }, { "code": null, "e": 29256, "s": 29246, "text": "Analysis " }, { "code": null, "e": 29276, "s": 29256, "text": "Search Methodology " }, { "code": null, "e": 29300, "s": 29276, "text": "Aggregation and Filters" }, { "code": null, "e": 29476, "s": 29300, "text": "Cluster: In Elasticserach, we store our data in nodes, there can be n number of nodes in a machine. And each node is related to the cluster. So the Cluster is a set of nodes. " }, { "code": null, "e": 29697, "s": 29476, "text": "Documents: You store your data as documents which are JSON objects. So how these data organized in the cluster? The answer is indices. In the world of relational databases, documents can be compared to a row in a table. " }, { "code": null, "e": 29835, "s": 29697, "text": "Index: Elasticsearch Indices are logical partitions of documents and can be compared to a database in the world of relational databases. " }, { "code": null, "e": 30240, "s": 29835, "text": "Types: Each index has one or more mapping types that are used to divide documents into a logical group. It can be compared to a table in the world of relational databases. Every document is stored as an index. The index you can say is the collection of documents. That has similar characteristics for instance, the Department will have A index, and Employees have B index i.e they are logically related. " }, { "code": null, "e": 30672, "s": 30240, "text": "Sharding a) Sharding is just a way to divided index into smaller pieces. b) Each piece is known as a shard. c) Sharding is done at an index level.Shard is just like an index. For scalability. With sharding, you can store billions of documents within the one index. There are also Replicas as well but for now, it is well enough for us to start and understand Elasticsearch. So let’s move further towards building and search engine." }, { "code": null, "e": 30725, "s": 30672, "text": "Before that, get the Elasticserach package manager. " }, { "code": null, "e": 30748, "s": 30725, "text": "npm -i elasticsearch \n" }, { "code": null, "e": 30810, "s": 30748, "text": "Step 1: Link Your application to Elasticsearch by following. " }, { "code": null, "e": 30821, "s": 30810, "text": "javascript" }, { "code": "var elasticsearch = require('elasticsearch');var client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace', // use the same version // of your Elasticsearch instance apiVersion: '7.2', }); module.exports = client; ", "e": 31058, "s": 30821, "text": null }, { "code": null, "e": 31120, "s": 31060, "text": "Step 2: Create Index for an eg We create an index as gov. " }, { "code": null, "e": 31131, "s": 31120, "text": "javascript" }, { "code": "// Write Javascript code herevar client = require('./connection.js'); client.indices.create({ index: 'gov'},function(err,resp,status) { if(err) { console.log(err); } else { console.log(\"create\",resp); }});", "e": 31351, "s": 31131, "text": null }, { "code": null, "e": 31541, "s": 31353, "text": "Step 3: Now we will add documents to index gov and in index gov, there is a type called constituencies. You can relate as there is a database called gov and the table is constituencies. " }, { "code": null, "e": 31552, "s": 31541, "text": "javascript" }, { "code": "// Write Javascript code herevar client = require('./connection.js'); client.index({ index: 'gov', id: '1', type: 'constituencies', body: { \"ConstituencyName\": \"Ipswich\", \"ConstituencyID\": \"E14000761\", \"ConstituencyType\": \"Borough\", \"Electorate\": 74499, \"ValidVotes\": 48694, }},function(err,resp,status) { console.log(resp);});", "e": 31906, "s": 31552, "text": null }, { "code": null, "e": 32010, "s": 31906, "text": "Mapping is the process of defining document, and its fields. Just like defining table-schema in RDBMS. " }, { "code": null, "e": 32082, "s": 32010, "text": "Step 4: Now we will define mappings to index gov type constituencies. " }, { "code": null, "e": 32093, "s": 32082, "text": "javascript" }, { "code": "var client = require('./connection.js'); <code>client.indices.putMapping({ index: 'gov', type: 'constituencies', body: { properties: { 'constituencyname': { // type is a required // attribute if index // is specified 'type': 'string', 'index': false }, 'electorate': { 'type': 'integer' }, 'validvotes': { 'type': 'integer' } } }},function(err,resp,status){ if (err) { console.log(err); } else { console.log(resp); }});", "e": 32632, "s": 32093, "text": null }, { "code": null, "e": 33263, "s": 32632, "text": "Text analysis is the process of converting unstructured text, like the body of an email or a product description, into a structured format that’s optimized for search. Elasticsearch performs text analysis when indexing or searching text fields. That we have defined in mappings. This is the key factor for the Search-engine. By default, Elasticsearch uses the standard analyzer for all text analysis. The standard analyzer gives you out-of-the-box support for most natural languages and use cases. If you choose to use the standard analyzer as-is, no further configuration is needed. You can also create your own custom analyzer. " }, { "code": null, "e": 33470, "s": 33263, "text": "There are different types of queries that you can apply to Elasticsearch. By that, you will get results accordingly. Here I’ll give a basic example of a query. Simplest query, which matches all documents. " }, { "code": null, "e": 33481, "s": 33470, "text": "javascript" }, { "code": "// Write Javascript code herevar client = require('./connection.js'); client.search({ index: 'gov', type: 'constituencies', body: { query: { match: { \"constituencyname\": \"Harwich\" } }, }},function (error, response,status) { if (error){ console.log(\"search error: \"+error) } else { console.log(\"--- Response ---\"); console.log(response); console.log(\"--- Hits ---\"); response.hits.hits.forEach(function(hit){ console.log(hit); }) }}); client.search({ index: 'gov', type: 'petitions', body: { query: { match: { 'action': 'Ipswich' } }, },function (error, response,status) { if (error){ console.log(\"search error: \"+error) } else { console.log(\"--- Response ---\"); console.log(response); console.log(\"--- Hits ---\"); response.hits.hits.forEach(function(hit){ console.log(hit); }) } });", "e": 34439, "s": 33481, "text": null }, { "code": null, "e": 34800, "s": 34439, "text": "Compound queries: Compound queries wrap other compound or leaf queries, either to combine their results and scores, to change their behavior, or to switch from query to filter context. The default query for combining multiple leaf or compound query clauses, as must, should, must_not, or filter clauses. The must and should clauses have their scores combined. " }, { "code": null, "e": 35107, "s": 34800, "text": "Full-text queries: The full-text queries enable you to search analyzed text fields such as the body of an email. The query string is processed using the same analyzer that was applied to the field during indexing. It will analyze your input. If the given input is not exact but still, you’ll get a result. " }, { "code": null, "e": 35371, "s": 35107, "text": "Joining queries: Performing full SQL-style joins in a distributed system like Elasticsearch is prohibitively expensive. Instead, Elasticsearch offers two forms of join which are designed to scale horizontally. a) nested query b) has_child and has_parent queries " }, { "code": null, "e": 35592, "s": 35371, "text": "Specialized queries: This group contains queries which do not fit into the other groups, It’s found that documents which are similar in nature, pinned queries also there are many more please check out its documentation. " }, { "code": null, "e": 36099, "s": 35592, "text": "Term-level queries: You can use term-level queries to find documents based on precise values in structured data. Examples of structured data include date ranges, IP addresses, prices, or product IDs.Unlike full-text queries, term-level queries do not analyze search terms. Instead, term-level queries match the exact terms stored in a field. It will find the exact match of input whereas in full-text first it will be analyzed then search so that is a big difference between Term-level and Full-text query." }, { "code": null, "e": 36329, "s": 36099, "text": "In a filter context, a query clause answers the question “Does this document match this query clause?” The answer is a simple Yes or No – no scores are calculated. Filter context is mostly used for filtering structured data, e.g." }, { "code": null, "e": 36387, "s": 36329, "text": "Does this timestamp fall into the range of 2015 to 2016? " }, { "code": null, "e": 36427, "s": 36387, "text": "Is the status field set to “published”?" }, { "code": null, "e": 36864, "s": 36427, "text": "Frequently used filters will be cached automatically by Elasticsearch, to speed up performance. Filter context is in effect whenever a query clause is passed to a filter parameter, such as the filter or must_not parameters in the bool query, the filter parameter in the constant_score query, or the filter aggregation. With aggregation is more like as it is in RDBMS you will find Avg, Sum, and much data insights using complex queries." }, { "code": null, "e": 37236, "s": 36864, "text": "Elastic Stack is a very important Tech to learn. You will apply this in any of your projects and the ELK Stack is most commonly used as a log analytics tool. Its popularity lies in the fact that it provides a reliable and relatively scalable way to aggregate data from multiple sources, there are still Many things remain but after this, you can start with Elasticsearch." }, { "code": null, "e": 37262, "s": 37236, "text": "Advanced Computer Subject" }, { "code": null, "e": 37268, "s": 37262, "text": "GBlog" }, { "code": null, "e": 37366, "s": 37268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37410, "s": 37366, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 37434, "s": 37410, "text": "Markov Decision Process" }, { "code": null, "e": 37461, "s": 37434, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 37482, "s": 37461, "text": "Q-Learning in Python" }, { "code": null, "e": 37523, "s": 37482, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 37597, "s": 37523, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 37622, "s": 37597, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37650, "s": 37622, "text": "Socket Programming in C/C++" }, { "code": null, "e": 37685, "s": 37650, "text": "GET and POST requests using Python" } ]
SQL | Create Table Extension - GeeksforGeeks
21 Mar, 2018 SQL provides an extension for CREATE TABLE clause that creates a new table with the same schema of some existing table in the database. It is used to store the result of complex queries temporarily in a new table. The new table created has the same schema as the referencing table. By default, the new table has the same column names and the data type of the referencing table. Syntax: CREATE TABLE newTable LIKE pets Example: CREATE TABLE newTable as (SELECT * FROM pets WHERE pets.BREED = 'German Shepherd') Queries pets table: Query 1: CREATE TABLE newTable LIKE pets; SELECT * FROM newTable where newTable.GENDER = 'Female'; Output: Explanation: The newTable created is a copy of pets table. So, selecting female pets from newTable returns only two rows in which the pet is a female.Query 2 : CREATE TABLE newTable as (SELECT * FROM pets WHERE pets.BREED = 'German Shepherd'); SELECT * from newTable; Output: Explanation: First the inner query is evaluated and the results are stored in a new temporary relation. Following this, the outer query is evaluated which create newTable as add the output of inner query to newTable. References : Database System Concepts 6th Edition by Silberschatz This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SQL-Clauses-Operators SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL SQL Interview Questions How to Update Multiple Columns in Single Update Statement in SQL? Difference between DDL and DML in DBMS SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL - ORDER BY How to Create a Table With Multiple Foreign Keys in SQL?
[ { "code": null, "e": 25055, "s": 25027, "text": "\n21 Mar, 2018" }, { "code": null, "e": 25191, "s": 25055, "text": "SQL provides an extension for CREATE TABLE clause that creates a new table with the same schema of some existing table in the database." }, { "code": null, "e": 25269, "s": 25191, "text": "It is used to store the result of complex queries temporarily in a new table." }, { "code": null, "e": 25337, "s": 25269, "text": "The new table created has the same schema as the referencing table." }, { "code": null, "e": 25433, "s": 25337, "text": "By default, the new table has the same column names and the data type of the referencing table." }, { "code": null, "e": 25441, "s": 25433, "text": "Syntax:" }, { "code": null, "e": 25473, "s": 25441, "text": "CREATE TABLE newTable LIKE pets" }, { "code": null, "e": 25482, "s": 25473, "text": "Example:" }, { "code": null, "e": 25605, "s": 25482, "text": "CREATE TABLE newTable as\n (SELECT * \n FROM pets\n WHERE pets.BREED = 'German Shepherd')\n" }, { "code": null, "e": 25613, "s": 25605, "text": "Queries" }, { "code": null, "e": 25625, "s": 25613, "text": "pets table:" }, { "code": null, "e": 25634, "s": 25625, "text": "Query 1:" }, { "code": null, "e": 25726, "s": 25634, "text": "CREATE TABLE newTable LIKE pets;\nSELECT * \nFROM newTable \nwhere newTable.GENDER = 'Female';" }, { "code": null, "e": 25734, "s": 25726, "text": "Output:" }, { "code": null, "e": 25894, "s": 25734, "text": "Explanation: The newTable created is a copy of pets table. So, selecting female pets from newTable returns only two rows in which the pet is a female.Query 2 :" }, { "code": null, "e": 26042, "s": 25894, "text": "CREATE TABLE newTable as\n (SELECT * \n FROM pets\n WHERE pets.BREED = 'German Shepherd');\nSELECT * from newTable;\n" }, { "code": null, "e": 26050, "s": 26042, "text": "Output:" }, { "code": null, "e": 26267, "s": 26050, "text": "Explanation: First the inner query is evaluated and the results are stored in a new temporary relation. Following this, the outer query is evaluated which create newTable as add the output of inner query to newTable." }, { "code": null, "e": 26333, "s": 26267, "text": "References : Database System Concepts 6th Edition by Silberschatz" }, { "code": null, "e": 26633, "s": 26333, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26758, "s": 26633, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26780, "s": 26758, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 26784, "s": 26780, "text": "SQL" }, { "code": null, "e": 26788, "s": 26784, "text": "SQL" }, { "code": null, "e": 26886, "s": 26788, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26897, "s": 26886, "text": "CTE in SQL" }, { "code": null, "e": 26921, "s": 26897, "text": "SQL Interview Questions" }, { "code": null, "e": 26987, "s": 26921, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27026, "s": 26987, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 27038, "s": 27026, "text": "SQL | Views" }, { "code": null, "e": 27083, "s": 27038, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 27115, "s": 27083, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 27154, "s": 27115, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 27169, "s": 27154, "text": "SQL - ORDER BY" } ]
Java Implementation of Diffie-Hellman Algorithm between Client and Server - GeeksforGeeks
10 Nov, 2021 Program to implement Diffie-Hellman Algorithm in Client-Server Fashion. Prerequisite: Server Socket Programming, Diffie-Hellman algorithm The Diffie Hellman Algorithm is being used to establish a shared secret that can be used for secret communications while exchanging data over a public network. In the below program, the client will share the value of , , and public key . Whereas, the server will accept the values and calculate its public key and send it to the client. Both Client and Server will calculate the secret key for symmetric encryption by using the public key. Program 1: Server Program import java.net.*;import java.io.*; public class GreetingServer { public static void main(String[] args) throws IOException { try { int port = 8088; // Server Key int b = 3; // Client p, g, and key double clientP, clientG, clientA, B, Bdash; String Bstr; // Established the Connection ServerSocket serverSocket = new ServerSocket(port); System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "..."); Socket server = serverSocket.accept(); System.out.println("Just connected to " + server.getRemoteSocketAddress()); // Server's Private Key System.out.println("From Server : Private Key = " + b); // Accepts the data from client DataInputStream in = new DataInputStream(server.getInputStream()); clientP = Integer.parseInt(in.readUTF()); // to accept p System.out.println("From Client : P = " + clientP); clientG = Integer.parseInt(in.readUTF()); // to accept g System.out.println("From Client : G = " + clientG); clientA = Double.parseDouble(in.readUTF()); // to accept A System.out.println("From Client : Public Key = " + clientA); B = ((Math.pow(clientG, b)) % clientP); // calculation of B Bstr = Double.toString(B); // Sends data to client // Value of B OutputStream outToclient = server.getOutputStream(); DataOutputStream out = new DataOutputStream(outToclient); out.writeUTF(Bstr); // Sending B Bdash = ((Math.pow(clientA, b)) % clientP); // calculation of Bdash System.out.println("Secret Key to perform Symmetric Encryption = " + Bdash); server.close(); } catch (SocketTimeoutException s) { System.out.println("Socket timed out!"); } catch (IOException e) { } }} Program 2: Client Program import java.net.*;import java.io.*; public class GreetingClient { public static void main(String[] args) { try { String pstr, gstr, Astr; String serverName = "localhost"; int port = 8088; // Declare p, g, and Key of client int p = 23; int g = 9; int a = 4; double Adash, serverB; // Established the connection System.out.println("Connecting to " + serverName + " on port " + port); Socket client = new Socket(serverName, port); System.out.println("Just connected to " + client.getRemoteSocketAddress()); // Sends the data to client OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); pstr = Integer.toString(p); out.writeUTF(pstr); // Sending p gstr = Integer.toString(g); out.writeUTF(gstr); // Sending g double A = ((Math.pow(g, a)) % p); // calculation of A Astr = Double.toString(A); out.writeUTF(Astr); // Sending A // Client's Private Key System.out.println("From Client : Private Key = " + a); // Accepts the data DataInputStream in = new DataInputStream(client.getInputStream()); serverB = Double.parseDouble(in.readUTF()); System.out.println("From Server : Public Key = " + serverB); Adash = ((Math.pow(serverB, a)) % p); // calculation of Adash System.out.println("Secret Key to perform Symmetric Encryption = " + Adash); client.close(); } catch (Exception e) { e.printStackTrace(); } }} Use javac to Compile the programs, and open two console/terminal to run the system Output:In the first console run the server program, it will wait for the client’s connection. As soon as client is connected results will popup In the second console, run the client’s program marcosarcticseal Java-Networking Computer Networks Java Programs Technical Scripter Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Types of Network Topology TCP 3-Way Handshake Process User Datagram Protocol (UDP) UDP Server-Client implementation in C Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25661, "s": 25633, "text": "\n10 Nov, 2021" }, { "code": null, "e": 25733, "s": 25661, "text": "Program to implement Diffie-Hellman Algorithm in Client-Server Fashion." }, { "code": null, "e": 25799, "s": 25733, "text": "Prerequisite: Server Socket Programming, Diffie-Hellman algorithm" }, { "code": null, "e": 25959, "s": 25799, "text": "The Diffie Hellman Algorithm is being used to establish a shared secret that can be used for secret communications while exchanging data over a public network." }, { "code": null, "e": 26137, "s": 25959, "text": "In the below program, the client will share the value of , , and public key . Whereas, the server will accept the values and calculate its public key and send it to the client." }, { "code": null, "e": 26240, "s": 26137, "text": "Both Client and Server will calculate the secret key for symmetric encryption by using the public key." }, { "code": null, "e": 26266, "s": 26240, "text": "Program 1: Server Program" }, { "code": "import java.net.*;import java.io.*; public class GreetingServer { public static void main(String[] args) throws IOException { try { int port = 8088; // Server Key int b = 3; // Client p, g, and key double clientP, clientG, clientA, B, Bdash; String Bstr; // Established the Connection ServerSocket serverSocket = new ServerSocket(port); System.out.println(\"Waiting for client on port \" + serverSocket.getLocalPort() + \"...\"); Socket server = serverSocket.accept(); System.out.println(\"Just connected to \" + server.getRemoteSocketAddress()); // Server's Private Key System.out.println(\"From Server : Private Key = \" + b); // Accepts the data from client DataInputStream in = new DataInputStream(server.getInputStream()); clientP = Integer.parseInt(in.readUTF()); // to accept p System.out.println(\"From Client : P = \" + clientP); clientG = Integer.parseInt(in.readUTF()); // to accept g System.out.println(\"From Client : G = \" + clientG); clientA = Double.parseDouble(in.readUTF()); // to accept A System.out.println(\"From Client : Public Key = \" + clientA); B = ((Math.pow(clientG, b)) % clientP); // calculation of B Bstr = Double.toString(B); // Sends data to client // Value of B OutputStream outToclient = server.getOutputStream(); DataOutputStream out = new DataOutputStream(outToclient); out.writeUTF(Bstr); // Sending B Bdash = ((Math.pow(clientA, b)) % clientP); // calculation of Bdash System.out.println(\"Secret Key to perform Symmetric Encryption = \" + Bdash); server.close(); } catch (SocketTimeoutException s) { System.out.println(\"Socket timed out!\"); } catch (IOException e) { } }}", "e": 28325, "s": 26266, "text": null }, { "code": null, "e": 28351, "s": 28325, "text": "Program 2: Client Program" }, { "code": "import java.net.*;import java.io.*; public class GreetingClient { public static void main(String[] args) { try { String pstr, gstr, Astr; String serverName = \"localhost\"; int port = 8088; // Declare p, g, and Key of client int p = 23; int g = 9; int a = 4; double Adash, serverB; // Established the connection System.out.println(\"Connecting to \" + serverName + \" on port \" + port); Socket client = new Socket(serverName, port); System.out.println(\"Just connected to \" + client.getRemoteSocketAddress()); // Sends the data to client OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); pstr = Integer.toString(p); out.writeUTF(pstr); // Sending p gstr = Integer.toString(g); out.writeUTF(gstr); // Sending g double A = ((Math.pow(g, a)) % p); // calculation of A Astr = Double.toString(A); out.writeUTF(Astr); // Sending A // Client's Private Key System.out.println(\"From Client : Private Key = \" + a); // Accepts the data DataInputStream in = new DataInputStream(client.getInputStream()); serverB = Double.parseDouble(in.readUTF()); System.out.println(\"From Server : Public Key = \" + serverB); Adash = ((Math.pow(serverB, a)) % p); // calculation of Adash System.out.println(\"Secret Key to perform Symmetric Encryption = \" + Adash); client.close(); } catch (Exception e) { e.printStackTrace(); } }}", "e": 30210, "s": 28351, "text": null }, { "code": null, "e": 30293, "s": 30210, "text": "Use javac to Compile the programs, and open two console/terminal to run the system" }, { "code": null, "e": 30437, "s": 30293, "text": "Output:In the first console run the server program, it will wait for the client’s connection. As soon as client is connected results will popup" }, { "code": null, "e": 30485, "s": 30437, "text": "In the second console, run the client’s program" }, { "code": null, "e": 30502, "s": 30485, "text": "marcosarcticseal" }, { "code": null, "e": 30518, "s": 30502, "text": "Java-Networking" }, { "code": null, "e": 30536, "s": 30518, "text": "Computer Networks" }, { "code": null, "e": 30550, "s": 30536, "text": "Java Programs" }, { "code": null, "e": 30569, "s": 30550, "text": "Technical Scripter" }, { "code": null, "e": 30587, "s": 30569, "text": "Computer Networks" }, { "code": null, "e": 30685, "s": 30587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30719, "s": 30685, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 30745, "s": 30719, "text": "Types of Network Topology" }, { "code": null, "e": 30773, "s": 30745, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 30802, "s": 30773, "text": "User Datagram Protocol (UDP)" }, { "code": null, "e": 30840, "s": 30802, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 30868, "s": 30840, "text": "Initializing a List in Java" }, { "code": null, "e": 30912, "s": 30868, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 30938, "s": 30912, "text": "Java Programming Examples" }, { "code": null, "e": 30972, "s": 30938, "text": "Convert Double to Integer in Java" } ]
Ego graph Using Networkx in Python - GeeksforGeeks
20 May, 2021 Prerequisite – Graphs, Networkx Basics Ego network is a special type of network consisting of one central node and all other nodes directly connected to it. The central node is known as ego, while the other surrounding nodes directly connected to it are known as alters. Ego networks are mostly used in analyzing social connections, links, and relationships. The network shown below is an illustration of Ego Network. The central node (ego) is shown as circular surrounded by the neighboring nodes (alters). Ego network is widely used in Social network analysis. The basic hypothesis about ego networks is that strong ties are homophilous. Homophilous is the tendency of individuals who are socially connected in some way to display certain traits or similarities to each other. In simple words, like-minded people are connected strongly in some manner. The ego network helps us to identify these hidden connections. The following functions are served by Ego Networks: Propagation of information efficiently. Sensemaking from links, For example – Social links, relationships. Access to resources, efficient connection path generation. Community detection, identification of the formation of groups. Analysis of the ties among individuals for social support. The easiest way to implement an ego network on any graph database is by using the Networkx library. It provides many predefined functions for the analysis and visualization of networks. Networkx: Networkx is a Python package for the creation, analysis, and studies the nature of complex networks. It is one of the most popular python libraries used for network analysis. Installation of the package: pip install networkx The Networkx library provides the method ego_graph() to generate an ego network from any graph. The method takes two mandatory parameters and four additional optional parameters. Syntax: ego_graph(G, n, radius=1, center=True, undirected=False, distance=None) Parameters: G (graph) – A NetworkX Graph (The parent network in whose ego network is to be created) N (node) – A single node (Ego/Central node of the ego network) Radius (number, optional) – Include all neighbors of distance <= radius from n. Center (bool, optional) – If False, do not include center node (ego) in graph Undirected (bool, optional) – If True use both in- and out-neighbors of directed graphs. Distance (key, optional) – Use specified edge data key as distance. For example, setting distance=’weight’ will use the edge weight to measure the distance from the node n. We are taking a sample network with few nodes interconnected to each other. In this example, the nodes are – (A, B, C, D, E, F, G, H), out of these nodes one node is taken as the central node (ego), in our case we have taken A as the ego. The following code creates and shows our sample network. Example: Python3 # import networkx for graph generationimport networkx as nx # import matplotlib libraryimport matplotlib.pyplot as plt # generation of a sample graphG = nx.Graph()G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'C'), ('E', 'F'), ('D', 'E'), ('A', 'D'), ('D', 'G'), ('C', 'F'), ('D', 'F'), ('E', 'H')]) # Defining ego as large and red# while alters are in lavender# Let 'A' be the egoego = 'A'pos = nx.spring_layout(G)nx.draw(G, pos, node_color = "lavender", node_size = 800, with_labels = True) options = {"node_size": 1200, "node_color": "r"}nx.draw_networkx_nodes(G, pos, nodelist=[ego], **options)plt.show() Output: The sample network (Ego – A) Node A is defined as ego and hence shown in red. The below code creates and shows the ego network considering node A as the ego. Python3 # create ego networkhub_ego = nx.ego_graph(G, ego) # showing the ego networknx.draw(hub_ego, pos, node_color="lavender", node_size = 800, with_labels = True) nx.draw_networkx_nodes( hub_ego, pos, nodelist = [ego], **options) plt.show() Output: Ego network (Ego – A, Alters – [B, C, D]) Python Networx-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n20 May, 2021" }, { "code": null, "e": 25576, "s": 25537, "text": "Prerequisite – Graphs, Networkx Basics" }, { "code": null, "e": 26045, "s": 25576, "text": "Ego network is a special type of network consisting of one central node and all other nodes directly connected to it. The central node is known as ego, while the other surrounding nodes directly connected to it are known as alters. Ego networks are mostly used in analyzing social connections, links, and relationships. The network shown below is an illustration of Ego Network. The central node (ego) is shown as circular surrounded by the neighboring nodes (alters)." }, { "code": null, "e": 26454, "s": 26045, "text": "Ego network is widely used in Social network analysis. The basic hypothesis about ego networks is that strong ties are homophilous. Homophilous is the tendency of individuals who are socially connected in some way to display certain traits or similarities to each other. In simple words, like-minded people are connected strongly in some manner. The ego network helps us to identify these hidden connections." }, { "code": null, "e": 26506, "s": 26454, "text": "The following functions are served by Ego Networks:" }, { "code": null, "e": 26546, "s": 26506, "text": "Propagation of information efficiently." }, { "code": null, "e": 26613, "s": 26546, "text": "Sensemaking from links, For example – Social links, relationships." }, { "code": null, "e": 26672, "s": 26613, "text": "Access to resources, efficient connection path generation." }, { "code": null, "e": 26736, "s": 26672, "text": "Community detection, identification of the formation of groups." }, { "code": null, "e": 26795, "s": 26736, "text": "Analysis of the ties among individuals for social support." }, { "code": null, "e": 26981, "s": 26795, "text": "The easiest way to implement an ego network on any graph database is by using the Networkx library. It provides many predefined functions for the analysis and visualization of networks." }, { "code": null, "e": 27166, "s": 26981, "text": "Networkx: Networkx is a Python package for the creation, analysis, and studies the nature of complex networks. It is one of the most popular python libraries used for network analysis." }, { "code": null, "e": 27195, "s": 27166, "text": "Installation of the package:" }, { "code": null, "e": 27216, "s": 27195, "text": "pip install networkx" }, { "code": null, "e": 27395, "s": 27216, "text": "The Networkx library provides the method ego_graph() to generate an ego network from any graph. The method takes two mandatory parameters and four additional optional parameters." }, { "code": null, "e": 27475, "s": 27395, "text": "Syntax: ego_graph(G, n, radius=1, center=True, undirected=False, distance=None)" }, { "code": null, "e": 27487, "s": 27475, "text": "Parameters:" }, { "code": null, "e": 27575, "s": 27487, "text": "G (graph) – A NetworkX Graph (The parent network in whose ego network is to be created)" }, { "code": null, "e": 27638, "s": 27575, "text": "N (node) – A single node (Ego/Central node of the ego network)" }, { "code": null, "e": 27718, "s": 27638, "text": "Radius (number, optional) – Include all neighbors of distance <= radius from n." }, { "code": null, "e": 27796, "s": 27718, "text": "Center (bool, optional) – If False, do not include center node (ego) in graph" }, { "code": null, "e": 27885, "s": 27796, "text": "Undirected (bool, optional) – If True use both in- and out-neighbors of directed graphs." }, { "code": null, "e": 28058, "s": 27885, "text": "Distance (key, optional) – Use specified edge data key as distance. For example, setting distance=’weight’ will use the edge weight to measure the distance from the node n." }, { "code": null, "e": 28354, "s": 28058, "text": "We are taking a sample network with few nodes interconnected to each other. In this example, the nodes are – (A, B, C, D, E, F, G, H), out of these nodes one node is taken as the central node (ego), in our case we have taken A as the ego. The following code creates and shows our sample network." }, { "code": null, "e": 28363, "s": 28354, "text": "Example:" }, { "code": null, "e": 28371, "s": 28363, "text": "Python3" }, { "code": "# import networkx for graph generationimport networkx as nx # import matplotlib libraryimport matplotlib.pyplot as plt # generation of a sample graphG = nx.Graph()G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'C'), ('E', 'F'), ('D', 'E'), ('A', 'D'), ('D', 'G'), ('C', 'F'), ('D', 'F'), ('E', 'H')]) # Defining ego as large and red# while alters are in lavender# Let 'A' be the egoego = 'A'pos = nx.spring_layout(G)nx.draw(G, pos, node_color = \"lavender\", node_size = 800, with_labels = True) options = {\"node_size\": 1200, \"node_color\": \"r\"}nx.draw_networkx_nodes(G, pos, nodelist=[ego], **options)plt.show()", "e": 29064, "s": 28371, "text": null }, { "code": null, "e": 29072, "s": 29064, "text": "Output:" }, { "code": null, "e": 29101, "s": 29072, "text": "The sample network (Ego – A)" }, { "code": null, "e": 29150, "s": 29101, "text": "Node A is defined as ego and hence shown in red." }, { "code": null, "e": 29230, "s": 29150, "text": "The below code creates and shows the ego network considering node A as the ego." }, { "code": null, "e": 29238, "s": 29230, "text": "Python3" }, { "code": "# create ego networkhub_ego = nx.ego_graph(G, ego) # showing the ego networknx.draw(hub_ego, pos, node_color=\"lavender\", node_size = 800, with_labels = True) nx.draw_networkx_nodes( hub_ego, pos, nodelist = [ego], **options) plt.show()", "e": 29486, "s": 29238, "text": null }, { "code": null, "e": 29494, "s": 29486, "text": "Output:" }, { "code": null, "e": 29536, "s": 29494, "text": "Ego network (Ego – A, Alters – [B, C, D])" }, { "code": null, "e": 29558, "s": 29536, "text": "Python Networx-module" }, { "code": null, "e": 29565, "s": 29558, "text": "Python" }, { "code": null, "e": 29663, "s": 29565, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29695, "s": 29663, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29737, "s": 29695, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29779, "s": 29737, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29806, "s": 29779, "text": "Python Classes and Objects" }, { "code": null, "e": 29862, "s": 29806, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29884, "s": 29862, "text": "Defaultdict in Python" }, { "code": null, "e": 29923, "s": 29884, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29954, "s": 29923, "text": "Python | os.path.join() method" }, { "code": null, "e": 29983, "s": 29954, "text": "Create a directory in Python" } ]
How to set Background Color of the FlowLayoutPanel in C#? - GeeksforGeeks
02 Aug, 2019 In Windows Forms, FlowLayoutPanel control is used to arrange its child controls in a horizontal or vertical flow direction. Or in other words, FlowLayoutPanel is a container which is used to organize different or same types of controls in it either horizontally or vertically. In FlowLayoutPanel control, you can set the background color of the control using BackColor Property. This property is an ambient property. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the background color of the FlowLayoutPanel as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the FlowLayoutPanel control from the toolbox to the form as shown in the below image: Step 3: After drag and drop you will go to the properties of the FlowLayoutPanel and set the background color of the FlowLayoutPanel as shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the FlowLayoutPanel control programmatically with the help of given syntax: public virtual System.Drawing.Color BackColor { get; set; } The following steps show how to set the background color of the FlowLayoutPanel dynamically: Step 1: Create a FlowLayoutPanel using the FlowLayoutPanel() constructor is provided by the FlowLayoutPanel class.// Creating a FlowLayoutPanel FlowLayoutPanel f = new FlowLayoutPanel(); // Creating a FlowLayoutPanel FlowLayoutPanel f = new FlowLayoutPanel(); Step 2: After creating FlowLayoutPanel, set the BackColor property of the FlowLayoutPanel provided by the FlowLayoutPanel class.// Setting the background color f.BackColor = Color.LightPink; // Setting the background color f.BackColor = Color.LightPink; Step 3: And last add this FlowLayoutPanel control to the form and also adding child controls in the FlowLayoutPanel using the following statements:// Adding a FlowLayoutPanel // control to the form this.Controls.Add(f); and // Adding child controls to // the FlowLayoutPanel f.Controls.Add(r1); // Adding a FlowLayoutPanel // control to the form this.Controls.Add(f); and // Adding child controls to // the FlowLayoutPanel f.Controls.Add(r1); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp50 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of FlowLayoutPanel FlowLayoutPanel f = new FlowLayoutPanel(); f.Location = new Point(380, 124); f.AutoSize = true; f.AutoSizeMode = AutoSizeMode.GrowAndShrink; f.Name = "Mycontainer"; f.Font = new Font("Calibri", 12); f.FlowDirection = FlowDirection.RightToLeft; f.BorderStyle = BorderStyle.Fixed3D; f.ForeColor = Color.BlueViolet; f.BackColor = Color.LightPink; f.Visible = true; // Adding this control to the form this.Controls.Add(f); // Creating and setting the // properties of radio buttons RadioButton r1 = new RadioButton(); r1.Location = new Point(3, 3); r1.Size = new Size(95, 20); r1.Text = "R1"; // Adding this control // to the FlowLayoutPanel f.Controls.Add(r1); RadioButton r2 = new RadioButton(); r2.Location = new Point(94, 3); r2.Size = new Size(95, 20); r2.Text = "R2"; // Adding this control // to the FlowLayoutPanel f.Controls.Add(r2); RadioButton r3 = new RadioButton(); r3.Location = new Point(3, 26); r3.Size = new Size(95, 20); r3.Text = "R3"; // Adding this control to // the FlowLayoutPanel f.Controls.Add(r3); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n02 Aug, 2019" }, { "code": null, "e": 26013, "s": 25547, "text": "In Windows Forms, FlowLayoutPanel control is used to arrange its child controls in a horizontal or vertical flow direction. Or in other words, FlowLayoutPanel is a container which is used to organize different or same types of controls in it either horizontally or vertically. In FlowLayoutPanel control, you can set the background color of the control using BackColor Property. This property is an ambient property. You can set this property in two different ways:" }, { "code": null, "e": 26135, "s": 26013, "text": "1. Design-Time: It is the easiest way to set the background color of the FlowLayoutPanel as shown in the following steps:" }, { "code": null, "e": 26251, "s": 26135, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 26365, "s": 26251, "text": "Step 2: Next, drag and drop the FlowLayoutPanel control from the toolbox to the form as shown in the below image:" }, { "code": null, "e": 26534, "s": 26365, "text": "Step 3: After drag and drop you will go to the properties of the FlowLayoutPanel and set the background color of the FlowLayoutPanel as shown in the below image:Output:" }, { "code": null, "e": 26542, "s": 26534, "text": "Output:" }, { "code": null, "e": 26734, "s": 26542, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the FlowLayoutPanel control programmatically with the help of given syntax:" }, { "code": null, "e": 26794, "s": 26734, "text": "public virtual System.Drawing.Color BackColor { get; set; }" }, { "code": null, "e": 26887, "s": 26794, "text": "The following steps show how to set the background color of the FlowLayoutPanel dynamically:" }, { "code": null, "e": 27076, "s": 26887, "text": "Step 1: Create a FlowLayoutPanel using the FlowLayoutPanel() constructor is provided by the FlowLayoutPanel class.// Creating a FlowLayoutPanel\nFlowLayoutPanel f = new FlowLayoutPanel(); \n" }, { "code": null, "e": 27151, "s": 27076, "text": "// Creating a FlowLayoutPanel\nFlowLayoutPanel f = new FlowLayoutPanel(); \n" }, { "code": null, "e": 27343, "s": 27151, "text": "Step 2: After creating FlowLayoutPanel, set the BackColor property of the FlowLayoutPanel provided by the FlowLayoutPanel class.// Setting the background color\nf.BackColor = Color.LightPink;\n" }, { "code": null, "e": 27407, "s": 27343, "text": "// Setting the background color\nf.BackColor = Color.LightPink;\n" }, { "code": null, "e": 27706, "s": 27407, "text": "Step 3: And last add this FlowLayoutPanel control to the form and also adding child controls in the FlowLayoutPanel using the following statements:// Adding a FlowLayoutPanel\n// control to the form\nthis.Controls.Add(f);\n\nand \n\n// Adding child controls to\n// the FlowLayoutPanel\nf.Controls.Add(r1);\n" }, { "code": null, "e": 27858, "s": 27706, "text": "// Adding a FlowLayoutPanel\n// control to the form\nthis.Controls.Add(f);\n\nand \n\n// Adding child controls to\n// the FlowLayoutPanel\nf.Controls.Add(r1);\n" }, { "code": null, "e": 27867, "s": 27858, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp50 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of FlowLayoutPanel FlowLayoutPanel f = new FlowLayoutPanel(); f.Location = new Point(380, 124); f.AutoSize = true; f.AutoSizeMode = AutoSizeMode.GrowAndShrink; f.Name = \"Mycontainer\"; f.Font = new Font(\"Calibri\", 12); f.FlowDirection = FlowDirection.RightToLeft; f.BorderStyle = BorderStyle.Fixed3D; f.ForeColor = Color.BlueViolet; f.BackColor = Color.LightPink; f.Visible = true; // Adding this control to the form this.Controls.Add(f); // Creating and setting the // properties of radio buttons RadioButton r1 = new RadioButton(); r1.Location = new Point(3, 3); r1.Size = new Size(95, 20); r1.Text = \"R1\"; // Adding this control // to the FlowLayoutPanel f.Controls.Add(r1); RadioButton r2 = new RadioButton(); r2.Location = new Point(94, 3); r2.Size = new Size(95, 20); r2.Text = \"R2\"; // Adding this control // to the FlowLayoutPanel f.Controls.Add(r2); RadioButton r3 = new RadioButton(); r3.Location = new Point(3, 26); r3.Size = new Size(95, 20); r3.Text = \"R3\"; // Adding this control to // the FlowLayoutPanel f.Controls.Add(r3); }}}", "e": 29634, "s": 27867, "text": null }, { "code": null, "e": 29642, "s": 29634, "text": "Output:" }, { "code": null, "e": 29673, "s": 29642, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 29676, "s": 29673, "text": "C#" }, { "code": null, "e": 29774, "s": 29676, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29797, "s": 29774, "text": "Extension Method in C#" }, { "code": null, "e": 29825, "s": 29797, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29842, "s": 29825, "text": "C# | Inheritance" }, { "code": null, "e": 29864, "s": 29842, "text": "Partial Classes in C#" }, { "code": null, "e": 29893, "s": 29864, "text": "C# | Generics - Introduction" }, { "code": null, "e": 29933, "s": 29893, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29956, "s": 29933, "text": "Switch Statement in C#" }, { "code": null, "e": 29996, "s": 29956, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 30039, "s": 29996, "text": "C# | How to insert an element in an Array?" } ]
How to Prepopulate Room Database in Android? - GeeksforGeeks
18 Oct, 2021 Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-level, which requires a lot of time and effort to use. But Room makes everything easy and clear to create a Database and perform the operations on it. But what is meant by Prepopulating the database? Prepopulating the database means having some pre-loaded data in the database at the first run. So, We will see the implementation for prepopulating the Room database. We will Prepopulate the database from the app assets. We need a pre-packaged database, which we will store in the assets folder in android studio. Step 1: To Prepopulate a room database from a pre-packaged database that is stored in assets, We need to call the createFromAsset( ) method from Room.databaseBuilder object. Now we will create the Data Entity. It will be a data class, let’s give it the name “Quote.kt”. Refer to the below code for reference. Kotlin import androidx.room.Entityimport androidx.room.PrimaryKey @Entity(tableName = "quote")data class Quote( @PrimaryKey(autoGenerate = true) val id: Int, val text: String, val author: String) (autoGenerate = true) is used to auto-increment to id whenever a new data is added. Step 2: Then we need to create Dao. Dao is an interface, So no need to define methods inside it. Room takes to care for implementation of these methods. Dao is used to accessing the data object in the database. Refer to the below code for reference. Kotlin import androidx.lifecycle.LiveDataimport androidx.room.Daoimport androidx.room.Insertimport androidx.room.Query @Daointerface QuoteDao { @Insert suspend fun insert(quote: Quote) @Query("Select * From quote") fun getQuote(): LiveData<List<Quote>>} Step 3: Now we will create the database class, it is the main access point to the application’s persisted data. It is an abstract class, It extends to RoomDatabase. Here we call the createFromAsset(“path”) method from our Room.databaseBuilder object before calling build(). Refer to the below code for reference. Kotlin import android.content.Contextimport androidx.room.Databaseimport androidx.room.Roomimport androidx.room.RoomDatabase @Database(entities = [Quote::class], version = 1)abstract class QuoteDatabase : RoomDatabase() { abstract fun quoteDao(): QuoteDao companion object { private var INSTANCE: QuoteDatabase? = null fun getDatabase(context: Context): QuoteDatabase { if (INSTANCE == null) { synchronized(this) { INSTANCE = Room.databaseBuilder(context, QuoteDatabase::class.java, "quote_database") .createFromAsset("quote.db") .build() } } return INSTANCE!! } }} So, this is how we implement the Pre-populated Room persistence database. Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Kotlin Setters and Getters
[ { "code": null, "e": 26381, "s": 26353, "text": "\n18 Oct, 2021" }, { "code": null, "e": 27099, "s": 26381, "text": "Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-level, which requires a lot of time and effort to use. But Room makes everything easy and clear to create a Database and perform the operations on it. But what is meant by Prepopulating the database? Prepopulating the database means having some pre-loaded data in the database at the first run. So, We will see the implementation for prepopulating the Room database. We will Prepopulate the database from the app assets." }, { "code": null, "e": 27192, "s": 27099, "text": "We need a pre-packaged database, which we will store in the assets folder in android studio." }, { "code": null, "e": 27200, "s": 27192, "text": "Step 1:" }, { "code": null, "e": 27501, "s": 27200, "text": "To Prepopulate a room database from a pre-packaged database that is stored in assets, We need to call the createFromAsset( ) method from Room.databaseBuilder object. Now we will create the Data Entity. It will be a data class, let’s give it the name “Quote.kt”. Refer to the below code for reference." }, { "code": null, "e": 27508, "s": 27501, "text": "Kotlin" }, { "code": "import androidx.room.Entityimport androidx.room.PrimaryKey @Entity(tableName = \"quote\")data class Quote( @PrimaryKey(autoGenerate = true) val id: Int, val text: String, val author: String)", "e": 27710, "s": 27508, "text": null }, { "code": null, "e": 27794, "s": 27710, "text": "(autoGenerate = true) is used to auto-increment to id whenever a new data is added." }, { "code": null, "e": 27802, "s": 27794, "text": "Step 2:" }, { "code": null, "e": 28044, "s": 27802, "text": "Then we need to create Dao. Dao is an interface, So no need to define methods inside it. Room takes to care for implementation of these methods. Dao is used to accessing the data object in the database. Refer to the below code for reference." }, { "code": null, "e": 28051, "s": 28044, "text": "Kotlin" }, { "code": "import androidx.lifecycle.LiveDataimport androidx.room.Daoimport androidx.room.Insertimport androidx.room.Query @Daointerface QuoteDao { @Insert suspend fun insert(quote: Quote) @Query(\"Select * From quote\") fun getQuote(): LiveData<List<Quote>>}", "e": 28313, "s": 28051, "text": null }, { "code": null, "e": 28321, "s": 28313, "text": "Step 3:" }, { "code": null, "e": 28626, "s": 28321, "text": "Now we will create the database class, it is the main access point to the application’s persisted data. It is an abstract class, It extends to RoomDatabase. Here we call the createFromAsset(“path”) method from our Room.databaseBuilder object before calling build(). Refer to the below code for reference." }, { "code": null, "e": 28633, "s": 28626, "text": "Kotlin" }, { "code": "import android.content.Contextimport androidx.room.Databaseimport androidx.room.Roomimport androidx.room.RoomDatabase @Database(entities = [Quote::class], version = 1)abstract class QuoteDatabase : RoomDatabase() { abstract fun quoteDao(): QuoteDao companion object { private var INSTANCE: QuoteDatabase? = null fun getDatabase(context: Context): QuoteDatabase { if (INSTANCE == null) { synchronized(this) { INSTANCE = Room.databaseBuilder(context, QuoteDatabase::class.java, \"quote_database\") .createFromAsset(\"quote.db\") .build() } } return INSTANCE!! } }}", "e": 29384, "s": 28633, "text": null }, { "code": null, "e": 29458, "s": 29384, "text": "So, this is how we implement the Pre-populated Room persistence database." }, { "code": null, "e": 29466, "s": 29458, "text": "Android" }, { "code": null, "e": 29473, "s": 29466, "text": "Kotlin" }, { "code": null, "e": 29481, "s": 29473, "text": "Android" }, { "code": null, "e": 29579, "s": 29481, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29617, "s": 29579, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 29656, "s": 29617, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29706, "s": 29656, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 29748, "s": 29706, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29799, "s": 29748, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 29818, "s": 29799, "text": "Android UI Layouts" }, { "code": null, "e": 29831, "s": 29818, "text": "Kotlin Array" }, { "code": null, "e": 29873, "s": 29831, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29913, "s": 29873, "text": "How to Get Current Location in Android?" } ]
C Program for Binary Insertion Sort - GeeksforGeeks
13 Feb, 2022 We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search. C/C++ C // C program for implementation of binary insertion sort#include <stdio.h> // A binary search based function to find the position// where item should be inserted in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low])? (low + 1): low; int mid = (low + high)/2; if(item == a[mid]) return mid+1; if(item > a[mid]) return binarySearch(a, item, mid+1, high); return binarySearch(a, item, low, mid-1);} // Function to sort an array a[] of size \'n\'void insertionSort(int a[], int n){ int i, loc, j, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inserted loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j+1] = a[j]; j--; } a[j+1] = selected; }} // Driver program to test above functionint main(){ int a[] = {37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54}; int n = sizeof(a)/sizeof(a[0]), i; insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ",a[i]); return 0;} Please refer complete article on Binary Insertion Sort for more details! sagartomar9927 sweetyty archstanton Insertion Sort C Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Exit codes in C/C++ with Examples C program to find the length of a string Handling multiple clients on server with multithreading using Socket Programming in C/C++
[ { "code": null, "e": 26253, "s": 26225, "text": "\n13 Feb, 2022" }, { "code": null, "e": 26586, "s": 26253, "text": "We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search." }, { "code": null, "e": 26592, "s": 26586, "text": "C/C++" }, { "code": null, "e": 26594, "s": 26592, "text": "C" }, { "code": "// C program for implementation of binary insertion sort#include <stdio.h> // A binary search based function to find the position// where item should be inserted in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low])? (low + 1): low; int mid = (low + high)/2; if(item == a[mid]) return mid+1; if(item > a[mid]) return binarySearch(a, item, mid+1, high); return binarySearch(a, item, low, mid-1);} // Function to sort an array a[] of size \\'n\\'void insertionSort(int a[], int n){ int i, loc, j, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inserted loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j+1] = a[j]; j--; } a[j+1] = selected; }} // Driver program to test above functionint main(){ int a[] = {37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54}; int n = sizeof(a)/sizeof(a[0]), i; insertionSort(a, n); printf(\"Sorted array: \\n\"); for (i = 0; i < n; i++) printf(\"%d \",a[i]); return 0;}", "e": 27841, "s": 26594, "text": null }, { "code": null, "e": 27914, "s": 27841, "text": "Please refer complete article on Binary Insertion Sort for more details!" }, { "code": null, "e": 27929, "s": 27914, "text": "sagartomar9927" }, { "code": null, "e": 27938, "s": 27929, "text": "sweetyty" }, { "code": null, "e": 27950, "s": 27938, "text": "archstanton" }, { "code": null, "e": 27965, "s": 27950, "text": "Insertion Sort" }, { "code": null, "e": 27976, "s": 27965, "text": "C Programs" }, { "code": null, "e": 27984, "s": 27976, "text": "Sorting" }, { "code": null, "e": 27992, "s": 27984, "text": "Sorting" }, { "code": null, "e": 28090, "s": 27992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28131, "s": 28090, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28162, "s": 28131, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 28196, "s": 28162, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 28237, "s": 28196, "text": "C program to find the length of a string" } ]
C Program to Check if a Given String is Palindrome - GeeksforGeeks
25 Jul, 2021 Given a string, write a c function to check if it is palindrome or not. A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is palindrome, but “abbc” is not palindrome. Algorithm: isPalindrome(str) 1) Find length of str. Let length be n. 2) Initialize low and high indexes as 0 and n-1 respectively. 3) Do following while low index ‘l’ is smaller than high index ‘h’. .....a) If str[l] is not same as str[h], then return false. .....b) Increment l and decrement h, i.e., do l++ and h–. 4) If we reach here, it means we didn’t find a misFollowing is C implementation to check if a given string is palindrome or not. C #include <stdio.h>#include <string.h> // A function to check if a string str is palindromevoid isPalindrome(char str[]){ // Start from leftmost and rightmost corners of str int l = 0; int h = strlen(str) - 1; // Keep comparing characters while they are same while (h > l) { if (str[l++] != str[h--]) { printf("%s is not a palindrome\n", str); return; } } printf("%s is a palindrome\n", str);} // Driver program to test above functionint main(){ isPalindrome("abba"); isPalindrome("abbccbba"); isPalindrome("geeks"); return 0;} abba is a palindrome abbccbba is a palindrome geeks is not a palindrome Recursive function to check if a string is palindromePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above AbhijeetPrakash rasheduliriyad FactSet Morgan Stanley palindrome Paytm TCS School Programming Strings Paytm Morgan Stanley FactSet TCS Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Classes and Objects Interfaces in Java Constructors in C++ Operator Overloading in C++ Copy Constructor in C++ Write a program to reverse an array or string Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26027, "s": 25999, "text": "\n25 Jul, 2021" }, { "code": null, "e": 26243, "s": 26027, "text": "Given a string, write a c function to check if it is palindrome or not. A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is palindrome, but “abbc” is not palindrome. " }, { "code": null, "e": 26692, "s": 26245, "text": "Algorithm: isPalindrome(str) 1) Find length of str. Let length be n. 2) Initialize low and high indexes as 0 and n-1 respectively. 3) Do following while low index ‘l’ is smaller than high index ‘h’. .....a) If str[l] is not same as str[h], then return false. .....b) Increment l and decrement h, i.e., do l++ and h–. 4) If we reach here, it means we didn’t find a misFollowing is C implementation to check if a given string is palindrome or not. " }, { "code": null, "e": 26694, "s": 26692, "text": "C" }, { "code": "#include <stdio.h>#include <string.h> // A function to check if a string str is palindromevoid isPalindrome(char str[]){ // Start from leftmost and rightmost corners of str int l = 0; int h = strlen(str) - 1; // Keep comparing characters while they are same while (h > l) { if (str[l++] != str[h--]) { printf(\"%s is not a palindrome\\n\", str); return; } } printf(\"%s is a palindrome\\n\", str);} // Driver program to test above functionint main(){ isPalindrome(\"abba\"); isPalindrome(\"abbccbba\"); isPalindrome(\"geeks\"); return 0;}", "e": 27301, "s": 26694, "text": null }, { "code": null, "e": 27374, "s": 27301, "text": "abba is a palindrome\nabbccbba is a palindrome\ngeeks is not a palindrome\n" }, { "code": null, "e": 27552, "s": 27374, "text": "Recursive function to check if a string is palindromePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 27568, "s": 27552, "text": "AbhijeetPrakash" }, { "code": null, "e": 27583, "s": 27568, "text": "rasheduliriyad" }, { "code": null, "e": 27591, "s": 27583, "text": "FactSet" }, { "code": null, "e": 27606, "s": 27591, "text": "Morgan Stanley" }, { "code": null, "e": 27617, "s": 27606, "text": "palindrome" }, { "code": null, "e": 27623, "s": 27617, "text": "Paytm" }, { "code": null, "e": 27627, "s": 27623, "text": "TCS" }, { "code": null, "e": 27646, "s": 27627, "text": "School Programming" }, { "code": null, "e": 27654, "s": 27646, "text": "Strings" }, { "code": null, "e": 27660, "s": 27654, "text": "Paytm" }, { "code": null, "e": 27675, "s": 27660, "text": "Morgan Stanley" }, { "code": null, "e": 27683, "s": 27675, "text": "FactSet" }, { "code": null, "e": 27687, "s": 27683, "text": "TCS" }, { "code": null, "e": 27695, "s": 27687, "text": "Strings" }, { "code": null, "e": 27706, "s": 27695, "text": "palindrome" }, { "code": null, "e": 27804, "s": 27706, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27828, "s": 27804, "text": "C++ Classes and Objects" }, { "code": null, "e": 27847, "s": 27828, "text": "Interfaces in Java" }, { "code": null, "e": 27867, "s": 27847, "text": "Constructors in C++" }, { "code": null, "e": 27895, "s": 27867, "text": "Operator Overloading in C++" }, { "code": null, "e": 27919, "s": 27895, "text": "Copy Constructor in C++" }, { "code": null, "e": 27965, "s": 27919, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 28025, "s": 27965, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 28040, "s": 28025, "text": "C++ Data Types" }, { "code": null, "e": 28074, "s": 28040, "text": "Longest Common Subsequence | DP-4" } ]
Python | Check if variable is tuple - GeeksforGeeks
21 Nov, 2019 Sometimes, while working with Python, we can have a problem in which we need to check if a variable is single or a record. This has applications in domains in which we need to restrict the type of data we work on. Let’s discuss certain ways in which this task can be performed. Method #1 : Using type()This inbuilt function can be used as shorthand to perform this task. It checks for the type of variable and can be employed to check tuple as well. # Python3 code to demonstrate working of# Check if variable is tuple# using type() # initialize tuple test_tup = (4, 5, 6) # printing original tupleprint("The original tuple : " + str(test_tup)) # Check if variable is tuple# using type()res = type(test_tup) is tuple # printing resultprint("Is variable tuple ? : " + str(res)) The original tuple : (4, 5, 6) Is variable tuple ? : True Method #2 : Using isinstance()Yet another function that can be employed to perform this task. It also returns true, in case the parent class of variable(if exists) is a tuple. # Python3 code to demonstrate working of# Check if variable is tuple# using isinstance() # initialize tuple test_tup = (4, 5, 6) # printing original tupleprint("The original tuple : " + str(test_tup)) # Check if variable is tuple# using isinstance()res = isinstance(test_tup, tuple) # printing resultprint("Is variable tuple ? : " + str(res)) The original tuple : (4, 5, 6) Is variable tuple ? : True Python tuple-programs Python Python Programs 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 Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26105, "s": 26077, "text": "\n21 Nov, 2019" }, { "code": null, "e": 26383, "s": 26105, "text": "Sometimes, while working with Python, we can have a problem in which we need to check if a variable is single or a record. This has applications in domains in which we need to restrict the type of data we work on. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26555, "s": 26383, "text": "Method #1 : Using type()This inbuilt function can be used as shorthand to perform this task. It checks for the type of variable and can be employed to check tuple as well." }, { "code": "# Python3 code to demonstrate working of# Check if variable is tuple# using type() # initialize tuple test_tup = (4, 5, 6) # printing original tupleprint(\"The original tuple : \" + str(test_tup)) # Check if variable is tuple# using type()res = type(test_tup) is tuple # printing resultprint(\"Is variable tuple ? : \" + str(res))", "e": 26886, "s": 26555, "text": null }, { "code": null, "e": 26945, "s": 26886, "text": "The original tuple : (4, 5, 6)\nIs variable tuple ? : True\n" }, { "code": null, "e": 27123, "s": 26947, "text": "Method #2 : Using isinstance()Yet another function that can be employed to perform this task. It also returns true, in case the parent class of variable(if exists) is a tuple." }, { "code": "# Python3 code to demonstrate working of# Check if variable is tuple# using isinstance() # initialize tuple test_tup = (4, 5, 6) # printing original tupleprint(\"The original tuple : \" + str(test_tup)) # Check if variable is tuple# using isinstance()res = isinstance(test_tup, tuple) # printing resultprint(\"Is variable tuple ? : \" + str(res))", "e": 27471, "s": 27123, "text": null }, { "code": null, "e": 27530, "s": 27471, "text": "The original tuple : (4, 5, 6)\nIs variable tuple ? : True\n" }, { "code": null, "e": 27552, "s": 27530, "text": "Python tuple-programs" }, { "code": null, "e": 27559, "s": 27552, "text": "Python" }, { "code": null, "e": 27575, "s": 27559, "text": "Python Programs" }, { "code": null, "e": 27673, "s": 27575, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27691, "s": 27673, "text": "Python Dictionary" }, { "code": null, "e": 27726, "s": 27691, "text": "Read a file line by line in Python" }, { "code": null, "e": 27758, "s": 27726, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27780, "s": 27758, "text": "Enumerate() in Python" }, { "code": null, "e": 27822, "s": 27780, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27865, "s": 27822, "text": "Python program to convert a list to string" }, { "code": null, "e": 27887, "s": 27865, "text": "Defaultdict in Python" }, { "code": null, "e": 27926, "s": 27887, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27972, "s": 27926, "text": "Python | Split string into list of characters" } ]
C library function - mbstowcs()
The C library function size_t mbstowcs(schar_t *pwcs, const char *str, size_t n) converts the string of multi-byte characters pointed to, by the argument str to the array pointed to by pwcs. Following is the declaration for mbstowcs() function. size_t mbstowcs(schar_t *pwcs, const char *str, size_t n) pwcs − This is the pointer to an array of wchar_t elements that is long enough to store a wide string max characters long. pwcs − This is the pointer to an array of wchar_t elements that is long enough to store a wide string max characters long. str − This is the C multi-byte character string to be interpreted. str − This is the C multi-byte character string to be interpreted. n − This is the maximum number of wchar_t characters to be interpreted. n − This is the maximum number of wchar_t characters to be interpreted. This function returns the number of characters translated, excluding the ending null-character. If an invalid multi-byte character is encountered, a -1 value is returned. The following example shows the usage of mbstowcs() function. #include<stdio.h> #include<stdlib.h> #include<string.h> int main () { int len; char *pmbnull = NULL; char *pmb = (char *)malloc( MB_CUR_MAX ); wchar_t *pwc = L"Hi"; wchar_t *pwcs = (wchar_t *)malloc( sizeof( wchar_t )); printf("Converting to multibyte string\n"); len = wcstombs( pmb, pwc, MB_CUR_MAX); printf("Characters converted %d\n", len); printf("Hex value of first multibyte character: %#.4x\n", pmb); printf("Converting back to Wide-Character string\n"); len = mbstowcs( pwcs, pmb, MB_CUR_MAX); printf("Characters converted %d\n", len); printf("Hex value of first wide character %#.4x\n\n", pwcs); return(0); } Let us compile and run the above program that will produce the following result − Converting to multibyte string Characters converted 1 Hex value of first multibyte character: 0x19a60010 Converting back to Wide-Character string Characters converted 1 Hex value of first wide character 0x19a60030 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2198, "s": 2007, "text": "The C library function size_t mbstowcs(schar_t *pwcs, const char *str, size_t n) converts the string of multi-byte characters pointed to, by the argument str to the array pointed to by pwcs." }, { "code": null, "e": 2252, "s": 2198, "text": "Following is the declaration for mbstowcs() function." }, { "code": null, "e": 2310, "s": 2252, "text": "size_t mbstowcs(schar_t *pwcs, const char *str, size_t n)" }, { "code": null, "e": 2433, "s": 2310, "text": "pwcs − This is the pointer to an array of wchar_t elements that is long enough to store a wide string max characters long." }, { "code": null, "e": 2556, "s": 2433, "text": "pwcs − This is the pointer to an array of wchar_t elements that is long enough to store a wide string max characters long." }, { "code": null, "e": 2623, "s": 2556, "text": "str − This is the C multi-byte character string to be interpreted." }, { "code": null, "e": 2690, "s": 2623, "text": "str − This is the C multi-byte character string to be interpreted." }, { "code": null, "e": 2762, "s": 2690, "text": "n − This is the maximum number of wchar_t characters to be interpreted." }, { "code": null, "e": 2834, "s": 2762, "text": "n − This is the maximum number of wchar_t characters to be interpreted." }, { "code": null, "e": 3005, "s": 2834, "text": "This function returns the number of characters translated, excluding the ending null-character. If an invalid multi-byte character is encountered, a -1 value is returned." }, { "code": null, "e": 3067, "s": 3005, "text": "The following example shows the usage of mbstowcs() function." }, { "code": null, "e": 3739, "s": 3067, "text": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\nint main () {\n int len;\n char *pmbnull = NULL;\n char *pmb = (char *)malloc( MB_CUR_MAX );\n wchar_t *pwc = L\"Hi\";\n wchar_t *pwcs = (wchar_t *)malloc( sizeof( wchar_t ));\n\n printf(\"Converting to multibyte string\\n\");\n len = wcstombs( pmb, pwc, MB_CUR_MAX);\n printf(\"Characters converted %d\\n\", len);\n printf(\"Hex value of first multibyte character: %#.4x\\n\", pmb);\n \n printf(\"Converting back to Wide-Character string\\n\");\n len = mbstowcs( pwcs, pmb, MB_CUR_MAX);\n printf(\"Characters converted %d\\n\", len);\n printf(\"Hex value of first wide character %#.4x\\n\\n\", pwcs);\n \n return(0);\n}" }, { "code": null, "e": 3821, "s": 3739, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 4036, "s": 3821, "text": "Converting to multibyte string\nCharacters converted 1\nHex value of first multibyte character: 0x19a60010\nConverting back to Wide-Character string\nCharacters converted 1\nHex value of first wide character 0x19a60030\n" }, { "code": null, "e": 4069, "s": 4036, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4084, "s": 4069, "text": " Nishant Malik" }, { "code": null, "e": 4119, "s": 4084, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4134, "s": 4119, "text": " Nishant Malik" }, { "code": null, "e": 4169, "s": 4134, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4183, "s": 4169, "text": " Asif Hussain" }, { "code": null, "e": 4216, "s": 4183, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4234, "s": 4216, "text": " Richa Maheshwari" }, { "code": null, "e": 4269, "s": 4234, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4288, "s": 4269, "text": " Vandana Annavaram" }, { "code": null, "e": 4321, "s": 4288, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 4333, "s": 4321, "text": " Amit Diwan" }, { "code": null, "e": 4340, "s": 4333, "text": " Print" }, { "code": null, "e": 4351, "s": 4340, "text": " Add Notes" } ]
Essential commands for data preparation with Pandas | by Mahbubul Alam | Towards Data Science
If you like to cook you know this very well. Turning on the stove and cooking food is a tiny part of the whole cooking process. Much of your sweat and tears actually go into preparing the right ingredients. Cliché, but worth saying it again — data preparation is 80% of work in any data science project. Whether it is about making a dashboard, a simple statistical analysis, or fitting advanced machine learning model — it all starts with finding the data and transforming it into the right format so the algorithm can take care of the rest. If you are a Python fan, then pandas is your best friend in your data science journey. Equipped with all the tools, it helps you get through the most difficult parts of a project. That said, like any new tool you first need to learn it’s functionalities and how to put them into use. Many beginners in data science still struggle to make the best use of Pandas and instead spend much of their time on Stack Overflow. The principal reason for this is, I’d say, not being able to match Pandas functionalities with their analytics needs. Much of this struggle can be overcome simply by making an inventory of typical data preparation problems and matching them with appropriate Pandas tools. Below I am presenting a typical data preparation and exploratory analysis workflow and matching with necessary Pandas functions. I am not trying to document everything under the sun on Pandas rather demonstrating the process of creating your own data wrangling cheatsheet. Soon after you fire up your favorite Python IDE you might want to get started right away and import the necessary libraries. That’s fine, but you still need to set up your environment for setting the working directory, locate data and other files etc. # find out your current directoryimport osos.getcwd()# if you want to set a different working directoryos.chdir("folder-path")# to get a list of all files in the directoryos.listdir() Next up data import, and this is where you’ll be using Pandas for the first time. Your data may be sitting anywhere in the world — your local machine, SQL database, in the cloud or even in an online database. And data can be saved in a variety of formats — csv, txt, excel, sav etc. Depending on where the data is coming from and it’s file extension, you’d need different Pandas commands. Below are a couple of examples. # import pandas and numpy librariesimport pandas as pdimport numpy as np# import a csv file from local machinedf = pd.read_csv("file_path")# import a csv file from an online databasedf = pd.read_csv("https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv") After importing data you’d like to inspect it for a number of things such as the number of columns and rows, columns names etc. # description of index, entries, columns, data types, memory infodf.info() # check out first few rowsdf.head(5) # head# number of columns & rowsdf.shape # column namesdf.columns # number of unique values of a columndf["sepal_length"].nunique()# show unique values of a columndf["sepal_length"].unique()# number of unique values alltogetherdf.columns.nunique()# value countsdf['species'].value_counts() Next, check for NA, NaN or missing values. Some algorithms can handle missing values but others require that missing values are taken care of before putting data into use. Regardless, checking for missing values and understanding how to handle them is an essential part of your “getting to know” the data. # show null/NA values per columndf.isnull().sum()# show NA values as % of total observations per columndf.isnull().sum()*100/len(df)# drop all rows containing nulldf.dropna()# drop all columns containing nulldf.dropna(axis=1)# drop columns with less than 5 NA valuesdf.dropna(axis=1, thresh=5)# replace all na values with -9999df.fillna(-9999)# fill na values with NaNdf.fillna(np.NaN)# fill na values with stringsdf.fillna("data missing")# fill missing values with mean column valuesdf.fillna(df.mean())# replace na values of specific columns with mean valuedf["columnName"] = df["columnName"].fillna(df["columnName"].mean())# interpolation of missing values (useful in time-series)df["columnName"].interpolate() As often the case, you may need to perform a wide range of column operations such as renaming or dropping a column, sorting column values, creating new calculated columns etc. # select a columndf["sepal_length"]# select multiple columns and create a new dataframe XX = df[["sepal_length", "sepal_width", "species"]]# select a column by column numberdf.iloc[:, [1,3,4]]# drop a column from dataframe XX = X.drop("sepalL", axis=1)# save all columns to a listdf.columns.tolist()# Rename columnsdf.rename(columns={"old colum1": "new column1", "old column2": "new column2"})# sorting values by column "sepalW" in ascending orderdf.sort_values(by = "sepal_width", ascending = True)# add new calculated columndf['newcol'] = df["sepal_length"]*2# create a conditional calculated columndf['newcol'] = ["short" if i<3 else "long" for i in df["sepal_width"]] Up until the previous section you have mostly cleaned up your data, but another important part of data preparation is slicing and filtering data to go into the next round of the analytics pipeline. # select rows 3 to 10df.iloc[3:10,]# select rows 3 to 49 and columns 1 to 3df.iloc[3:50, 1:4]# randomly select 10 rowsdf.sample(10)# find rows with specific stringsdf[df["species"].isin(["Iris-setosa"])]# conditional filteringdf[df.sepal_length >= 5]# filtering rows with multiple values e.g. 0.2, 0.3df[df["petal_width"].isin([0.2, 0.3])]# multi-conditional filteringdf[(df.petal_length > 1) & (df.species=="Iris-setosa") | (df.sepal_width < 3)]# drop rowsdf.drop(df.index[1]) # 1 is row index to be deleted Last but not least, often you will need to group data by different categories — and it is especially useful in exploratory data analysis and in getting insights on categorical variables. # data grouped by column "species"X = df.groupby("species")# return mean values of a column ("sepal_length" ) grouped by "species" columndf.groupby("spp")["sepal_length"].mean()# return mean values of ALL columns grouped by "species" categorydf.groupby("species").mean()# get counts in different categoriesdf.groupby("spp").nunique() The purpose of this article was to show some essential Pandas functions needed for making data analysis-ready. In this demonstration, I followed a typical analytics process rather than showing codes in a random fashion, which will allow data scientists to find the right tool in the right order in the project. Of course, I did not intend to show every single code required to deal with every single problem in data preparation, rather the intention was to show how to create an essential Pandas cheatsheet. Hope this was useful. If you liked this article feel free to follow me on Twitter.
[ { "code": null, "e": 379, "s": 172, "text": "If you like to cook you know this very well. Turning on the stove and cooking food is a tiny part of the whole cooking process. Much of your sweat and tears actually go into preparing the right ingredients." }, { "code": null, "e": 715, "s": 379, "text": "Cliché, but worth saying it again — data preparation is 80% of work in any data science project. Whether it is about making a dashboard, a simple statistical analysis, or fitting advanced machine learning model — it all starts with finding the data and transforming it into the right format so the algorithm can take care of the rest." }, { "code": null, "e": 895, "s": 715, "text": "If you are a Python fan, then pandas is your best friend in your data science journey. Equipped with all the tools, it helps you get through the most difficult parts of a project." }, { "code": null, "e": 1250, "s": 895, "text": "That said, like any new tool you first need to learn it’s functionalities and how to put them into use. Many beginners in data science still struggle to make the best use of Pandas and instead spend much of their time on Stack Overflow. The principal reason for this is, I’d say, not being able to match Pandas functionalities with their analytics needs." }, { "code": null, "e": 1677, "s": 1250, "text": "Much of this struggle can be overcome simply by making an inventory of typical data preparation problems and matching them with appropriate Pandas tools. Below I am presenting a typical data preparation and exploratory analysis workflow and matching with necessary Pandas functions. I am not trying to document everything under the sun on Pandas rather demonstrating the process of creating your own data wrangling cheatsheet." }, { "code": null, "e": 1929, "s": 1677, "text": "Soon after you fire up your favorite Python IDE you might want to get started right away and import the necessary libraries. That’s fine, but you still need to set up your environment for setting the working directory, locate data and other files etc." }, { "code": null, "e": 2113, "s": 1929, "text": "# find out your current directoryimport osos.getcwd()# if you want to set a different working directoryos.chdir(\"folder-path\")# to get a list of all files in the directoryos.listdir()" }, { "code": null, "e": 2195, "s": 2113, "text": "Next up data import, and this is where you’ll be using Pandas for the first time." }, { "code": null, "e": 2396, "s": 2195, "text": "Your data may be sitting anywhere in the world — your local machine, SQL database, in the cloud or even in an online database. And data can be saved in a variety of formats — csv, txt, excel, sav etc." }, { "code": null, "e": 2534, "s": 2396, "text": "Depending on where the data is coming from and it’s file extension, you’d need different Pandas commands. Below are a couple of examples." }, { "code": null, "e": 2812, "s": 2534, "text": "# import pandas and numpy librariesimport pandas as pdimport numpy as np# import a csv file from local machinedf = pd.read_csv(\"file_path\")# import a csv file from an online databasedf = pd.read_csv(\"https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv\")" }, { "code": null, "e": 2940, "s": 2812, "text": "After importing data you’d like to inspect it for a number of things such as the number of columns and rows, columns names etc." }, { "code": null, "e": 3342, "s": 2940, "text": "# description of index, entries, columns, data types, memory infodf.info() # check out first few rowsdf.head(5) # head# number of columns & rowsdf.shape # column namesdf.columns # number of unique values of a columndf[\"sepal_length\"].nunique()# show unique values of a columndf[\"sepal_length\"].unique()# number of unique values alltogetherdf.columns.nunique()# value countsdf['species'].value_counts()" }, { "code": null, "e": 3648, "s": 3342, "text": "Next, check for NA, NaN or missing values. Some algorithms can handle missing values but others require that missing values are taken care of before putting data into use. Regardless, checking for missing values and understanding how to handle them is an essential part of your “getting to know” the data." }, { "code": null, "e": 4362, "s": 3648, "text": "# show null/NA values per columndf.isnull().sum()# show NA values as % of total observations per columndf.isnull().sum()*100/len(df)# drop all rows containing nulldf.dropna()# drop all columns containing nulldf.dropna(axis=1)# drop columns with less than 5 NA valuesdf.dropna(axis=1, thresh=5)# replace all na values with -9999df.fillna(-9999)# fill na values with NaNdf.fillna(np.NaN)# fill na values with stringsdf.fillna(\"data missing\")# fill missing values with mean column valuesdf.fillna(df.mean())# replace na values of specific columns with mean valuedf[\"columnName\"] = df[\"columnName\"].fillna(df[\"columnName\"].mean())# interpolation of missing values (useful in time-series)df[\"columnName\"].interpolate()" }, { "code": null, "e": 4538, "s": 4362, "text": "As often the case, you may need to perform a wide range of column operations such as renaming or dropping a column, sorting column values, creating new calculated columns etc." }, { "code": null, "e": 5211, "s": 4538, "text": "# select a columndf[\"sepal_length\"]# select multiple columns and create a new dataframe XX = df[[\"sepal_length\", \"sepal_width\", \"species\"]]# select a column by column numberdf.iloc[:, [1,3,4]]# drop a column from dataframe XX = X.drop(\"sepalL\", axis=1)# save all columns to a listdf.columns.tolist()# Rename columnsdf.rename(columns={\"old colum1\": \"new column1\", \"old column2\": \"new column2\"})# sorting values by column \"sepalW\" in ascending orderdf.sort_values(by = \"sepal_width\", ascending = True)# add new calculated columndf['newcol'] = df[\"sepal_length\"]*2# create a conditional calculated columndf['newcol'] = [\"short\" if i<3 else \"long\" for i in df[\"sepal_width\"]] " }, { "code": null, "e": 5409, "s": 5211, "text": "Up until the previous section you have mostly cleaned up your data, but another important part of data preparation is slicing and filtering data to go into the next round of the analytics pipeline." }, { "code": null, "e": 5918, "s": 5409, "text": "# select rows 3 to 10df.iloc[3:10,]# select rows 3 to 49 and columns 1 to 3df.iloc[3:50, 1:4]# randomly select 10 rowsdf.sample(10)# find rows with specific stringsdf[df[\"species\"].isin([\"Iris-setosa\"])]# conditional filteringdf[df.sepal_length >= 5]# filtering rows with multiple values e.g. 0.2, 0.3df[df[\"petal_width\"].isin([0.2, 0.3])]# multi-conditional filteringdf[(df.petal_length > 1) & (df.species==\"Iris-setosa\") | (df.sepal_width < 3)]# drop rowsdf.drop(df.index[1]) # 1 is row index to be deleted" }, { "code": null, "e": 6105, "s": 5918, "text": "Last but not least, often you will need to group data by different categories — and it is especially useful in exploratory data analysis and in getting insights on categorical variables." }, { "code": null, "e": 6440, "s": 6105, "text": "# data grouped by column \"species\"X = df.groupby(\"species\")# return mean values of a column (\"sepal_length\" ) grouped by \"species\" columndf.groupby(\"spp\")[\"sepal_length\"].mean()# return mean values of ALL columns grouped by \"species\" categorydf.groupby(\"species\").mean()# get counts in different categoriesdf.groupby(\"spp\").nunique() " }, { "code": null, "e": 6948, "s": 6440, "text": "The purpose of this article was to show some essential Pandas functions needed for making data analysis-ready. In this demonstration, I followed a typical analytics process rather than showing codes in a random fashion, which will allow data scientists to find the right tool in the right order in the project. Of course, I did not intend to show every single code required to deal with every single problem in data preparation, rather the intention was to show how to create an essential Pandas cheatsheet." } ]
Clojure - Recursion
We have seen the recur statement in an earlier topic and whereas the ‘for’ loop is somewhat like a loop, recur is a real loop in Clojure. If you have a programming background, you may have heard of tail recursion, which is a major feature of functional languages. This recur special form is the one that implements tail recursion. As the word “tail recursion” indicates, recur must be called in the tail position. In other words, recur must be the last thing to be evaluated. The simplest example of the recur statement is used within the ‘for’ loop. In the following example, the recur statement is used to change the value of the variable ‘i’ and feed the value of the variable back to the loop expression. (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (loop [i 0] (when (< i 5) (println i) (recur (inc i))))) (Example) The above program produces the following output. 0 1 2 3 4 Print Add Notes Bookmark this page
[ { "code": null, "e": 2512, "s": 2374, "text": "We have seen the recur statement in an earlier topic and whereas the ‘for’ loop is somewhat like a loop, recur is a real loop in Clojure." }, { "code": null, "e": 2850, "s": 2512, "text": "If you have a programming background, you may have heard of tail recursion, which is a major feature of functional languages. This recur special form is the one that implements tail recursion. As the word “tail recursion” indicates, recur must be called in the tail position. In other words, recur must be the last thing to be evaluated." }, { "code": null, "e": 3083, "s": 2850, "text": "The simplest example of the recur statement is used within the ‘for’ loop. In the following example, the recur statement is used to change the value of the variable ‘i’ and feed the value of the variable back to the loop expression." }, { "code": null, "e": 3270, "s": 3083, "text": "(ns clojure.examples.hello\n (:gen-class))\n\n;; This program displays Hello World\n(defn Example []\n (loop [i 0]\n (when (< i 5)\n (println i)\n (recur (inc i)))))\n(Example)" }, { "code": null, "e": 3319, "s": 3270, "text": "The above program produces the following output." }, { "code": null, "e": 3330, "s": 3319, "text": "0\n1\n2\n3\n4\n" }, { "code": null, "e": 3337, "s": 3330, "text": " Print" }, { "code": null, "e": 3348, "s": 3337, "text": " Add Notes" } ]
Dataloader for sequential data using PyTorch deep learning framework — Part 2 | by Alleviate and Elevate (A & E) | May, 2021 | Medium | Towards Data Science
Deep learning and machine learning algorithms are ruling the world these days. PyTorch is one of the most commonly used deep learning framework used for implementing various deep learning algorithms. On the other hand, the learning-based method essentially requires some annotated training dataset which can be used by the model to extract the relation between input data and labels. In order to feed data to the neural network, we define a data loader. In this blog, we will see how to write a data loader for different datasets in the PyTorch framework. We will be working on dog vs cat image classification problem. We have to classify whether the given image is of cat or dog and the dataset can be downloaded from here. The training dataset contains a total of 25,000 images. As this is a classification problem, the label for dog is “0” and the label for cat is “1”. Let’s start by importing all the required libraries. import osfrom PIL import Imageimport torchfrom torch.utils.data import DataLoader, Datasetimport torchvision.transforms as transformsimport torch.nn as nn The dataset class for PyTorch framework is defined as a class, whose basic structure is as follows class data(Dataset): def __init__(self, param1, param2): #the function is initialised here def __len__(self): #the function returns length of data def __getitem__(self, index): #gives one item at a time The ultimate aim of this class is to provide one data point at a time using function __getitem__. This is done using index which is passed to the function internally, using a sampler function defined in the Dataloader (will be discussed in the coming blog). The function __init__ is called when you initialize the object for the dataset. Here, you can pass multiple arguments that will be useful for writing __getitem__. The __len__ function is used to return the total length of the dataset. Based on this, index will be generated which will then be provided to __getitem__ . The format of the dog vs cat dataset is as follows -: data/ - dog_1.jpg - dog_2.jpg ... ... ... - cat_1.jpg - cat_2.jpg ... ... ... Now that we understand the components required for writing our data loader, let’s delve deeper into our use case. class data(Dataset): def __init__(self, path, transform): self.files = os.listdir(path) self.transform = transform self.path = path def __len__(self): return len(self.files) def __getitem__(self, index): filename = self.files[index] input = Image.open(os.path.join(self.path, filename)) label = 0 if filename.find("dog")>=0 else 1 img_as_tensor = self.transform(input) return img_as_tensor, labeltransformations = transforms.Compose( [transforms.Resize((224,224)),transforms.ToTensor()] )path = "./data"train_dataset = data(path, transformations)dataloader = DataLoader(train_dataset, batch_size=Train_Batch_Size, shuffle=True) Let us first understand the function __init__. The class data is initialized with two arguments, path and transform which are passed as arguments to __init__. When we declare an object of this class it internally calls __init__ which stores the list of names of files self.files, the transform in self.transform and the path in self.path. Since the __len__ is used to return the length of the whole dataset, I have used len(self.files) to return the same. The function __getitem__ is the most crucial, it loads the image, then resizes it, and then converts it into a tensor. An important thing to note here is that the data provided to the neural network should always be normalized. We take care of normalization using transforms.ToTensor(). Finally, __getitem__ returns two things, image_as_tensor and label for the corresponding data point. After initializing the class data, we use a DataLoader function which automatically batches the whole data into a defined batch size. So if your original datapoint size is (3, 224, 224) (that you get from __getitem__), each item of the dataloader will have size (batch_size, 3, 224, 224) i.e. it automatically samples batch_size number of datapoints. This is possible in our case because the size of images is constant so the DataLoader function is able to create batches automatically. However, in cases like Natural language processing when the size is not constant, we need to write our own batching function. Let’s deal with sequential dataset i.e. sentences, time series, audio, etc. now. Here __getitem__ will no longer give us data points with the same size. For example, consider the task of sentiment classification (explained here), then one sentence can be “The flight service was very good” and other could be “I did not get my baggage on the belt, pathetic service.” Here the length of both sentences is different. To tackle this, let’s answer three questions first. What is batching? — Batching means to merge tensors of multiple data points into a single tensorWhy do we need batching? — Batching is used to make computation faster, because of batching we can process multiple data points together instead of just one at a time.How is batching done? — Since we are merging multiple tensors here, the size along each dimension of the tensor needs to be the same. Since out data points are of varied sizes we have a problem in our hands. What is batching? — Batching means to merge tensors of multiple data points into a single tensor Why do we need batching? — Batching is used to make computation faster, because of batching we can process multiple data points together instead of just one at a time. How is batching done? — Since we are merging multiple tensors here, the size along each dimension of the tensor needs to be the same. Since out data points are of varied sizes we have a problem in our hands. Mainly we need to now tackle problem of batching. For the purpose of our discussion here, we will use the IMDB dataset which is a review dataset and can be downloaded from here. Since we are dealing with sentences here, the way to process the dataset will vary a bit. Since the neural networks only understand numbers, not words, we will have to convert each word into a number. In order to do that we have to build a vocabulary as explained in the following code. The function reader is used to read the whole data and it returns a list of all sentences and labels “0” for negative review and “1” for positive review. The function build_vocab takes data and minimum word count as input and gives as output a mapping (named “word2id”) of each word to a unique number. For every unknown word going forward the corresponding number will be 1. Moving on to writing a dataset class for the sequential dataset. Our objective here is to output one item at a time, given an index. As the functionality of different functions is already discussed above, I will briefly recap. The function __init__ takes word2id mapping and train_path. Then __init__ calls reader to get data and labels corresponding to the sentences. The function __len__ returns the length of the whole dataset i.e. self.data. The function preprocess converts the input sentence into a tensor of numbers, where each number corresponds to the word in the sentence. The function __getitem__ is used to output one processed data point at a time with the help of the index. Coming on to the solution of our problem of each datapoint having different size. The following code defines collate_fn. This function is used to take care of batching data points of different sizes. train_dataset = Dataset_seq(word2id, train_path)train_dataloader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True,collate_fn=collate_fn) A point to note here is that in a list of tuple, each tuple can have different sizes but in a tensor, the size along all the dimensions need to be same in order to merge them. The collate_fn is automatically given one input named data, which is a list of tuples with length equal to batch size. Each tuple contains tensors of numbers (seq returned from __getitem__) and their corresponding label. For the sake of simplicity, we will call them sequence and label respectively. So ultimately we have to convert each sequence in such a manner that their size becomes constant. To achieve that we perform zero-padding as shown in the code above. Since zero padding is uniformly used for the whole dataset, the model learns that it is not of much use and that it just represents waste values. We have reached a solution for sure but the question remains, is it an optimal solution? In cases when the original sizes of all the sequence vary with a huge difference or in other words with a huge variance, we will end up wasting a lot of GPU memory with zero padding, which is ultimately of no use. There has to be a better way that minimizes the requirement of zero padding! This problem and its solution is discussed here. Become a Medium member to unlock and read many other stories on medium. Follow us on Medium for reading more such blog posts.
[ { "code": null, "e": 727, "s": 171, "text": "Deep learning and machine learning algorithms are ruling the world these days. PyTorch is one of the most commonly used deep learning framework used for implementing various deep learning algorithms. On the other hand, the learning-based method essentially requires some annotated training dataset which can be used by the model to extract the relation between input data and labels. In order to feed data to the neural network, we define a data loader. In this blog, we will see how to write a data loader for different datasets in the PyTorch framework." }, { "code": null, "e": 1044, "s": 727, "text": "We will be working on dog vs cat image classification problem. We have to classify whether the given image is of cat or dog and the dataset can be downloaded from here. The training dataset contains a total of 25,000 images. As this is a classification problem, the label for dog is “0” and the label for cat is “1”." }, { "code": null, "e": 1097, "s": 1044, "text": "Let’s start by importing all the required libraries." }, { "code": null, "e": 1252, "s": 1097, "text": "import osfrom PIL import Imageimport torchfrom torch.utils.data import DataLoader, Datasetimport torchvision.transforms as transformsimport torch.nn as nn" }, { "code": null, "e": 1351, "s": 1252, "text": "The dataset class for PyTorch framework is defined as a class, whose basic structure is as follows" }, { "code": null, "e": 1593, "s": 1351, "text": "class data(Dataset): def __init__(self, param1, param2): #the function is initialised here def __len__(self): #the function returns length of data def __getitem__(self, index): #gives one item at a time" }, { "code": null, "e": 1851, "s": 1593, "text": "The ultimate aim of this class is to provide one data point at a time using function __getitem__. This is done using index which is passed to the function internally, using a sampler function defined in the Dataloader (will be discussed in the coming blog)." }, { "code": null, "e": 2014, "s": 1851, "text": "The function __init__ is called when you initialize the object for the dataset. Here, you can pass multiple arguments that will be useful for writing __getitem__." }, { "code": null, "e": 2170, "s": 2014, "text": "The __len__ function is used to return the total length of the dataset. Based on this, index will be generated which will then be provided to __getitem__ ." }, { "code": null, "e": 2224, "s": 2170, "text": "The format of the dog vs cat dataset is as follows -:" }, { "code": null, "e": 2328, "s": 2224, "text": "data/ - dog_1.jpg - dog_2.jpg ... ... ... - cat_1.jpg - cat_2.jpg ... ... ..." }, { "code": null, "e": 2442, "s": 2328, "text": "Now that we understand the components required for writing our data loader, let’s delve deeper into our use case." }, { "code": null, "e": 3161, "s": 2442, "text": "class data(Dataset): def __init__(self, path, transform): self.files = os.listdir(path) self.transform = transform self.path = path def __len__(self): return len(self.files) def __getitem__(self, index): filename = self.files[index] input = Image.open(os.path.join(self.path, filename)) label = 0 if filename.find(\"dog\")>=0 else 1 img_as_tensor = self.transform(input) return img_as_tensor, labeltransformations = transforms.Compose( [transforms.Resize((224,224)),transforms.ToTensor()] )path = \"./data\"train_dataset = data(path, transformations)dataloader = DataLoader(train_dataset, batch_size=Train_Batch_Size, shuffle=True)" }, { "code": null, "e": 3500, "s": 3161, "text": "Let us first understand the function __init__. The class data is initialized with two arguments, path and transform which are passed as arguments to __init__. When we declare an object of this class it internally calls __init__ which stores the list of names of files self.files, the transform in self.transform and the path in self.path." }, { "code": null, "e": 3617, "s": 3500, "text": "Since the __len__ is used to return the length of the whole dataset, I have used len(self.files) to return the same." }, { "code": null, "e": 4005, "s": 3617, "text": "The function __getitem__ is the most crucial, it loads the image, then resizes it, and then converts it into a tensor. An important thing to note here is that the data provided to the neural network should always be normalized. We take care of normalization using transforms.ToTensor(). Finally, __getitem__ returns two things, image_as_tensor and label for the corresponding data point." }, { "code": null, "e": 4618, "s": 4005, "text": "After initializing the class data, we use a DataLoader function which automatically batches the whole data into a defined batch size. So if your original datapoint size is (3, 224, 224) (that you get from __getitem__), each item of the dataloader will have size (batch_size, 3, 224, 224) i.e. it automatically samples batch_size number of datapoints. This is possible in our case because the size of images is constant so the DataLoader function is able to create batches automatically. However, in cases like Natural language processing when the size is not constant, we need to write our own batching function." }, { "code": null, "e": 5033, "s": 4618, "text": "Let’s deal with sequential dataset i.e. sentences, time series, audio, etc. now. Here __getitem__ will no longer give us data points with the same size. For example, consider the task of sentiment classification (explained here), then one sentence can be “The flight service was very good” and other could be “I did not get my baggage on the belt, pathetic service.” Here the length of both sentences is different." }, { "code": null, "e": 5085, "s": 5033, "text": "To tackle this, let’s answer three questions first." }, { "code": null, "e": 5556, "s": 5085, "text": "What is batching? — Batching means to merge tensors of multiple data points into a single tensorWhy do we need batching? — Batching is used to make computation faster, because of batching we can process multiple data points together instead of just one at a time.How is batching done? — Since we are merging multiple tensors here, the size along each dimension of the tensor needs to be the same. Since out data points are of varied sizes we have a problem in our hands." }, { "code": null, "e": 5653, "s": 5556, "text": "What is batching? — Batching means to merge tensors of multiple data points into a single tensor" }, { "code": null, "e": 5821, "s": 5653, "text": "Why do we need batching? — Batching is used to make computation faster, because of batching we can process multiple data points together instead of just one at a time." }, { "code": null, "e": 6029, "s": 5821, "text": "How is batching done? — Since we are merging multiple tensors here, the size along each dimension of the tensor needs to be the same. Since out data points are of varied sizes we have a problem in our hands." }, { "code": null, "e": 6079, "s": 6029, "text": "Mainly we need to now tackle problem of batching." }, { "code": null, "e": 6494, "s": 6079, "text": "For the purpose of our discussion here, we will use the IMDB dataset which is a review dataset and can be downloaded from here. Since we are dealing with sentences here, the way to process the dataset will vary a bit. Since the neural networks only understand numbers, not words, we will have to convert each word into a number. In order to do that we have to build a vocabulary as explained in the following code." }, { "code": null, "e": 6648, "s": 6494, "text": "The function reader is used to read the whole data and it returns a list of all sentences and labels “0” for negative review and “1” for positive review." }, { "code": null, "e": 6870, "s": 6648, "text": "The function build_vocab takes data and minimum word count as input and gives as output a mapping (named “word2id”) of each word to a unique number. For every unknown word going forward the corresponding number will be 1." }, { "code": null, "e": 7003, "s": 6870, "text": "Moving on to writing a dataset class for the sequential dataset. Our objective here is to output one item at a time, given an index." }, { "code": null, "e": 7097, "s": 7003, "text": "As the functionality of different functions is already discussed above, I will briefly recap." }, { "code": null, "e": 7239, "s": 7097, "text": "The function __init__ takes word2id mapping and train_path. Then __init__ calls reader to get data and labels corresponding to the sentences." }, { "code": null, "e": 7316, "s": 7239, "text": "The function __len__ returns the length of the whole dataset i.e. self.data." }, { "code": null, "e": 7453, "s": 7316, "text": "The function preprocess converts the input sentence into a tensor of numbers, where each number corresponds to the word in the sentence." }, { "code": null, "e": 7559, "s": 7453, "text": "The function __getitem__ is used to output one processed data point at a time with the help of the index." }, { "code": null, "e": 7759, "s": 7559, "text": "Coming on to the solution of our problem of each datapoint having different size. The following code defines collate_fn. This function is used to take care of batching data points of different sizes." }, { "code": null, "e": 7919, "s": 7759, "text": "train_dataset = Dataset_seq(word2id, train_path)train_dataloader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True,collate_fn=collate_fn)" }, { "code": null, "e": 8095, "s": 7919, "text": "A point to note here is that in a list of tuple, each tuple can have different sizes but in a tensor, the size along all the dimensions need to be same in order to merge them." }, { "code": null, "e": 8707, "s": 8095, "text": "The collate_fn is automatically given one input named data, which is a list of tuples with length equal to batch size. Each tuple contains tensors of numbers (seq returned from __getitem__) and their corresponding label. For the sake of simplicity, we will call them sequence and label respectively. So ultimately we have to convert each sequence in such a manner that their size becomes constant. To achieve that we perform zero-padding as shown in the code above. Since zero padding is uniformly used for the whole dataset, the model learns that it is not of much use and that it just represents waste values." }, { "code": null, "e": 9136, "s": 8707, "text": "We have reached a solution for sure but the question remains, is it an optimal solution? In cases when the original sizes of all the sequence vary with a huge difference or in other words with a huge variance, we will end up wasting a lot of GPU memory with zero padding, which is ultimately of no use. There has to be a better way that minimizes the requirement of zero padding! This problem and its solution is discussed here." } ]
Check if a value is present in an Array in Java
At first sort the array − int intArr[] = {55, 20, 10, 60, 12, 90, 59}; // sorting array Arrays.sort(intArr); Now, set the value to be searched in an int variable − int searchVal = 12; Check for the presence of a value in an array − int retVal = Arrays.binarySearch(intArr,searchVal); boolean res = retVal > 0 ? true : false; Following is an example to check if a value is present in an array − import java.util.Arrays; public class Main { public static void main(String[] args) { // initializing unsorted int array int intArr[] = {55, 20, 10, 60, 12, 90, 59}; // sorting array Arrays.sort(intArr); // let us print all the elements available in list System.out.println("The sorted int array is:"); for (int number : intArr) { System.out.println("Number = " + number); } // entering the value to be searched int searchVal = 12; int retVal = Arrays.binarySearch(intArr,searchVal); boolean res = retVal > 0 ? true : false; System.out.println("Is element 12 in the array? = " + res); System.out.println("The index of element 12 is : " + retVal); } } The sorted int array is: Number = 10 Number = 12 Number = 20 Number = 55 Number = 59 Number = 60 Number = 90 Is element 12 in the array? = true The index of element 12 is : 1
[ { "code": null, "e": 1088, "s": 1062, "text": "At first sort the array −" }, { "code": null, "e": 1171, "s": 1088, "text": "int intArr[] = {55, 20, 10, 60, 12, 90, 59};\n// sorting array\nArrays.sort(intArr);" }, { "code": null, "e": 1226, "s": 1171, "text": "Now, set the value to be searched in an int variable −" }, { "code": null, "e": 1246, "s": 1226, "text": "int searchVal = 12;" }, { "code": null, "e": 1294, "s": 1246, "text": "Check for the presence of a value in an array −" }, { "code": null, "e": 1387, "s": 1294, "text": "int retVal = Arrays.binarySearch(intArr,searchVal);\nboolean res = retVal > 0 ? true : false;" }, { "code": null, "e": 1456, "s": 1387, "text": "Following is an example to check if a value is present in an array −" }, { "code": null, "e": 2206, "s": 1456, "text": "import java.util.Arrays;\npublic class Main {\n public static void main(String[] args) {\n // initializing unsorted int array\n int intArr[] = {55, 20, 10, 60, 12, 90, 59};\n // sorting array\n Arrays.sort(intArr);\n // let us print all the elements available in list\n System.out.println(\"The sorted int array is:\");\n for (int number : intArr) {\n System.out.println(\"Number = \" + number);\n }\n // entering the value to be searched\n int searchVal = 12;\n int retVal = Arrays.binarySearch(intArr,searchVal);\n boolean res = retVal > 0 ? true : false;\n System.out.println(\"Is element 12 in the array? = \" + res);\n System.out.println(\"The index of element 12 is : \" + retVal);\n }\n}" }, { "code": null, "e": 2381, "s": 2206, "text": "The sorted int array is:\nNumber = 10\nNumber = 12\nNumber = 20\nNumber = 55\nNumber = 59\nNumber = 60\nNumber = 90\nIs element 12 in the array? = true\nThe index of element 12 is : 1" } ]
Function prototypes in JavaScript
Functions created in JavaScript always have the prototype property added by the JavaScript engine to them. The prototype property is an object which contains the constructor property by default. The function protoype can be accessed by − functionName.prototype When objects are creating using the function constructor, this prototype property can be used to share methods or properties between the objects created by that function constructor. Following is the code for function prototypes in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Function prototypes in JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">Click Here</button> <h3>Click on the above button to call the welcome method of person1 and person2 object</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); function personConstructor(fName, lName) { this.fName = fName; this.lName = lName; } personConstructor.prototype.welcome = function () { return "Welcome " + this.fName + " " + this.lName; }; let person1 = new personConstructor("Rohan", "Sharma"); let person2 = new personConstructor("Shawn", "Smith"); BtnEle.addEventListener("click", () => { resEle.innerHTML = "person1.welcome() = " + person1.welcome() + "<br>"; resEle.innerHTML += "person2.welcome() = " + person2.welcome() + "<br>"; }); </script> </body> </html> On clicking the ‘Click Here’ button −
[ { "code": null, "e": 1300, "s": 1062, "text": "Functions created in JavaScript always have the prototype property added by the JavaScript\nengine to them. The prototype property is an object which contains the constructor property\nby default. The function protoype can be accessed by −" }, { "code": null, "e": 1323, "s": 1300, "text": "functionName.prototype" }, { "code": null, "e": 1506, "s": 1323, "text": "When objects are creating using the function constructor, this prototype property can be used to share methods or properties between the objects created by that function constructor." }, { "code": null, "e": 1568, "s": 1506, "text": "Following is the code for function prototypes in JavaScript −" }, { "code": null, "e": 1579, "s": 1568, "text": " Live Demo" }, { "code": null, "e": 2835, "s": 1579, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Function prototypes in JavaScript</h1>\n<div class=\"result\"></div>\n<br />\n<button class=\"Btn\">Click Here</button>\n<h3>Click on the above button to call the welcome method of person1 and person2 object</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n function personConstructor(fName, lName) {\n this.fName = fName;\n this.lName = lName;\n }\n personConstructor.prototype.welcome = function () {\n return \"Welcome \" + this.fName + \" \" + this.lName;\n };\n let person1 = new personConstructor(\"Rohan\", \"Sharma\");\n let person2 = new personConstructor(\"Shawn\", \"Smith\");\n BtnEle.addEventListener(\"click\", () => {\n resEle.innerHTML = \"person1.welcome() = \" + person1.welcome() + \"<br>\";\n resEle.innerHTML += \"person2.welcome() = \" + person2.welcome() + \"<br>\";\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2873, "s": 2835, "text": "On clicking the ‘Click Here’ button −" } ]
CICS - WRITE
Write command is used to add new records to a file. The parameters used in Write command are same as we had described before. Data is picked from the data area mentioned in the FROM clause. Following is the syntax for Write command − EXEC CICS WRITE FILE(name) FROM(data-area) RIDFLD(data-area) LENGTH(data-value) KEYLENGTH(data-value) END-EXEC. Following is the example to write a record in 'FL001' file where Student-id is the primary key and a new record with 101 student id will be written in the file − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-STD-REC-LEN PIC S9(4) COMP. 01 WS-STD-KEY-LEN PIC S9(4) COMP. 01 WS-STD-REC-KEY PIC 9(3). 01 WS-STD-REC PIC X(70). PROCEDURE DIVISION. MOVE +70 TO WS-STD-REC-LEN. MOVE ‘101’ TO WS-STD-REC-KEY. MOVE 3 TO WS-STD-KEY-LEN. MOVE '101Mohtahim M TutorialsPoint' TO WS-STD-REC. EXEC CICS WRITE FILE ('FL001') FROM (WS-STD-REC) LENGTH (WS-STD-REC-LEN) RIDFLD (WS-STD-REC-KEY) KEYLENGTH (WS-STD-KEY-LEN) END-EXEC. The following table shows the list of exceptions that arise during a WRITE statement − NOTOPEN File is not open. FILENOTFOUND File entry is not made in FCT. LENGERR Mismatch between the length specified in command and actual length of the record. NOTAUTH If the user does not have enough permissions to use the file. DUPKEY If more than 1 record satisfy the condition on the alternate key. NOSPACE There is not enough space in the dataset. Print Add Notes Bookmark this page
[ { "code": null, "e": 2160, "s": 1926, "text": "Write command is used to add new records to a file. The parameters used in Write command are same as we had described before. Data is picked from the data area mentioned in the FROM clause. Following is the syntax for Write command −" }, { "code": null, "e": 2288, "s": 2160, "text": "EXEC CICS WRITE\n FILE(name)\n FROM(data-area)\n RIDFLD(data-area)\n LENGTH(data-value)\n KEYLENGTH(data-value)\nEND-EXEC.\n" }, { "code": null, "e": 2450, "s": 2288, "text": "Following is the example to write a record in 'FL001' file where Student-id is the primary key and a new record with 101 student id will be written in the file −" }, { "code": null, "e": 3094, "s": 2450, "text": "IDENTIFICATION DIVISION. \nPROGRAM-ID. HELLO. \nDATA DIVISION. \nWORKING-STORAGE SECTION.\n01 WS-STD-REC-LEN PIC S9(4) COMP.\n01 WS-STD-KEY-LEN PIC S9(4) COMP.\n01 WS-STD-REC-KEY PIC 9(3).\n01 WS-STD-REC PIC X(70).\nPROCEDURE DIVISION.\nMOVE +70 TO WS-STD-REC-LEN.\nMOVE ‘101’ TO WS-STD-REC-KEY.\nMOVE 3 TO WS-STD-KEY-LEN.\nMOVE '101Mohtahim M TutorialsPoint' TO WS-STD-REC.\nEXEC CICS WRITE\n FILE ('FL001')\n FROM (WS-STD-REC)\n LENGTH (WS-STD-REC-LEN)\n RIDFLD (WS-STD-REC-KEY)\n KEYLENGTH (WS-STD-KEY-LEN)\nEND-EXEC." }, { "code": null, "e": 3181, "s": 3094, "text": "The following table shows the list of exceptions that arise during a WRITE statement −" }, { "code": null, "e": 3189, "s": 3181, "text": "NOTOPEN" }, { "code": null, "e": 3207, "s": 3189, "text": "File is not open." }, { "code": null, "e": 3220, "s": 3207, "text": "FILENOTFOUND" }, { "code": null, "e": 3251, "s": 3220, "text": "File entry is not made in FCT." }, { "code": null, "e": 3259, "s": 3251, "text": "LENGERR" }, { "code": null, "e": 3341, "s": 3259, "text": "Mismatch between the length specified in command and actual length of the record." }, { "code": null, "e": 3349, "s": 3341, "text": "NOTAUTH" }, { "code": null, "e": 3411, "s": 3349, "text": "If the user does not have enough permissions to use the file." }, { "code": null, "e": 3418, "s": 3411, "text": "DUPKEY" }, { "code": null, "e": 3484, "s": 3418, "text": "If more than 1 record satisfy the condition on the alternate key." }, { "code": null, "e": 3492, "s": 3484, "text": "NOSPACE" }, { "code": null, "e": 3534, "s": 3492, "text": "There is not enough space in the dataset." }, { "code": null, "e": 3541, "s": 3534, "text": " Print" }, { "code": null, "e": 3552, "s": 3541, "text": " Add Notes" } ]
Faster Levenshtein Distance Calculation using mbleven | by Parthvi Shah | Towards Data Science
Levenshtein Distance is the minimal number of insertions, deletions, and symbol substitutions required to transform a string a into string b. Example: Consider string a: mouse & string b: morse Levenshtein distance between string a and string b is 2. You need to delete u from string a and insert r to transform string a to string b. There is also one other modification to levenshtein distance: Damerau Levenshtein follows exactly the same approach as Levenshtein Distance but you can also use transpositions (swapping of adjacent symbols) and hence, it makes levenshtein faster and efficient. Damerau Levenshtein follows exactly the same approach as Levenshtein Distance but you can also use transpositions (swapping of adjacent symbols) and hence, it makes levenshtein faster and efficient. In the above example, Damerau-Levenshtein distance between string a and string b is 1. You just need to substitute u from string a with r to transform string a to string b. As easy as it seems, Levenshtein Distance takes a lot of time to run if you have thousands of rows in a pandas DataFrame. Unlike Levenshtein, mbleven is a “hypotheses-based algorithm”. It will first list down all the possible hypotheses to transform one string to the other. Possible hypotheses for the example mentioned above: Can string a be converted to string b if I insert r?Can string a be converted to string b if I delete u?Can string a be converted to string b if I substitute u?.... Can string a be converted to string b if I insert r? Can string a be converted to string b if I delete u? Can string a be converted to string b if I substitute u? .... mbleven will check out all the hypotheses one by one. All the hypotheses can be computed in O(n) times. The entire code and its implementation can be viewed here: https://github.com/fujimotos/mbleven mbleven can confirm if one string can be converted to the other string using the mentioned k-bound & it can also return the edit-distance between the two strings. A few of the examples mentioned are: >>> from mbleven import compare>>> compare("meet", "meat")1>>> compare("meet", "eat")2>>> compare("meet", "mars") # distance 3-1 The last example returns -1 because the distance between these two strings is 3 edit-distance and this algorithm has an upper bound of 2 edit-distance by default.
[ { "code": null, "e": 314, "s": 172, "text": "Levenshtein Distance is the minimal number of insertions, deletions, and symbol substitutions required to transform a string a into string b." }, { "code": null, "e": 366, "s": 314, "text": "Example: Consider string a: mouse & string b: morse" }, { "code": null, "e": 506, "s": 366, "text": "Levenshtein distance between string a and string b is 2. You need to delete u from string a and insert r to transform string a to string b." }, { "code": null, "e": 568, "s": 506, "text": "There is also one other modification to levenshtein distance:" }, { "code": null, "e": 767, "s": 568, "text": "Damerau Levenshtein follows exactly the same approach as Levenshtein Distance but you can also use transpositions (swapping of adjacent symbols) and hence, it makes levenshtein faster and efficient." }, { "code": null, "e": 966, "s": 767, "text": "Damerau Levenshtein follows exactly the same approach as Levenshtein Distance but you can also use transpositions (swapping of adjacent symbols) and hence, it makes levenshtein faster and efficient." }, { "code": null, "e": 1139, "s": 966, "text": "In the above example, Damerau-Levenshtein distance between string a and string b is 1. You just need to substitute u from string a with r to transform string a to string b." }, { "code": null, "e": 1261, "s": 1139, "text": "As easy as it seems, Levenshtein Distance takes a lot of time to run if you have thousands of rows in a pandas DataFrame." }, { "code": null, "e": 1414, "s": 1261, "text": "Unlike Levenshtein, mbleven is a “hypotheses-based algorithm”. It will first list down all the possible hypotheses to transform one string to the other." }, { "code": null, "e": 1467, "s": 1414, "text": "Possible hypotheses for the example mentioned above:" }, { "code": null, "e": 1632, "s": 1467, "text": "Can string a be converted to string b if I insert r?Can string a be converted to string b if I delete u?Can string a be converted to string b if I substitute u?...." }, { "code": null, "e": 1685, "s": 1632, "text": "Can string a be converted to string b if I insert r?" }, { "code": null, "e": 1738, "s": 1685, "text": "Can string a be converted to string b if I delete u?" }, { "code": null, "e": 1795, "s": 1738, "text": "Can string a be converted to string b if I substitute u?" }, { "code": null, "e": 1800, "s": 1795, "text": "...." }, { "code": null, "e": 1904, "s": 1800, "text": "mbleven will check out all the hypotheses one by one. All the hypotheses can be computed in O(n) times." }, { "code": null, "e": 2000, "s": 1904, "text": "The entire code and its implementation can be viewed here: https://github.com/fujimotos/mbleven" }, { "code": null, "e": 2200, "s": 2000, "text": "mbleven can confirm if one string can be converted to the other string using the mentioned k-bound & it can also return the edit-distance between the two strings. A few of the examples mentioned are:" }, { "code": null, "e": 2330, "s": 2200, "text": ">>> from mbleven import compare>>> compare(\"meet\", \"meat\")1>>> compare(\"meet\", \"eat\")2>>> compare(\"meet\", \"mars\") # distance 3-1" } ]
Java XPath Parser - Parse XML Document
Following are the steps used while parsing a document using XPath Parser. Import XML-related packages. Import XML-related packages. Create a DocumentBuilder. Create a DocumentBuilder. Create a Document from a file or stream. Create a Document from a file or stream. Create an Xpath object and an XPath path expression. Create an Xpath object and an XPath path expression. Compile the XPath expression using XPath.compile() and get a list of nodes by evaluating the compiled expression via XPath.evaluate(). Compile the XPath expression using XPath.compile() and get a list of nodes by evaluating the compiled expression via XPath.evaluate(). Iterate over the list of nodes. Iterate over the list of nodes. Examine attributes. Examine attributes. Examine sub-elements. Examine sub-elements. import org.w3c.dom.*; import org.xml.sax.*; import javax.xml.parsers.*; import javax.xml.xpath.*; import java.io.*; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StringBuilder xmlStringBuilder = new StringBuilder(); xmlStringBuilder.append("<?xml version = "1.0"?> <class> </class>"); ByteArrayInputStream input = new ByteArrayInputStream( xmlStringBuilder.toString().getBytes("UTF-8")); Document doc = builder.parse(input); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/class/student"; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate( doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i); ... } //returns specific attribute getAttribute("attributeName"); //returns a Map (table) of names/values getAttributes(); //returns a list of subelements of specified name getElementsByTagName("subelementName"); //returns a list of all child nodes getChildNodes(); Here is the input text file we need to parse − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singh</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import org.xml.sax.SAXException; public class XPathParserDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/class/student"; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate( doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Student roll no :" + eElement.getAttribute("rollno")); System.out.println("First Name : " + eElement .getElementsByTagName("firstname") .item(0) .getTextContent()); System.out.println("Last Name : " + eElement .getElementsByTagName("lastname") .item(0) .getTextContent()); System.out.println("Nick Name : " + eElement .getElementsByTagName("nickname") .item(0) .getTextContent()); System.out.println("Marks : " + eElement .getElementsByTagName("marks") .item(0) .getTextContent()); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } } } This would produce the following result − Current Element :student Student roll no : 393 First Name : dinkar Last Name : kad Nick Name : dinkar Marks : 85 Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta Nick Name : vinni Marks : 95 Current Element :student Student roll no : 593 First Name : jasvir Last Name : singh Nick Name : jazz Marks : 90 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2397, "s": 2323, "text": "Following are the steps used while parsing a document using XPath Parser." }, { "code": null, "e": 2426, "s": 2397, "text": "Import XML-related packages." }, { "code": null, "e": 2455, "s": 2426, "text": "Import XML-related packages." }, { "code": null, "e": 2481, "s": 2455, "text": "Create a DocumentBuilder." }, { "code": null, "e": 2507, "s": 2481, "text": "Create a DocumentBuilder." }, { "code": null, "e": 2548, "s": 2507, "text": "Create a Document from a file or stream." }, { "code": null, "e": 2589, "s": 2548, "text": "Create a Document from a file or stream." }, { "code": null, "e": 2642, "s": 2589, "text": "Create an Xpath object and an XPath path expression." }, { "code": null, "e": 2695, "s": 2642, "text": "Create an Xpath object and an XPath path expression." }, { "code": null, "e": 2830, "s": 2695, "text": "Compile the XPath expression using XPath.compile() and get a list of nodes by evaluating the compiled expression via XPath.evaluate()." }, { "code": null, "e": 2965, "s": 2830, "text": "Compile the XPath expression using XPath.compile() and get a list of nodes by evaluating the compiled expression via XPath.evaluate()." }, { "code": null, "e": 2997, "s": 2965, "text": "Iterate over the list of nodes." }, { "code": null, "e": 3029, "s": 2997, "text": "Iterate over the list of nodes." }, { "code": null, "e": 3049, "s": 3029, "text": "Examine attributes." }, { "code": null, "e": 3069, "s": 3049, "text": "Examine attributes." }, { "code": null, "e": 3091, "s": 3069, "text": "Examine sub-elements." }, { "code": null, "e": 3113, "s": 3091, "text": "Examine sub-elements." }, { "code": null, "e": 3229, "s": 3113, "text": "import org.w3c.dom.*;\nimport org.xml.sax.*;\nimport javax.xml.parsers.*;\nimport javax.xml.xpath.*;\nimport java.io.*;" }, { "code": null, "e": 3356, "s": 3229, "text": "DocumentBuilderFactory factory =\nDocumentBuilderFactory.newInstance();\nDocumentBuilder builder = factory.newDocumentBuilder();" }, { "code": null, "e": 3623, "s": 3356, "text": "StringBuilder xmlStringBuilder = new StringBuilder();\nxmlStringBuilder.append(\"<?xml version = \"1.0\"?> <class> </class>\");\nByteArrayInputStream input = new ByteArrayInputStream(\n xmlStringBuilder.toString().getBytes(\"UTF-8\"));\nDocument doc = builder.parse(input);" }, { "code": null, "e": 3677, "s": 3623, "text": "XPath xPath = XPathFactory.newInstance().newXPath();" }, { "code": null, "e": 3824, "s": 3677, "text": "String expression = \"/class/student\";\t \nNodeList nodeList = (NodeList) xPath.compile(expression).evaluate(\n doc, XPathConstants.NODESET);" }, { "code": null, "e": 3916, "s": 3824, "text": "for (int i = 0; i < nodeList.getLength(); i++) {\n Node nNode = nodeList.item(i);\n ...\n}" }, { "code": null, "e": 4035, "s": 3916, "text": "//returns specific attribute\ngetAttribute(\"attributeName\");\n\n//returns a Map (table) of names/values\ngetAttributes(); " }, { "code": null, "e": 4180, "s": 4035, "text": "//returns a list of subelements of specified name\ngetElementsByTagName(\"subelementName\");\n\n//returns a list of all child nodes\ngetChildNodes(); " }, { "code": null, "e": 4227, "s": 4180, "text": "Here is the input text file we need to parse −" }, { "code": null, "e": 4778, "s": 4227, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singh</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 7454, "s": 4778, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathConstants;\nimport javax.xml.xpath.XPathExpressionException;\nimport javax.xml.xpath.XPathFactory;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.NodeList;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.Element;\nimport org.xml.sax.SAXException;\n\npublic class XPathParserDemo {\n \n public static void main(String[] args) {\n \n try {\n File inputFile = new File(\"input.txt\");\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder;\n\n dBuilder = dbFactory.newDocumentBuilder();\n\n Document doc = dBuilder.parse(inputFile);\n doc.getDocumentElement().normalize();\n\n XPath xPath = XPathFactory.newInstance().newXPath();\n\n String expression = \"/class/student\";\t \n NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(\n doc, XPathConstants.NODESET);\n\n for (int i = 0; i < nodeList.getLength(); i++) {\n Node nNode = nodeList.item(i);\n System.out.println(\"\\nCurrent Element :\" + nNode.getNodeName());\n \n if (nNode.getNodeType() == Node.ELEMENT_NODE) {\n Element eElement = (Element) nNode;\n System.out.println(\"Student roll no :\" + eElement.getAttribute(\"rollno\"));\n System.out.println(\"First Name : \" \n + eElement\n .getElementsByTagName(\"firstname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Last Name : \" \n + eElement\n .getElementsByTagName(\"lastname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Nick Name : \" \n + eElement\n .getElementsByTagName(\"nickname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Marks : \" \n + eElement\n .getElementsByTagName(\"marks\")\n .item(0)\n .getTextContent());\n }\n }\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (SAXException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (XPathExpressionException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 7496, "s": 7454, "text": "This would produce the following result −" }, { "code": null, "e": 7839, "s": 7496, "text": "Current Element :student\nStudent roll no : 393\nFirst Name : dinkar\nLast Name : kad\nNick Name : dinkar\nMarks : 85\n\nCurrent Element :student\nStudent roll no : 493\nFirst Name : Vaneet\nLast Name : Gupta\nNick Name : vinni\nMarks : 95\n\nCurrent Element :student\nStudent roll no : 593\nFirst Name : jasvir\nLast Name : singh\nNick Name : jazz\nMarks : 90\n" }, { "code": null, "e": 7872, "s": 7839, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 7888, "s": 7872, "text": " Malhar Lathkar" }, { "code": null, "e": 7921, "s": 7888, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 7937, "s": 7921, "text": " Malhar Lathkar" }, { "code": null, "e": 7972, "s": 7937, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7986, "s": 7972, "text": " Anadi Sharma" }, { "code": null, "e": 8020, "s": 7986, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 8034, "s": 8020, "text": " Tushar Kale" }, { "code": null, "e": 8071, "s": 8034, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 8086, "s": 8071, "text": " Monica Mittal" }, { "code": null, "e": 8119, "s": 8086, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 8138, "s": 8119, "text": " Arnab Chakraborty" }, { "code": null, "e": 8145, "s": 8138, "text": " Print" }, { "code": null, "e": 8156, "s": 8145, "text": " Add Notes" } ]
Vue.js | v-on:click directive
22 Jun, 2020 The v-on:click directive is a Vue.js directive used to add a click event listener to an element. First, we will create a div element with id as app and let’s apply the v-on:click directive to a element. Further, we can execute a function when click even occurs. Syntax: v-on:click="function" Parameters: This directive accepts function which will be executed when the click event occurs.Example: This example uses VueJS to toggle the visibility of a element with v-on:click. HTML <!DOCTYPE html><html> <head> <title> VueJS | v-on:click directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script></head> <body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> VueJS | v-on:click directive </b> </div> <div id="canvas" style="border:1px solid #000000; width: 600px;height: 200px;"> <div id="app" style="text-align: center; padding-top: 40px;"> <button v-on:click="data = !data"> Show </button> <h1 v-if="data">GeeksforGeeks</h1> </div> </div> <script> var app = new Vue({ el: '#app', data: { data: false } }) </script></body></html> Output: Vue.JS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request 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": "\n22 Jun, 2020" }, { "code": null, "e": 290, "s": 28, "text": "The v-on:click directive is a Vue.js directive used to add a click event listener to an element. First, we will create a div element with id as app and let’s apply the v-on:click directive to a element. Further, we can execute a function when click even occurs." }, { "code": null, "e": 298, "s": 290, "text": "Syntax:" }, { "code": null, "e": 321, "s": 298, "text": "v-on:click=\"function\"\n" }, { "code": null, "e": 504, "s": 321, "text": "Parameters: This directive accepts function which will be executed when the click event occurs.Example: This example uses VueJS to toggle the visibility of a element with v-on:click." }, { "code": null, "e": 509, "s": 504, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> VueJS | v-on:click directive </title> <!-- Load Vuejs --> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script></head> <body> <div style=\"text-align: center;width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> VueJS | v-on:click directive </b> </div> <div id=\"canvas\" style=\"border:1px solid #000000; width: 600px;height: 200px;\"> <div id=\"app\" style=\"text-align: center; padding-top: 40px;\"> <button v-on:click=\"data = !data\"> Show </button> <h1 v-if=\"data\">GeeksforGeeks</h1> </div> </div> <script> var app = new Vue({ el: '#app', data: { data: false } }) </script></body></html>", "e": 1433, "s": 509, "text": null }, { "code": null, "e": 1441, "s": 1433, "text": "Output:" }, { "code": null, "e": 1448, "s": 1441, "text": "Vue.JS" }, { "code": null, "e": 1459, "s": 1448, "text": "JavaScript" }, { "code": null, "e": 1476, "s": 1459, "text": "Web Technologies" }, { "code": null, "e": 1574, "s": 1476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1635, "s": 1574, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1707, "s": 1635, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1747, "s": 1707, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1799, "s": 1747, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 1840, "s": 1799, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1902, "s": 1840, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1935, "s": 1902, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1996, "s": 1935, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2046, "s": 1996, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to filter nested JSON object to return certain value using JavaScript ?
03 Dec, 2020 Given a collection that contains the detail information of employees who are working in the organization. We need to find some values from that nested collections of details. That collection is known as the JSON object and the information inside object are known as nested JSON object. Example 1: We create the nested JSON objects using JavaScript code. Consider an example, suppose there are details of 4 employees and we need to find the street number of the first employee then it can be done in the following way. employees[0].address.["street-no"] If we need to find the residential details of the second employee then use the following instruction. employees[1].address.["street-no"] Note: The dot is an operator which indicates that select the street number from the address field of the first employee. That “street-no” is inside the “address”, so the dot operator is used. To print the above result in the document, we need to use document.write html <!DOCTYPE html><html> <body> <h2 style="color:green;"> GeeksForGeeks </h2> <script> var employees = [ { "emp_id":101, "empname":"Ram", "salary":60000, "address" : { "street-no":20, "plot-no":121, "city":"pune", "contact" : { "landline" : 2292099, "mobile" : 8907632178 } } }, { "emp_id":102, "empname":"Shyam", "salary":50000, "address" : { "street-no":12, "plot-no":221, "city":"pune" } }, { "emp_id":103, "empname":"Lakhan", "salary":40000, "address" : { "street-no":11, "plot-no":432, "city":"pune" } }, { "emp_id":104, "empname":"Snigdha", "salary":60000, "address" : { "street-no":21, "plot-no":222, "city":"pune" } }] document.write("<b>" + "Employee Id : " + "</b>" + employees[0].emp_id + "<br>"); document.write("<b>" + "Employee Name : " + "</b>" + employees[0].empname + "<br>"); document.write("<b>" + "Employee Salary : " + "</b>" + employees[0].salary + "<br>"); document.write("<b>" + "Address -> " + "Street Number : " + "</b>" + employees[0].address["street-no"]); </script></body> </html> Output: Example 2: We need to create the nested JSON objects using JavaScript. Consider an example that contains the information of 4 employees and we need to find the mobile number of the first employee then it can be done in the following manner. employees[0].address.contact["mobile"] To find the contact details of the second employee. employees[1].address.contact["mobile"] The dot operator is used for selecting the mobile from the contact field of the address field of the second employee. html <!DOCTYPE html><html> <body> <h2 style="color: green;"> GeeksForGeeks </h2> <script> var employees = [ { "emp_id":101, "empname":"Ram", "salary":60000, "address" : { "street-no":20, "plot-no":121, "city":"pune", "contact" : { "landline" : 2292099, "mobile" : 8907632178 } } }, { "emp_id":102, "empname":"Shyam", "salary":50000, "address" : { "street-no":12, "plot-no":221, "city":"pune" } }, { "emp_id":103, "empname":"Lakhan", "salary":40000, "address" : { "street-no":11, "plot-no":432, "city":"pune" } }, { "emp_id":104, "empname":"Snigdha", "salary":60000, "address" : { "street-no":21, "plot-no":222, "city":"pune" } }] document.write("<b>" + "Employee Id : " + "</b>" + employees[0].emp_id + "<br>"); document.write("<b>" + "Employee Name : " + "</b>" + employees[0].empname + "<br>"); document.write("<b>" + "Employee Salary : " + "</b>" + employees[0].salary + "<br>"); document.write("<b>" + "Address -> " + "Street Number : " + "</b>" + employees[0].address["street-no"] + "<br>"); document.write("<b>" + "Address -> " + "Phone Number -> " + "</b>" + "<b>" + "Mobile : " + "</b>" + employees[0].address.contact["mobile"] + "<br>"); </script></body> </html> Output: Example 3: We have created a JSON object that consists personal details like their first name, last name, gender etc. using JavaScript. Suppose, our JSON object contains details of 2 people and we need to find the first name and last name of the second person then we need to do the following. For first name Person[1].Name["FirstName"] For Last name Person[1].Name["LastName"] html <!DOCTYPE html><html> <body> <h2 style="color: green;"> GeeksForGeeks </h2> <script> var Person = [ { "Name" : { "FirstName" : "Smita", "LastName" : "Verma" }, "Degree" : { "BE" : "CSE", "MTECH" : "CSE" }, "Gender" : "Female" }, { "Name" : { "FirstName" : "Ramesh", "LastName" : "Rajput" }, "Degree" : { "BE" : "CIVIL", "MTECH" : "CIVIL" }, "Gender" : "Male" }] document.write("<b>" + "FirstName : " + "</b>" + " " + Person[1].Name["FirstName"] + "<br>"); document.write("<b>" + "LastName :" + "</b>" + " " + Person[1].Name["LastName"] + "<br>"); document.write("<b>" + "Degree : " + "->" + "BE : " + "</b>" + " " + Person[1].Degree["BE"] + "<br>"); document.write("<b>" + "Gender :" + "</b>" + " " + Person[1].Gender + "<br>"); </script></body> </html> Output: HTML-Misc JavaScript-Misc Picked HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2020" }, { "code": null, "e": 314, "s": 28, "text": "Given a collection that contains the detail information of employees who are working in the organization. We need to find some values from that nested collections of details. That collection is known as the JSON object and the information inside object are known as nested JSON object." }, { "code": null, "e": 547, "s": 314, "text": "Example 1: We create the nested JSON objects using JavaScript code. Consider an example, suppose there are details of 4 employees and we need to find the street number of the first employee then it can be done in the following way. " }, { "code": null, "e": 583, "s": 547, "text": "employees[0].address.[\"street-no\"] " }, { "code": null, "e": 685, "s": 583, "text": "If we need to find the residential details of the second employee then use the following instruction." }, { "code": null, "e": 720, "s": 685, "text": "employees[1].address.[\"street-no\"]" }, { "code": null, "e": 913, "s": 720, "text": "Note: The dot is an operator which indicates that select the street number from the address field of the first employee. That “street-no” is inside the “address”, so the dot operator is used. " }, { "code": null, "e": 986, "s": 913, "text": "To print the above result in the document, we need to use document.write" }, { "code": null, "e": 991, "s": 986, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h2 style=\"color:green;\"> GeeksForGeeks </h2> <script> var employees = [ { \"emp_id\":101, \"empname\":\"Ram\", \"salary\":60000, \"address\" : { \"street-no\":20, \"plot-no\":121, \"city\":\"pune\", \"contact\" : { \"landline\" : 2292099, \"mobile\" : 8907632178 } } }, { \"emp_id\":102, \"empname\":\"Shyam\", \"salary\":50000, \"address\" : { \"street-no\":12, \"plot-no\":221, \"city\":\"pune\" } }, { \"emp_id\":103, \"empname\":\"Lakhan\", \"salary\":40000, \"address\" : { \"street-no\":11, \"plot-no\":432, \"city\":\"pune\" } }, { \"emp_id\":104, \"empname\":\"Snigdha\", \"salary\":60000, \"address\" : { \"street-no\":21, \"plot-no\":222, \"city\":\"pune\" } }] document.write(\"<b>\" + \"Employee Id : \" + \"</b>\" + employees[0].emp_id + \"<br>\"); document.write(\"<b>\" + \"Employee Name : \" + \"</b>\" + employees[0].empname + \"<br>\"); document.write(\"<b>\" + \"Employee Salary : \" + \"</b>\" + employees[0].salary + \"<br>\"); document.write(\"<b>\" + \"Address -> \" + \"Street Number : \" + \"</b>\" + employees[0].address[\"street-no\"]); </script></body> </html>", "e": 2709, "s": 991, "text": null }, { "code": null, "e": 2717, "s": 2709, "text": "Output:" }, { "code": null, "e": 2958, "s": 2717, "text": "Example 2: We need to create the nested JSON objects using JavaScript. Consider an example that contains the information of 4 employees and we need to find the mobile number of the first employee then it can be done in the following manner." }, { "code": null, "e": 2997, "s": 2958, "text": "employees[0].address.contact[\"mobile\"]" }, { "code": null, "e": 3049, "s": 2997, "text": "To find the contact details of the second employee." }, { "code": null, "e": 3088, "s": 3049, "text": "employees[1].address.contact[\"mobile\"]" }, { "code": null, "e": 3206, "s": 3088, "text": "The dot operator is used for selecting the mobile from the contact field of the address field of the second employee." }, { "code": null, "e": 3211, "s": 3206, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h2 style=\"color: green;\"> GeeksForGeeks </h2> <script> var employees = [ { \"emp_id\":101, \"empname\":\"Ram\", \"salary\":60000, \"address\" : { \"street-no\":20, \"plot-no\":121, \"city\":\"pune\", \"contact\" : { \"landline\" : 2292099, \"mobile\" : 8907632178 } } }, { \"emp_id\":102, \"empname\":\"Shyam\", \"salary\":50000, \"address\" : { \"street-no\":12, \"plot-no\":221, \"city\":\"pune\" } }, { \"emp_id\":103, \"empname\":\"Lakhan\", \"salary\":40000, \"address\" : { \"street-no\":11, \"plot-no\":432, \"city\":\"pune\" } }, { \"emp_id\":104, \"empname\":\"Snigdha\", \"salary\":60000, \"address\" : { \"street-no\":21, \"plot-no\":222, \"city\":\"pune\" } }] document.write(\"<b>\" + \"Employee Id : \" + \"</b>\" + employees[0].emp_id + \"<br>\"); document.write(\"<b>\" + \"Employee Name : \" + \"</b>\" + employees[0].empname + \"<br>\"); document.write(\"<b>\" + \"Employee Salary : \" + \"</b>\" + employees[0].salary + \"<br>\"); document.write(\"<b>\" + \"Address -> \" + \"Street Number : \" + \"</b>\" + employees[0].address[\"street-no\"] + \"<br>\"); document.write(\"<b>\" + \"Address -> \" + \"Phone Number -> \" + \"</b>\" + \"<b>\" + \"Mobile : \" + \"</b>\" + employees[0].address.contact[\"mobile\"] + \"<br>\"); </script></body> </html>", "e": 5142, "s": 3211, "text": null }, { "code": null, "e": 5150, "s": 5142, "text": "Output:" }, { "code": null, "e": 5444, "s": 5150, "text": "Example 3: We have created a JSON object that consists personal details like their first name, last name, gender etc. using JavaScript. Suppose, our JSON object contains details of 2 people and we need to find the first name and last name of the second person then we need to do the following." }, { "code": null, "e": 5459, "s": 5444, "text": "For first name" }, { "code": null, "e": 5487, "s": 5459, "text": "Person[1].Name[\"FirstName\"]" }, { "code": null, "e": 5501, "s": 5487, "text": "For Last name" }, { "code": null, "e": 5529, "s": 5501, "text": "Person[1].Name[\"LastName\"] " }, { "code": null, "e": 5534, "s": 5529, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h2 style=\"color: green;\"> GeeksForGeeks </h2> <script> var Person = [ { \"Name\" : { \"FirstName\" : \"Smita\", \"LastName\" : \"Verma\" }, \"Degree\" : { \"BE\" : \"CSE\", \"MTECH\" : \"CSE\" }, \"Gender\" : \"Female\" }, { \"Name\" : { \"FirstName\" : \"Ramesh\", \"LastName\" : \"Rajput\" }, \"Degree\" : { \"BE\" : \"CIVIL\", \"MTECH\" : \"CIVIL\" }, \"Gender\" : \"Male\" }] document.write(\"<b>\" + \"FirstName : \" + \"</b>\" + \" \" + Person[1].Name[\"FirstName\"] + \"<br>\"); document.write(\"<b>\" + \"LastName :\" + \"</b>\" + \" \" + Person[1].Name[\"LastName\"] + \"<br>\"); document.write(\"<b>\" + \"Degree : \" + \"->\" + \"BE : \" + \"</b>\" + \" \" + Person[1].Degree[\"BE\"] + \"<br>\"); document.write(\"<b>\" + \"Gender :\" + \"</b>\" + \" \" + Person[1].Gender + \"<br>\"); </script></body> </html>", "e": 6666, "s": 5534, "text": null }, { "code": null, "e": 6674, "s": 6666, "text": "Output:" }, { "code": null, "e": 6684, "s": 6674, "text": "HTML-Misc" }, { "code": null, "e": 6700, "s": 6684, "text": "JavaScript-Misc" }, { "code": null, "e": 6707, "s": 6700, "text": "Picked" }, { "code": null, "e": 6712, "s": 6707, "text": "HTML" }, { "code": null, "e": 6723, "s": 6712, "text": "JavaScript" }, { "code": null, "e": 6740, "s": 6723, "text": "Web Technologies" }, { "code": null, "e": 6745, "s": 6740, "text": "HTML" }, { "code": null, "e": 6843, "s": 6745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6891, "s": 6843, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 6915, "s": 6891, "text": "REST API (Introduction)" }, { "code": null, "e": 6965, "s": 6915, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 7004, "s": 6965, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 7041, "s": 7004, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 7102, "s": 7041, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7174, "s": 7102, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 7214, "s": 7174, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7266, "s": 7214, "text": "How to append HTML code to a div using JavaScript ?" } ]
Overview of testing package in Golang
18 Dec, 2021 In the software industry, there are clear differences between manual testing and automated testing. Where manual testing is used to ensure that the software code performs as expected and it requires time and effort. Most of the manual testing includes checking log files, external services, and the database for errors. In a dissimilar fashion, Automated testing is, well, automated where certain software/code perform the testing as the user would do. Because automated testing is done using an automation tool, exploration tests take less time and more test scripts, while increasing the overall scope of the tests. In Golang, package testing is responsible for different types of testing maybe it is performance testing, parallel testing, functional testing, or any possible combination of these all. The testing package provides support for automated testing of the Golang code. To run any test function use “go test” command, which automates the execution of any function of the form TestXxx(*testing.T), where Xxx must not start with any lowercase letter. Test Function Syntax : func TestXxx(*testing.T) Steps for writing test suite in Golang: Create a file whose name ends with _test.go Import package testing by import “testing” command Write the test function of form func TestXxx(*testing.T) which uses any of Error, Fail, or related methods to signal failure. Put the file in any package. Run command go test Note: test file will be excluded in package build and will only get executed on go test command. Example: File: main.go Go package main // function which return "geeks"func ReturnGeeks() string{ return "geeks";} // main function of packagefunc main() { ReturnGeeks()} Test file: pkg_test.go Go package main import ( "testing") // test functionfunc TestReturnGeeks(t *testing.T) { actualString := ReturnGeeks() expectedString := "geeks" if actualString != expectedString{ t.Errorf("Expected String(%s) is not same as"+ " actual string (%s)", expectedString,actualString) }} Output: Screen after running test case amshashank Golang-Packages Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Data Types in Go Slices in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Dec, 2021" }, { "code": null, "e": 646, "s": 28, "text": "In the software industry, there are clear differences between manual testing and automated testing. Where manual testing is used to ensure that the software code performs as expected and it requires time and effort. Most of the manual testing includes checking log files, external services, and the database for errors. In a dissimilar fashion, Automated testing is, well, automated where certain software/code perform the testing as the user would do. Because automated testing is done using an automation tool, exploration tests take less time and more test scripts, while increasing the overall scope of the tests." }, { "code": null, "e": 832, "s": 646, "text": "In Golang, package testing is responsible for different types of testing maybe it is performance testing, parallel testing, functional testing, or any possible combination of these all." }, { "code": null, "e": 1091, "s": 832, "text": "The testing package provides support for automated testing of the Golang code. To run any test function use “go test” command, which automates the execution of any function of the form TestXxx(*testing.T), where Xxx must not start with any lowercase letter." }, { "code": null, "e": 1114, "s": 1091, "text": "Test Function Syntax :" }, { "code": null, "e": 1139, "s": 1114, "text": "func TestXxx(*testing.T)" }, { "code": null, "e": 1179, "s": 1139, "text": "Steps for writing test suite in Golang:" }, { "code": null, "e": 1223, "s": 1179, "text": "Create a file whose name ends with _test.go" }, { "code": null, "e": 1274, "s": 1223, "text": "Import package testing by import “testing” command" }, { "code": null, "e": 1400, "s": 1274, "text": "Write the test function of form func TestXxx(*testing.T) which uses any of Error, Fail, or related methods to signal failure." }, { "code": null, "e": 1429, "s": 1400, "text": "Put the file in any package." }, { "code": null, "e": 1449, "s": 1429, "text": "Run command go test" }, { "code": null, "e": 1546, "s": 1449, "text": "Note: test file will be excluded in package build and will only get executed on go test command." }, { "code": null, "e": 1555, "s": 1546, "text": "Example:" }, { "code": null, "e": 1570, "s": 1555, "text": "File: main.go " }, { "code": null, "e": 1573, "s": 1570, "text": "Go" }, { "code": "package main // function which return \"geeks\"func ReturnGeeks() string{ return \"geeks\";} // main function of packagefunc main() { ReturnGeeks()}", "e": 1724, "s": 1573, "text": null }, { "code": null, "e": 1750, "s": 1727, "text": "Test file: pkg_test.go" }, { "code": null, "e": 1755, "s": 1752, "text": "Go" }, { "code": "package main import ( \"testing\") // test functionfunc TestReturnGeeks(t *testing.T) { actualString := ReturnGeeks() expectedString := \"geeks\" if actualString != expectedString{ t.Errorf(\"Expected String(%s) is not same as\"+ \" actual string (%s)\", expectedString,actualString) }}", "e": 2064, "s": 1755, "text": null }, { "code": null, "e": 2072, "s": 2064, "text": "Output:" }, { "code": null, "e": 2103, "s": 2072, "text": "Screen after running test case" }, { "code": null, "e": 2114, "s": 2103, "text": "amshashank" }, { "code": null, "e": 2130, "s": 2114, "text": "Golang-Packages" }, { "code": null, "e": 2142, "s": 2130, "text": "Go Language" }, { "code": null, "e": 2240, "s": 2142, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2291, "s": 2240, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 2338, "s": 2291, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 2351, "s": 2338, "text": "Arrays in Go" }, { "code": null, "e": 2363, "s": 2351, "text": "Golang Maps" }, { "code": null, "e": 2396, "s": 2363, "text": "How to Split a String in Golang?" }, { "code": null, "e": 2417, "s": 2396, "text": "Interfaces in Golang" }, { "code": null, "e": 2434, "s": 2417, "text": "Data Types in Go" }, { "code": null, "e": 2451, "s": 2434, "text": "Slices in Golang" }, { "code": null, "e": 2505, "s": 2451, "text": "Different Ways to Find the Type of Variable in Golang" } ]
Reverse and Add given number repeatedly to get a Palindrome number
07 Mar, 2022 Write a program that takes number and gives the resulting palindrome (if one exists). If it took more than 1, 000 iterations (additions) or yield a palindrome that is greater than 4, 294, 967, 295, assume that no palindrome exist for the given number. Examples: Input: N = 195Output: 9339 Input: N = 265Output: 45254 Input: N = 196Output: No palindrome exist Approach: Create a reverse and add function to start with a number, reverses its digits, and adds the reverse to the original. If the sum is not a palindrome, repeat this procedure until it does. C++ Java Python3 C# PHP Javascript // C++ Program to implement reverse and add function#include <bits/stdc++.h>using namespace std; /* Iterative function to reverse digits of num*/long long reversDigits(long long num){ long long rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Function to check whether the number is palindrome or not */bool isPalindrome(long long num){ return (reversDigits(num) == num);} /* Reverse and Add Function */void ReverseandAdd(long long num){ long long rev_num = 0; while (num <= 4294967295) { // Reversing the digits of the number rev_num = reversDigits(num); // Adding the reversed number // with the original num = num + rev_num; // Checking whether the number // is palindrome or not if (isPalindrome(num)) { printf("%lld\n", num); break; } else if (num > 4294967295) { printf("No palindrome exist"); } }} // Driver Programint main(){ ReverseandAdd(195); ReverseandAdd(265); return 0;} // Java Program to implement reverse and add functionpublic class ReverseAdd { /* Iterative function to reverse digits of num*/ long reversDigits(long num) { long rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } /* Function to check whether he number is palindrome or not */ boolean isPalindrome(long num) { return (reversDigits(num) == num); } /* Reverse and Add Function */ void ReverseandAdd(long num) { long rev_num = 0; while (num <= 4294967295l) { // Reversing the digits of the number rev_num = reversDigits(num); // Adding the reversed number // with the original num = num + rev_num; // Checking whether the number // is palindrome or not if (isPalindrome(num)) { System.out.println(num); break; } else if (num > 4294967295l) { System.out.println("No palindrome exist"); } } } // Main method public static void main(String[] args) { ReverseAdd ob = new ReverseAdd(); ob.ReverseandAdd(195l); ob.ReverseandAdd(265l); }} # Python Program to implement reverse and add function # Iterative function to reverse digits of numdef reversDigits(num): rev_num = 0 while (num > 0): rev_num = rev_num * 10 + num % 10 num = num//10 return rev_num # Function to check whether # the number is palindrome or notdef isPalindrome(num): return (reversDigits(num) == num) # Reverse and Add Functiondef ReverseandAdd(num): rev_num = 0 while (num <= 4294967295): # Reversing the digits of the number rev_num = reversDigits(num) # Adding the reversed number # with the original num = num + rev_num # Checking whether the number # is palindrome or not if(isPalindrome(num)): print (num) break else: if (num > 4294967295): print ("No palindrome exist") # Driver CodeReverseandAdd(195)ReverseandAdd(265) // C# Program to implement reverse and add functionusing System; class GFG { /* Iterative function to reverse digits of num*/ static long reversDigits(long num) { long rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } /* Function to check whether he number is palindrome or not */ static bool isPalindrome(long num) { return (reversDigits(num) == num); } /* Reverse and Add Function */ static void ReverseandAdd(long num) { long rev_num = 0; while (num <= 4294967295) { // Reversing the digits of the number rev_num = reversDigits(num); // Adding the reversed number // with the original num = num + rev_num; // Checking whether the number // is palindrome or not if (isPalindrome(num)) { Console.WriteLine(num); break; } else if (num > 4294967295) { Console.WriteLine("No palindrome exist"); } } } // Driver code public static void Main() { ReverseandAdd(195); ReverseandAdd(265); }} // This code is contributed by chandan_jnu <?php// PHP Program to implement reverse and add function /* Iterative function to reverse digits of num*/function reversDigits($num){ $rev_num = 0; while ($num > 0) { $rev_num = $rev_num * 10 + $num % 10; $num = (int)($num / 10); } return $rev_num;} /* Function to check whether he number is palindrome or not */function isPalindrome($num){ return (reversDigits($num) == $num);} /* Reverse and Add Function */function ReverseandAdd($num){ $rev_num = 0; while ($num <= 4294967295) { // Reversing the digits of the number $rev_num = reversDigits($num); // Adding the reversed number with // the original $num = $num + $rev_num; // Checking whether the number is // palindrome or not if (isPalindrome($num)) { print($num . "\n"); break; } else if ($num > 4294967295) { print("No palindrome exist"); } }} // Driver CodeReverseandAdd(195);ReverseandAdd(265); // This code is contributed by chandan_jnu?> <script> // Javascript program to implement// reverse and add function // Iterative function to reverse digits of numfunction reversDigits(num){ let rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = parseInt(num / 10, 10); } return rev_num;} // Function to check whether he number // is palindrome or not function isPalindrome(num){ return(reversDigits(num) == num);} // Reverse and Add Function function ReverseandAdd(num){ let rev_num = 0; while (num <= 4294967295) { // Reversing the digits of the number rev_num = reversDigits(num); // Adding the reversed number // with the original num = num + rev_num; // Checking whether the number // is palindrome or not if (isPalindrome(num)) { document.write(num + "</br>"); break; } else if (num > 4294967295) { document.write("No palindrome exist" + "</br>"); } }} // Driver codeReverseandAdd(195);ReverseandAdd(265); // This code is contributed by rameshtravel07 </script> 9339 45254 References: https://app.assembla.com/spaces/AASU_Fall2008_ProgrammingTeam/wiki This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Chandan_Kumar rameshtravel07 amartyaghoshgfg Reverse Mathematical Mathematical Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Mar, 2022" }, { "code": null, "e": 305, "s": 53, "text": "Write a program that takes number and gives the resulting palindrome (if one exists). If it took more than 1, 000 iterations (additions) or yield a palindrome that is greater than 4, 294, 967, 295, assume that no palindrome exist for the given number." }, { "code": null, "e": 316, "s": 305, "text": "Examples: " }, { "code": null, "e": 343, "s": 316, "text": "Input: N = 195Output: 9339" }, { "code": null, "e": 371, "s": 343, "text": "Input: N = 265Output: 45254" }, { "code": null, "e": 413, "s": 371, "text": "Input: N = 196Output: No palindrome exist" }, { "code": null, "e": 609, "s": 413, "text": "Approach: Create a reverse and add function to start with a number, reverses its digits, and adds the reverse to the original. If the sum is not a palindrome, repeat this procedure until it does." }, { "code": null, "e": 613, "s": 609, "text": "C++" }, { "code": null, "e": 618, "s": 613, "text": "Java" }, { "code": null, "e": 626, "s": 618, "text": "Python3" }, { "code": null, "e": 629, "s": 626, "text": "C#" }, { "code": null, "e": 633, "s": 629, "text": "PHP" }, { "code": null, "e": 644, "s": 633, "text": "Javascript" }, { "code": "// C++ Program to implement reverse and add function#include <bits/stdc++.h>using namespace std; /* Iterative function to reverse digits of num*/long long reversDigits(long long num){ long long rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Function to check whether the number is palindrome or not */bool isPalindrome(long long num){ return (reversDigits(num) == num);} /* Reverse and Add Function */void ReverseandAdd(long long num){ long long rev_num = 0; while (num <= 4294967295) { // Reversing the digits of the number rev_num = reversDigits(num); // Adding the reversed number // with the original num = num + rev_num; // Checking whether the number // is palindrome or not if (isPalindrome(num)) { printf(\"%lld\\n\", num); break; } else if (num > 4294967295) { printf(\"No palindrome exist\"); } }} // Driver Programint main(){ ReverseandAdd(195); ReverseandAdd(265); return 0;}", "e": 1760, "s": 644, "text": null }, { "code": "// Java Program to implement reverse and add functionpublic class ReverseAdd { /* Iterative function to reverse digits of num*/ long reversDigits(long num) { long rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } /* Function to check whether he number is palindrome or not */ boolean isPalindrome(long num) { return (reversDigits(num) == num); } /* Reverse and Add Function */ void ReverseandAdd(long num) { long rev_num = 0; while (num <= 4294967295l) { // Reversing the digits of the number rev_num = reversDigits(num); // Adding the reversed number // with the original num = num + rev_num; // Checking whether the number // is palindrome or not if (isPalindrome(num)) { System.out.println(num); break; } else if (num > 4294967295l) { System.out.println(\"No palindrome exist\"); } } } // Main method public static void main(String[] args) { ReverseAdd ob = new ReverseAdd(); ob.ReverseandAdd(195l); ob.ReverseandAdd(265l); }}", "e": 3088, "s": 1760, "text": null }, { "code": "# Python Program to implement reverse and add function # Iterative function to reverse digits of numdef reversDigits(num): rev_num = 0 while (num > 0): rev_num = rev_num * 10 + num % 10 num = num//10 return rev_num # Function to check whether # the number is palindrome or notdef isPalindrome(num): return (reversDigits(num) == num) # Reverse and Add Functiondef ReverseandAdd(num): rev_num = 0 while (num <= 4294967295): # Reversing the digits of the number rev_num = reversDigits(num) # Adding the reversed number # with the original num = num + rev_num # Checking whether the number # is palindrome or not if(isPalindrome(num)): print (num) break else: if (num > 4294967295): print (\"No palindrome exist\") # Driver CodeReverseandAdd(195)ReverseandAdd(265)", "e": 4000, "s": 3088, "text": null }, { "code": "// C# Program to implement reverse and add functionusing System; class GFG { /* Iterative function to reverse digits of num*/ static long reversDigits(long num) { long rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } /* Function to check whether he number is palindrome or not */ static bool isPalindrome(long num) { return (reversDigits(num) == num); } /* Reverse and Add Function */ static void ReverseandAdd(long num) { long rev_num = 0; while (num <= 4294967295) { // Reversing the digits of the number rev_num = reversDigits(num); // Adding the reversed number // with the original num = num + rev_num; // Checking whether the number // is palindrome or not if (isPalindrome(num)) { Console.WriteLine(num); break; } else if (num > 4294967295) { Console.WriteLine(\"No palindrome exist\"); } } } // Driver code public static void Main() { ReverseandAdd(195); ReverseandAdd(265); }} // This code is contributed by chandan_jnu", "e": 5305, "s": 4000, "text": null }, { "code": "<?php// PHP Program to implement reverse and add function /* Iterative function to reverse digits of num*/function reversDigits($num){ $rev_num = 0; while ($num > 0) { $rev_num = $rev_num * 10 + $num % 10; $num = (int)($num / 10); } return $rev_num;} /* Function to check whether he number is palindrome or not */function isPalindrome($num){ return (reversDigits($num) == $num);} /* Reverse and Add Function */function ReverseandAdd($num){ $rev_num = 0; while ($num <= 4294967295) { // Reversing the digits of the number $rev_num = reversDigits($num); // Adding the reversed number with // the original $num = $num + $rev_num; // Checking whether the number is // palindrome or not if (isPalindrome($num)) { print($num . \"\\n\"); break; } else if ($num > 4294967295) { print(\"No palindrome exist\"); } }} // Driver CodeReverseandAdd(195);ReverseandAdd(265); // This code is contributed by chandan_jnu?>", "e": 6385, "s": 5305, "text": null }, { "code": "<script> // Javascript program to implement// reverse and add function // Iterative function to reverse digits of numfunction reversDigits(num){ let rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = parseInt(num / 10, 10); } return rev_num;} // Function to check whether he number // is palindrome or not function isPalindrome(num){ return(reversDigits(num) == num);} // Reverse and Add Function function ReverseandAdd(num){ let rev_num = 0; while (num <= 4294967295) { // Reversing the digits of the number rev_num = reversDigits(num); // Adding the reversed number // with the original num = num + rev_num; // Checking whether the number // is palindrome or not if (isPalindrome(num)) { document.write(num + \"</br>\"); break; } else if (num > 4294967295) { document.write(\"No palindrome exist\" + \"</br>\"); } }} // Driver codeReverseandAdd(195);ReverseandAdd(265); // This code is contributed by rameshtravel07 </script>", "e": 7554, "s": 6385, "text": null }, { "code": null, "e": 7566, "s": 7554, "text": "9339\n45254\n" }, { "code": null, "e": 7645, "s": 7566, "text": "References: https://app.assembla.com/spaces/AASU_Fall2008_ProgrammingTeam/wiki" }, { "code": null, "e": 8067, "s": 7645, "text": "This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8081, "s": 8067, "text": "Chandan_Kumar" }, { "code": null, "e": 8096, "s": 8081, "text": "rameshtravel07" }, { "code": null, "e": 8112, "s": 8096, "text": "amartyaghoshgfg" }, { "code": null, "e": 8120, "s": 8112, "text": "Reverse" }, { "code": null, "e": 8133, "s": 8120, "text": "Mathematical" }, { "code": null, "e": 8146, "s": 8133, "text": "Mathematical" }, { "code": null, "e": 8154, "s": 8146, "text": "Reverse" } ]
Number of triangles that can be formed with given N points
07 Jul, 2022 Given X and Y coordinates of N points on a Cartesian plane. The task is to find the number of possible triangles with the non-zero area that can be formed by joining each point to every other point. Examples: Input: P[] = {{0, 0}, {2, 0}, {1, 1}, {2, 2}} Output: 3 Possible triangles can be [(0, 0}, (2, 0), (1, 1)], [(0, 0), (2, 0), (2, 2)] and [(1, 1), (2, 2), (2, 0)] Input : P[] = {{0, 0}, {2, 0}, {1, 1}} Output : 1 A Naive approach has been already discussed in Number of possible Triangles in a Cartesian coordinate system Efficient Approach: Consider a point Z and find its slope with every other point. Now, if two points are having the same slope with point Z that means the 3 points are collinear and they cannot form a triangle. Hence, the number of triangles having Z as one of its points is the number of ways of choosing 2 points from the remaining points and then subtracting the number of ways of choosing 2 points from points having the same slope with Z. Since Z can be any point among N points, we have to iterate one more loop. Below is the implementation of above approach: C++ Python3 Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // This function returns the required number// of trianglesint countTriangles(pair<int, int> P[], int N){ // Hash Map to store the frequency of // slope corresponding to a point (X, Y) map<pair<int, int>, int> mp; int ans = 0; // Iterate over all possible points for (int i = 0; i < N; i++) { mp.clear(); // Calculate slope of all elements // with current element for (int j = i + 1; j < N; j++) { int X = P[i].first - P[j].first; int Y = P[i].second - P[j].second; // find the slope with reduced // fraction int g = __gcd(X, Y); X /= g; Y /= g; mp[{ X, Y }]++; } int num = N - (i + 1); // Total number of ways to form a triangle // having one point as current element ans += (num * (num - 1)) / 2; // Subtracting the total number of ways to // form a triangle having the same slope or are // collinear for (auto j : mp) ans -= (j.second * (j.second - 1)) / 2; } return ans;} // Driver Code to test above functionint main(){ pair<int, int> P[] = { { 0, 0 }, { 2, 0 }, { 1, 1 }, { 2, 2 } }; int N = sizeof(P) / sizeof(P[0]); cout << countTriangles(P, N) << endl; return 0;} # Python3 implementation of the above approachfrom collections import defaultdictfrom math import gcd # This function returns the# required number of trianglesdef countTriangles(P, N): # Hash Map to store the frequency of # slope corresponding to a point (X, Y) mp = defaultdict(lambda:0) ans = 0 # Iterate over all possible points for i in range(0, N): mp.clear() # Calculate slope of all elements # with current element for j in range(i + 1, N): X = P[i][0] - P[j][0] Y = P[i][1] - P[j][1] # find the slope with reduced # fraction g = gcd(X, Y) X //= g Y //= g mp[(X, Y)] += 1 num = N - (i + 1) # Total number of ways to form a triangle # having one point as current element ans += (num * (num - 1)) // 2 # Subtracting the total number of # ways to form a triangle having # the same slope or are collinear for j in mp: ans -= (mp[j] * (mp[j] - 1)) // 2 return ans # Driver Codeif __name__ == "__main__": P = [[0, 0], [2, 0], [1, 1], [2, 2]] N = len(P) print(countTriangles(P, N)) # This code is contributed by Rituraj Jain // JavaScript implementation of the above approach // A recursive function to find gcd of two numbers.function __gcd(x, y) { if ((typeof x !== 'number') || (typeof y !== 'number')) return false; x = Math.abs(x); y = Math.abs(y); while(y) { var t = y; y = x % y; x = t; } return x;} // This function returns the required number// of trianglesfunction countTriangles(P, N){ // Hash Map to store the frequency of // slope corresponding to a point (X, Y) // map<pair<int, int>, int> mp; let mp = new Map(); let ans = 0; // Iterate over all possible points for (let i = 0; i < N; i++) { mp.clear(); // Calculate slope of all elements // with current element for (let j = i + 1; j < N; j++) { let X = P[i][0] - P[j][0]; let Y = P[i][1] - P[j][1]; // find the slope with reduced // fraction let g = __gcd(X, Y); X = Math.floor(X/g); Y = Math.floor(Y/g); if(mp.has([X, Y].join())){ mp.set([X, Y].join(), mp.get([X, Y].join()) + 1); } else{ mp.set([X, Y].join(), 1); } } let num = N - (i + 1); // Total number of ways to form a triangle // having one point as current element ans += Math.floor((num * (num - 1)) / 2); // Subtracting the total number of ways to // form a triangle having the same slope or are // collinear for (const [key, value] of mp.entries()) ans -= (value * (value - 1)) / 2; } return ans;} // Driver Code to test above functionlet P = [[0, 0], [2, 0], [1, 1 ], [2, 2 ]];let N = P.length;console.log(countTriangles(P, N)); // The code is contributed by Nidhi goel 3 Time Complexity: O(N2logN) Auxiliary Space: O(N) rituraj_jain classroompxico subham348 triangle Combinatorial Competitive Programming Geometric Mathematical Mathematical Combinatorial Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subsets with sum equal to X Combinational Sum Find the K-th Permutation Sequence of first N natural numbers Count ways to reach the nth stair using step 1, 2 or 3 Count Derangements (Permutation such that no element appears in its original position) Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 263, "s": 54, "text": "Given X and Y coordinates of N points on a Cartesian plane. The task is to find the number of possible triangles with the non-zero area that can be formed by joining each point to every other point. Examples:" }, { "code": null, "e": 477, "s": 263, "text": "Input: P[] = {{0, 0}, {2, 0}, {1, 1}, {2, 2}}\nOutput: 3\nPossible triangles can be [(0, 0}, (2, 0), (1, 1)], \n[(0, 0), (2, 0), (2, 2)] and [(1, 1), (2, 2), (2, 0)]\n\nInput : P[] = {{0, 0}, {2, 0}, {1, 1}}\nOutput : 1" }, { "code": null, "e": 1153, "s": 477, "text": "A Naive approach has been already discussed in Number of possible Triangles in a Cartesian coordinate system Efficient Approach: Consider a point Z and find its slope with every other point. Now, if two points are having the same slope with point Z that means the 3 points are collinear and they cannot form a triangle. Hence, the number of triangles having Z as one of its points is the number of ways of choosing 2 points from the remaining points and then subtracting the number of ways of choosing 2 points from points having the same slope with Z. Since Z can be any point among N points, we have to iterate one more loop. Below is the implementation of above approach: " }, { "code": null, "e": 1157, "s": 1153, "text": "C++" }, { "code": null, "e": 1165, "s": 1157, "text": "Python3" }, { "code": null, "e": 1176, "s": 1165, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // This function returns the required number// of trianglesint countTriangles(pair<int, int> P[], int N){ // Hash Map to store the frequency of // slope corresponding to a point (X, Y) map<pair<int, int>, int> mp; int ans = 0; // Iterate over all possible points for (int i = 0; i < N; i++) { mp.clear(); // Calculate slope of all elements // with current element for (int j = i + 1; j < N; j++) { int X = P[i].first - P[j].first; int Y = P[i].second - P[j].second; // find the slope with reduced // fraction int g = __gcd(X, Y); X /= g; Y /= g; mp[{ X, Y }]++; } int num = N - (i + 1); // Total number of ways to form a triangle // having one point as current element ans += (num * (num - 1)) / 2; // Subtracting the total number of ways to // form a triangle having the same slope or are // collinear for (auto j : mp) ans -= (j.second * (j.second - 1)) / 2; } return ans;} // Driver Code to test above functionint main(){ pair<int, int> P[] = { { 0, 0 }, { 2, 0 }, { 1, 1 }, { 2, 2 } }; int N = sizeof(P) / sizeof(P[0]); cout << countTriangles(P, N) << endl; return 0;}", "e": 2568, "s": 1176, "text": null }, { "code": "# Python3 implementation of the above approachfrom collections import defaultdictfrom math import gcd # This function returns the# required number of trianglesdef countTriangles(P, N): # Hash Map to store the frequency of # slope corresponding to a point (X, Y) mp = defaultdict(lambda:0) ans = 0 # Iterate over all possible points for i in range(0, N): mp.clear() # Calculate slope of all elements # with current element for j in range(i + 1, N): X = P[i][0] - P[j][0] Y = P[i][1] - P[j][1] # find the slope with reduced # fraction g = gcd(X, Y) X //= g Y //= g mp[(X, Y)] += 1 num = N - (i + 1) # Total number of ways to form a triangle # having one point as current element ans += (num * (num - 1)) // 2 # Subtracting the total number of # ways to form a triangle having # the same slope or are collinear for j in mp: ans -= (mp[j] * (mp[j] - 1)) // 2 return ans # Driver Codeif __name__ == \"__main__\": P = [[0, 0], [2, 0], [1, 1], [2, 2]] N = len(P) print(countTriangles(P, N)) # This code is contributed by Rituraj Jain", "e": 3831, "s": 2568, "text": null }, { "code": "// JavaScript implementation of the above approach // A recursive function to find gcd of two numbers.function __gcd(x, y) { if ((typeof x !== 'number') || (typeof y !== 'number')) return false; x = Math.abs(x); y = Math.abs(y); while(y) { var t = y; y = x % y; x = t; } return x;} // This function returns the required number// of trianglesfunction countTriangles(P, N){ // Hash Map to store the frequency of // slope corresponding to a point (X, Y) // map<pair<int, int>, int> mp; let mp = new Map(); let ans = 0; // Iterate over all possible points for (let i = 0; i < N; i++) { mp.clear(); // Calculate slope of all elements // with current element for (let j = i + 1; j < N; j++) { let X = P[i][0] - P[j][0]; let Y = P[i][1] - P[j][1]; // find the slope with reduced // fraction let g = __gcd(X, Y); X = Math.floor(X/g); Y = Math.floor(Y/g); if(mp.has([X, Y].join())){ mp.set([X, Y].join(), mp.get([X, Y].join()) + 1); } else{ mp.set([X, Y].join(), 1); } } let num = N - (i + 1); // Total number of ways to form a triangle // having one point as current element ans += Math.floor((num * (num - 1)) / 2); // Subtracting the total number of ways to // form a triangle having the same slope or are // collinear for (const [key, value] of mp.entries()) ans -= (value * (value - 1)) / 2; } return ans;} // Driver Code to test above functionlet P = [[0, 0], [2, 0], [1, 1 ], [2, 2 ]];let N = P.length;console.log(countTriangles(P, N)); // The code is contributed by Nidhi goel", "e": 5641, "s": 3831, "text": null }, { "code": null, "e": 5643, "s": 5641, "text": "3" }, { "code": null, "e": 5670, "s": 5643, "text": "Time Complexity: O(N2logN)" }, { "code": null, "e": 5692, "s": 5670, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 5705, "s": 5692, "text": "rituraj_jain" }, { "code": null, "e": 5720, "s": 5705, "text": "classroompxico" }, { "code": null, "e": 5730, "s": 5720, "text": "subham348" }, { "code": null, "e": 5739, "s": 5730, "text": "triangle" }, { "code": null, "e": 5753, "s": 5739, "text": "Combinatorial" }, { "code": null, "e": 5777, "s": 5753, "text": "Competitive Programming" }, { "code": null, "e": 5787, "s": 5777, "text": "Geometric" }, { "code": null, "e": 5800, "s": 5787, "text": "Mathematical" }, { "code": null, "e": 5813, "s": 5800, "text": "Mathematical" }, { "code": null, "e": 5827, "s": 5813, "text": "Combinatorial" }, { "code": null, "e": 5837, "s": 5827, "text": "Geometric" }, { "code": null, "e": 5935, "s": 5837, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5972, "s": 5935, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 5990, "s": 5972, "text": "Combinational Sum" }, { "code": null, "e": 6052, "s": 5990, "text": "Find the K-th Permutation Sequence of first N natural numbers" }, { "code": null, "e": 6107, "s": 6052, "text": "Count ways to reach the nth stair using step 1, 2 or 3" }, { "code": null, "e": 6194, "s": 6107, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 6237, "s": 6194, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 6280, "s": 6237, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 6321, "s": 6280, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 6348, "s": 6321, "text": "Modulo 10^9+7 (1000000007)" } ]
Delete a Node from linked list without head pointer
24 Jun, 2022 You are given a singly linked list and pointer which is pointing to the node which is required to be deleted. Any information about head pointer or any other node is not given. You need to write a function to delete that node from linked list. Your function will take only one argument, i.e., pointer to the node which is to be deleted. Note: No head reference is given to you. It is guaranteed that the node to be deleted is not the last node. A linked list is built as: Definition of each node is as follows: struct Node { int data; struct Node* next;}; Examples: Consider below LL for given examples: Input : C (a pointer to C) Output : A–>B–>D–>E–>F Input : A (a pointer to A) Output : B–>D–>E–>F Approach: Why conventional deletion method would fail here?It would be a simple deletion problem from the singly linked list if the head pointer was given because for deletion you must know the previous node and you can easily reach there by traversing from the head pointer. Conventional deletion is impossible without knowledge of the previous node of a node that needs to be deleted. How to delete the node when you dont have the head pointer?The trick here is we can copy the data of the next node to the data field of the current node to be deleted. Then we can move one step forward. Now our next has become the current node and the current has become the previous node. Now we can easily delete the current node by conventional deletion methods. Illustration: For example, suppose we need to delete B and a pointer to B is given. If we had a pointer to A, we could have deleted B easily. But here we will copy the data field of C to the data field of B. Then we will move forward. Now we are at C and we have a pointer to B i.e. the previous pointer. So we will delete C. That’s how node B will be deleted. Below image is a dry run of the above approach: Below is the implementation of the above approach : CPP // C++ program to delete a node#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; // Function to delete the node without headvoid deleteNodeWithoutHead(struct Node* pos){ if (pos == NULL) // If linked list is empty return; else { if (pos->next == NULL) { printf("This is last node, require head, can't " "be freed\n"); return; } struct Node* temp = pos->next; // Copy data of the next node to current node pos->data = pos->next->data; // Perform conventional deletion pos->next = pos->next->next; free(temp); }} // Function to print the linked listvoid print(Node* head){ Node* temp = head; while (temp) { cout << temp->data << " -> "; temp = temp->next; } cout << "NULL";} void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver Codeint main(){ /* Start with the empty list */ struct Node* head = NULL; // create linked 35->15->4->20 push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); cout << "Initial Linked List: \n"; print(head); cout << endl << endl; // Delete 15 without sending head Node* del = head->next; deleteNodeWithoutHead(del); // Print the final linked list cout << "Final Linked List after deletion of 15:\n"; print(head); return 0; // This code has been contributed by Striver} Initial Linked List: 35 -> 15 -> 4 -> 20 -> NULL Final Linked List after deletion of 15: 35 -> 4 -> 20 -> NULL This article is contributed by Jeet Jain. Please see Given only a pointer to a node to be deleted in a singly linked list, how do you delete it for more details and complete implementation. zweack neekusys baatinx anikakapoor atharvakango jeffreyk MAQ Software programming-puzzle Technical Scripter 2018 Linked List Technical Scripter MAQ Software Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion) Merge two sorted linked lists What is Data Structure: Types, Classifications and Applications Linked List vs Array Merge Sort for Linked Lists Implementing a Linked List in Java using Class Find Length of a Linked List (Iterative and Recursive) Queue - Linked List Implementation
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2022" }, { "code": null, "e": 389, "s": 52, "text": "You are given a singly linked list and pointer which is pointing to the node which is required to be deleted. Any information about head pointer or any other node is not given. You need to write a function to delete that node from linked list. Your function will take only one argument, i.e., pointer to the node which is to be deleted." }, { "code": null, "e": 497, "s": 389, "text": "Note: No head reference is given to you. It is guaranteed that the node to be deleted is not the last node." }, { "code": null, "e": 525, "s": 497, "text": "A linked list is built as: " }, { "code": null, "e": 616, "s": 525, "text": "Definition of each node is as follows: struct Node { int data; struct Node* next;}; " }, { "code": null, "e": 627, "s": 616, "text": "Examples: " }, { "code": null, "e": 665, "s": 627, "text": "Consider below LL for given examples:" }, { "code": null, "e": 692, "s": 665, "text": "Input : C (a pointer to C)" }, { "code": null, "e": 715, "s": 692, "text": "Output : A–>B–>D–>E–>F" }, { "code": null, "e": 742, "s": 715, "text": "Input : A (a pointer to A)" }, { "code": null, "e": 762, "s": 742, "text": "Output : B–>D–>E–>F" }, { "code": null, "e": 773, "s": 762, "text": "Approach: " }, { "code": null, "e": 1151, "s": 773, "text": "Why conventional deletion method would fail here?It would be a simple deletion problem from the singly linked list if the head pointer was given because for deletion you must know the previous node and you can easily reach there by traversing from the head pointer. Conventional deletion is impossible without knowledge of the previous node of a node that needs to be deleted. " }, { "code": null, "e": 1518, "s": 1151, "text": "How to delete the node when you dont have the head pointer?The trick here is we can copy the data of the next node to the data field of the current node to be deleted. Then we can move one step forward. Now our next has become the current node and the current has become the previous node. Now we can easily delete the current node by conventional deletion methods. " }, { "code": null, "e": 1532, "s": 1518, "text": "Illustration:" }, { "code": null, "e": 1603, "s": 1532, "text": "For example, suppose we need to delete B and a pointer to B is given. " }, { "code": null, "e": 1755, "s": 1603, "text": "If we had a pointer to A, we could have deleted B easily. But here we will copy the data field of C to the data field of B. Then we will move forward. " }, { "code": null, "e": 1847, "s": 1755, "text": "Now we are at C and we have a pointer to B i.e. the previous pointer. So we will delete C. " }, { "code": null, "e": 1883, "s": 1847, "text": "That’s how node B will be deleted. " }, { "code": null, "e": 1931, "s": 1883, "text": "Below image is a dry run of the above approach:" }, { "code": null, "e": 1984, "s": 1931, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 1988, "s": 1984, "text": "CPP" }, { "code": "// C++ program to delete a node#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; // Function to delete the node without headvoid deleteNodeWithoutHead(struct Node* pos){ if (pos == NULL) // If linked list is empty return; else { if (pos->next == NULL) { printf(\"This is last node, require head, can't \" \"be freed\\n\"); return; } struct Node* temp = pos->next; // Copy data of the next node to current node pos->data = pos->next->data; // Perform conventional deletion pos->next = pos->next->next; free(temp); }} // Function to print the linked listvoid print(Node* head){ Node* temp = head; while (temp) { cout << temp->data << \" -> \"; temp = temp->next; } cout << \"NULL\";} void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver Codeint main(){ /* Start with the empty list */ struct Node* head = NULL; // create linked 35->15->4->20 push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); cout << \"Initial Linked List: \\n\"; print(head); cout << endl << endl; // Delete 15 without sending head Node* del = head->next; deleteNodeWithoutHead(del); // Print the final linked list cout << \"Final Linked List after deletion of 15:\\n\"; print(head); return 0; // This code has been contributed by Striver}", "e": 3762, "s": 1988, "text": null }, { "code": null, "e": 3875, "s": 3762, "text": "Initial Linked List: \n35 -> 15 -> 4 -> 20 -> NULL\n\nFinal Linked List after deletion of 15:\n35 -> 4 -> 20 -> NULL" }, { "code": null, "e": 4065, "s": 3875, "text": "This article is contributed by Jeet Jain. Please see Given only a pointer to a node to be deleted in a singly linked list, how do you delete it for more details and complete implementation." }, { "code": null, "e": 4072, "s": 4065, "text": "zweack" }, { "code": null, "e": 4081, "s": 4072, "text": "neekusys" }, { "code": null, "e": 4089, "s": 4081, "text": "baatinx" }, { "code": null, "e": 4101, "s": 4089, "text": "anikakapoor" }, { "code": null, "e": 4114, "s": 4101, "text": "atharvakango" }, { "code": null, "e": 4123, "s": 4114, "text": "jeffreyk" }, { "code": null, "e": 4136, "s": 4123, "text": "MAQ Software" }, { "code": null, "e": 4155, "s": 4136, "text": "programming-puzzle" }, { "code": null, "e": 4179, "s": 4155, "text": "Technical Scripter 2018" }, { "code": null, "e": 4191, "s": 4179, "text": "Linked List" }, { "code": null, "e": 4210, "s": 4191, "text": "Technical Scripter" }, { "code": null, "e": 4223, "s": 4210, "text": "MAQ Software" }, { "code": null, "e": 4235, "s": 4223, "text": "Linked List" }, { "code": null, "e": 4333, "s": 4235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4352, "s": 4333, "text": "LinkedList in Java" }, { "code": null, "e": 4384, "s": 4352, "text": "Introduction to Data Structures" }, { "code": null, "e": 4440, "s": 4384, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 4470, "s": 4440, "text": "Merge two sorted linked lists" }, { "code": null, "e": 4534, "s": 4470, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 4555, "s": 4534, "text": "Linked List vs Array" }, { "code": null, "e": 4583, "s": 4555, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 4630, "s": 4583, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4685, "s": 4630, "text": "Find Length of a Linked List (Iterative and Recursive)" } ]
How to scroll to top on every Route click in Angular5 ?
18 Sep, 2020 We can use Router and NavigationEnd from ‘@angular/router’ and hence we can scroll to the top of the webpage for every route. Approach: First, we need to import the Router and NavigationEnd from ‘@angular/router’ in both app.module.ts file and app.component.ts. Then we need to create an instance of those in the constructor function. After creating the instance we need to use them in the ngOninit() life cycle hook. In the ngOninit() hook, we need to subscribe to the events of the router and check whether it is an instance of NavigationEnd or not. Then after checking we can use the window.scrollTo() function with (0,0) coordinates to navigate to the top. After following the above steps start your project using the below command. ng serve --open Below is the implementation of the above steps: app.module.ts: Javascript import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; const routes: Routes = [ { path: '', component: AppComponent },]; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot(routes) ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { } app.component.ts: Javascript import { Component, OnInit } from '@angular/core';import { Router, NavigationEnd } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent implements OnInit { constructor(private router: Router) { } ngOnInit() { this.router.events.subscribe((event) => { if (!(event instanceof NavigationEnd)) { return; } window.scrollTo(0, 0) }); }} app.component.html: HTML <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"><div class="jumbotron"> <h1 class="display-4">Hello,Geek!</h1> <p class="lead"> GeeksForGeeks is a website which is a one stop destination for all the computer science related doubts. </p> <hr class="my-4"> <p> Click on the below button to starting learning. </p> <p class="lead"> <a class="btn btn-primary btn-lg" href="#" role="button"> Explore </a> </p></div> <div class="card"> <div class="card-header"> Featured </div> <div class="card-body"> <h5 class="card-title"> Front End Technologies </h5> <p class="card-text"> HTML, CSS, Javascript, Angular, React.js </p> <a href="#" class="btn btn-primary"> Start Learning </a> </div></div><br> <div class="card"> <div class="card-header"> Featured </div> <div class="card-body"> <h5 class="card-title"> Backend Technologies </h5> <p class="card-text"> Node.js, Django,Express </p> <a href="#" class="btn btn-primary"> Start Learning </a> </div></div> Output: AngularJS-Misc Picked AngularJS Web Technologies 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": "\n18 Sep, 2020" }, { "code": null, "e": 154, "s": 28, "text": "We can use Router and NavigationEnd from ‘@angular/router’ and hence we can scroll to the top of the webpage for every route." }, { "code": null, "e": 164, "s": 154, "text": "Approach:" }, { "code": null, "e": 290, "s": 164, "text": "First, we need to import the Router and NavigationEnd from ‘@angular/router’ in both app.module.ts file and app.component.ts." }, { "code": null, "e": 363, "s": 290, "text": "Then we need to create an instance of those in the constructor function." }, { "code": null, "e": 446, "s": 363, "text": "After creating the instance we need to use them in the ngOninit() life cycle hook." }, { "code": null, "e": 580, "s": 446, "text": "In the ngOninit() hook, we need to subscribe to the events of the router and check whether it is an instance of NavigationEnd or not." }, { "code": null, "e": 689, "s": 580, "text": "Then after checking we can use the window.scrollTo() function with (0,0) coordinates to navigate to the top." }, { "code": null, "e": 765, "s": 689, "text": "After following the above steps start your project using the below command." }, { "code": null, "e": 781, "s": 765, "text": "ng serve --open" }, { "code": null, "e": 829, "s": 781, "text": "Below is the implementation of the above steps:" }, { "code": null, "e": 844, "s": 829, "text": "app.module.ts:" }, { "code": null, "e": 855, "s": 844, "text": "Javascript" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; const routes: Routes = [ { path: '', component: AppComponent },]; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot(routes) ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { }", "e": 1308, "s": 855, "text": null }, { "code": null, "e": 1326, "s": 1308, "text": "app.component.ts:" }, { "code": null, "e": 1337, "s": 1326, "text": "Javascript" }, { "code": "import { Component, OnInit } from '@angular/core';import { Router, NavigationEnd } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent implements OnInit { constructor(private router: Router) { } ngOnInit() { this.router.events.subscribe((event) => { if (!(event instanceof NavigationEnd)) { return; } window.scrollTo(0, 0) }); }}", "e": 1821, "s": 1337, "text": null }, { "code": null, "e": 1841, "s": 1821, "text": "app.component.html:" }, { "code": null, "e": 1846, "s": 1841, "text": "HTML" }, { "code": "<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" rel=\"stylesheet\"><div class=\"jumbotron\"> <h1 class=\"display-4\">Hello,Geek!</h1> <p class=\"lead\"> GeeksForGeeks is a website which is a one stop destination for all the computer science related doubts. </p> <hr class=\"my-4\"> <p> Click on the below button to starting learning. </p> <p class=\"lead\"> <a class=\"btn btn-primary btn-lg\" href=\"#\" role=\"button\"> Explore </a> </p></div> <div class=\"card\"> <div class=\"card-header\"> Featured </div> <div class=\"card-body\"> <h5 class=\"card-title\"> Front End Technologies </h5> <p class=\"card-text\"> HTML, CSS, Javascript, Angular, React.js </p> <a href=\"#\" class=\"btn btn-primary\"> Start Learning </a> </div></div><br> <div class=\"card\"> <div class=\"card-header\"> Featured </div> <div class=\"card-body\"> <h5 class=\"card-title\"> Backend Technologies </h5> <p class=\"card-text\"> Node.js, Django,Express </p> <a href=\"#\" class=\"btn btn-primary\"> Start Learning </a> </div></div>", "e": 3167, "s": 1846, "text": null }, { "code": null, "e": 3175, "s": 3167, "text": "Output:" }, { "code": null, "e": 3190, "s": 3175, "text": "AngularJS-Misc" }, { "code": null, "e": 3197, "s": 3190, "text": "Picked" }, { "code": null, "e": 3207, "s": 3197, "text": "AngularJS" }, { "code": null, "e": 3224, "s": 3207, "text": "Web Technologies" }, { "code": null, "e": 3322, "s": 3224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3353, "s": 3322, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 3377, "s": 3353, "text": "Routing in Angular 9/10" }, { "code": null, "e": 3422, "s": 3377, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 3464, "s": 3422, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 3499, "s": 3464, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 3532, "s": 3499, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3594, "s": 3532, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3655, "s": 3594, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3705, "s": 3655, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Memory Management in Operating Systems - GeeksQuiz
03 Oct, 2019 Let the page size is of 'x' bits Size of T1 = 2 ^ x bytes (This is because T1 occupies exactly one page) Now, number of entries in T1 = (2^x) / 4 (This is because each page table entry is 32 bits or 4 bytes in size) Number of entries in T1 = Number of second level page tables (Because each I-level page table entry stores the base address of page of II-level page table) Total size of second level page tables = ((2^x) / 4) * (2^x) Similarly, number of entries in II-level page tables = Number of III level page tables = ((2^x) / 4) * ((2^x) / 4) Total size of third level page tables = ((2^x) / 4) * ((2^x) / 4) * (2^x) Similarly, total number of entries (pages) in all III-level page tables = ((2^x) / 4) * ((2^x) / 4) * ((2^x) / 4) = 2^(3x - 6) Size of virtual memory = 2^46 Number of pages in virtual memory = (2^46) / (2^x) = 2^(46 - x) Total number the pages in the III-level page tables = Number of pages in virtual memory 2^(3x - 6) = 2^(46 - x) 3x - 6 = 46 - x 4x = 52 x = 13 That means, page size is of 13 bits or Page size = 2^13 bytes = 8 KB 1 MB 16-way set associative virtually indexed physically tagged cache(VIPT). The cache block size is 64 bytes. No of blocks is 2^20/2^6 = 2^14. No of sets is 2^14/2^4 = 2^10. VA(46) +-------------------------------+ tag(30) , Set(10) , block offset(6) +-------------------------------+ In VIPT if the no. of bits of page offset = (Set+block offset) then only one page color is sufficient. but we need 8 colors because the number bits where the cache set index and physical page number over lap is 3 so 2^3 page colors is required.(option c is ans). Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 34106, "s": 34078, "text": "\n03 Oct, 2019" }, { "code": null, "e": 35270, "s": 34106, "text": "Let the page size is of 'x' bits\n\nSize of T1 = 2 ^ x bytes\n\n(This is because T1 occupies exactly one page)\n\nNow, number of entries in T1 = (2^x) / 4\n\n(This is because each page table entry is 32 bits\n or 4 bytes in size)\n\nNumber of entries in T1 = Number of second level \npage tables\n\n(Because each I-level page table entry stores the \n base address of page of II-level page table)\n\nTotal size of second level page tables = ((2^x) / 4) * (2^x)\n\nSimilarly, number of entries in II-level page tables = Number\n of III level page tables = ((2^x) / 4) * ((2^x) / 4)\n\nTotal size of third level page tables = ((2^x) / 4) * \n ((2^x) / 4) * (2^x)\n\nSimilarly, total number of entries (pages) in all III-level \npage tables = ((2^x) / 4) * ((2^x) / 4) * ((2^x) / 4)\n = 2^(3x - 6)\n\nSize of virtual memory = 2^46\n\nNumber of pages in virtual memory = (2^46) / (2^x) = 2^(46 - x)\n\nTotal number the pages in the III-level page tables = \n Number of pages in virtual memory\n\n2^(3x - 6) = 2^(46 - x)\n\n3x - 6 = 46 - x\n\n4x = 52\nx = 13\n\nThat means, page size is of 13 bits\nor Page size = 2^13 bytes = 8 KB " }, { "code": null, "e": 35847, "s": 35270, "text": "1 MB 16-way set associative virtually indexed physically tagged cache(VIPT). \nThe cache block size is 64 bytes.\n\nNo of blocks is 2^20/2^6 = 2^14.\n\nNo of sets is 2^14/2^4 = 2^10.\n\nVA(46)\n+-------------------------------+\ntag(30) , Set(10) , block offset(6)\n+-------------------------------+\n\nIn VIPT if the no. of bits of page offset = \n (Set+block offset) then only one page color is sufficient.\n\nbut we need 8 colors because the number bits where the cache set index and \nphysical page number over lap is 3 so 2^3 page colors is required.(option \nc is ans). " } ]
PostgreSQL – While Loops
24 Jan, 2021 PostgreSQL provides the loop statement which simply defines an unconditional loop that executes repeatedly a block of code until terminated by an exit or return statement. The while loop statement executes a block of code till the condition remains true and stops executing when the conditions become false. The syntax of the loop statement: [ <<label>> ] while condition loop statements; end loop; If we analyze the above syntax: Condition: If the condition is true, it executes the statements. After each iteration, the while loop again checks the condition. Body / Statements: Inside the body of the while loop, we need to change the values of some variables to make the condition false or null at some points. Otherwise, we will encounter the case of an infinite loop. As the while loop tests the condition before executing the statements, it is also referred to as a pretest loop. The following flowchart describes the while loop statement: Flowchart of While loop Example 1: The following code is used to raise notices while increasing the count of an arbitrary variable from 0 to 9. do $$ declare add integer := 0; begin while add <10 loop raise notice 'Out addition count %', add; add := add+1; end loop; end$$; Output: Example 2: The following code is used to raise notices while decreasing the count of an arbitrary variable from 10 to 1. do $$ declare add integer := 10; begin while add > 0 loop raise notice 'Out addition count %',add; add := add-1; end loop; end$$; Output: Picked Technical Scripter 2020 PostgreSQL Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - Psql commands PostgreSQL - Change Column Type PostgreSQL - For Loops PostgreSQL - Function Returning A Table PostgreSQL - LIMIT with OFFSET clause PostgreSQL - ARRAY_AGG() Function PostgreSQL - DROP INDEX PostgreSQL - Create Auto-increment Column using SERIAL PostgreSQL - Copy Table PostgreSQL - ROW_NUMBER Function
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 336, "s": 28, "text": "PostgreSQL provides the loop statement which simply defines an unconditional loop that executes repeatedly a block of code until terminated by an exit or return statement. The while loop statement executes a block of code till the condition remains true and stops executing when the conditions become false." }, { "code": null, "e": 370, "s": 336, "text": "The syntax of the loop statement:" }, { "code": null, "e": 429, "s": 370, "text": "[ <<label>> ]\nwhile condition loop\n statements;\nend loop;" }, { "code": null, "e": 461, "s": 429, "text": "If we analyze the above syntax:" }, { "code": null, "e": 591, "s": 461, "text": "Condition: If the condition is true, it executes the statements. After each iteration, the while loop again checks the condition." }, { "code": null, "e": 803, "s": 591, "text": "Body / Statements: Inside the body of the while loop, we need to change the values of some variables to make the condition false or null at some points. Otherwise, we will encounter the case of an infinite loop." }, { "code": null, "e": 916, "s": 803, "text": "As the while loop tests the condition before executing the statements, it is also referred to as a pretest loop." }, { "code": null, "e": 976, "s": 916, "text": "The following flowchart describes the while loop statement:" }, { "code": null, "e": 1000, "s": 976, "text": "Flowchart of While loop" }, { "code": null, "e": 1011, "s": 1000, "text": "Example 1:" }, { "code": null, "e": 1121, "s": 1011, "text": " The following code is used to raise notices while increasing the count of an arbitrary variable from 0 to 9." }, { "code": null, "e": 1251, "s": 1121, "text": "do $$\ndeclare\nadd integer := 0;\nbegin\nwhile add <10 loop\nraise notice 'Out addition count %', add;\nadd := add+1;\nend loop;\nend$$;" }, { "code": null, "e": 1259, "s": 1251, "text": "Output:" }, { "code": null, "e": 1270, "s": 1259, "text": "Example 2:" }, { "code": null, "e": 1381, "s": 1270, "text": " The following code is used to raise notices while decreasing the count of an arbitrary variable from 10 to 1." }, { "code": null, "e": 1511, "s": 1381, "text": "do $$\ndeclare\nadd integer := 10;\nbegin\nwhile add > 0 loop\nraise notice 'Out addition count %',add;\nadd := add-1;\nend loop;\nend$$;" }, { "code": null, "e": 1519, "s": 1511, "text": "Output:" }, { "code": null, "e": 1526, "s": 1519, "text": "Picked" }, { "code": null, "e": 1550, "s": 1526, "text": "Technical Scripter 2020" }, { "code": null, "e": 1561, "s": 1550, "text": "PostgreSQL" }, { "code": null, "e": 1580, "s": 1561, "text": "Technical Scripter" }, { "code": null, "e": 1678, "s": 1580, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1705, "s": 1678, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 1737, "s": 1705, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 1760, "s": 1737, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 1800, "s": 1760, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 1838, "s": 1800, "text": "PostgreSQL - LIMIT with OFFSET clause" }, { "code": null, "e": 1872, "s": 1838, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 1896, "s": 1872, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 1951, "s": 1896, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 1975, "s": 1951, "text": "PostgreSQL - Copy Table" } ]
Deadlock - GeeksforGeeks
28 Mar, 2020 if (i % 2 == 0) { if (i < n) request Ri if (i+2 < n) request Ri+2 } else { if (i < n) request Rn-i if (i+2 < n) request Rn-i-2 } Option B is answer No. of resources, n = 21 No. of processes, k = 12 Processes {P0, P1....P11} make the following Resource requests: {R0, R20, R2, R18, R4, R16, R6, R14, R8, R12, R10, R10} For example P0 will request R0 (0%2 is = 0 and 0< n=21). Similarly, P10 will request R10. P11 will request R10 as n - i = 21 - 11 = 10. As different processes are requesting the same resource, deadlock may occur. Process P1: t=0: requests 2 units of R2 t=1: requests 1 unit of R3 t=3: requests 2 units of R1 t=5: releases 1 unit of R2 and 1 unit of R1. t=7: releases 1 unit of R3 t=8: requests 2 units of R4 t=10: Finishes Process P2: t=0: requests 2 units of R3 t=2: requests 1 unit of R4 t=4: requests 1 unit of R1 t=6: releases 1 unit of R3 t=8: Finishes Process P3: t=0: requests 1 unit of R4 t=2: requests 2 units of R1 t=5: releases 2 units of R1 t=7: requests 1 unit of R2 t=8: requests 1 unit of R3 t=9: Finishes We can apply the following Deadlock Detection algorithm and see that there is no process waiting indefinitely for a resource. See this for deadlock detection algorithm. REQ1: P0 requests 0 units of X, 0 units of Y and 2 units of Z REQ2: P1 requests 2 units of X, 0 units of Y and 0 units of Z Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Must Do Coding Questions for Product Based Companies 50 Common Ports You Should Know GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? Types of Distributed System Spring Boot - Thymeleaf with Example Naming Convention in C++ How to Install MySQL on Linux? Floyd’s Cycle Finding Algorithm How to use arrays to swap variables in JavaScript ?
[ { "code": null, "e": 34185, "s": 34157, "text": "\n28 Mar, 2020" }, { "code": null, "e": 34339, "s": 34185, "text": " if (i % 2 == 0) {\n if (i < n) request Ri\n if (i+2 < n) request Ri+2\n}\nelse {\n if (i < n) request Rn-i\n if (i+2 < n) request Rn-i-2\n}" }, { "code": null, "e": 34750, "s": 34339, "text": "Option B is answer\n\nNo. of resources, n = 21\nNo. of processes, k = 12\n\nProcesses {P0, P1....P11} make the following Resource requests:\n{R0, R20, R2, R18, R4, R16, R6, R14, R8, R12, R10, R10}\n\nFor example P0 will request R0 (0%2 is = 0 and 0< n=21). \n\nSimilarly, P10 will request R10.\n\nP11 will request R10 as n - i = 21 - 11 = 10.\n\nAs different processes are requesting the same resource, deadlock\nmay occur. " }, { "code": null, "e": 35290, "s": 34750, "text": "Process P1: \nt=0: requests 2 units of R2 \nt=1: requests 1 unit of R3 \nt=3: requests 2 units of R1 \nt=5: releases 1 unit of R2 \n and 1 unit of R1. \nt=7: releases 1 unit of R3 \nt=8: requests 2 units of R4 \nt=10: Finishes\n\nProcess P2: \nt=0: requests 2 units of R3 \nt=2: requests 1 unit of R4 \nt=4: requests 1 unit of R1 \nt=6: releases 1 unit of R3 \nt=8: Finishes\n\nProcess P3: \nt=0: requests 1 unit of R4 \nt=2: requests 2 units of R1 \nt=5: releases 2 units of R1 \nt=7: requests 1 unit of R2 \nt=8: requests 1 unit of R3 \nt=9: Finishes" }, { "code": null, "e": 35459, "s": 35290, "text": "We can apply the following Deadlock Detection algorithm and see that there is no process waiting indefinitely for a resource. See this for deadlock detection algorithm." }, { "code": null, "e": 35598, "s": 35459, "text": "REQ1: P0 requests 0 units of X, \n 0 units of Y and 2 units of Z\nREQ2: P1 requests 2 units of X, \n 0 units of Y and 0 units of Z" }, { "code": null, "e": 35696, "s": 35598, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 35770, "s": 35696, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 35823, "s": 35770, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 35855, "s": 35823, "text": "50 Common Ports You Should Know" }, { "code": null, "e": 35921, "s": 35855, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 35949, "s": 35921, "text": "Types of Distributed System" }, { "code": null, "e": 35986, "s": 35949, "text": "Spring Boot - Thymeleaf with Example" }, { "code": null, "e": 36011, "s": 35986, "text": "Naming Convention in C++" }, { "code": null, "e": 36042, "s": 36011, "text": "How to Install MySQL on Linux?" }, { "code": null, "e": 36074, "s": 36042, "text": "Floyd’s Cycle Finding Algorithm" } ]
How to perform tukey HSD in base R?
First thing you must remember while moving on to post hoc analysis is the null hypothesis of the analysis of variance must be rejected, so that we can claim there exists a difference in the group means. Now, once we achieve that the tukey HSD can be performed simply by using TukeyHSD function in base R. Consider the below data frame − Live Demo x1<-rep(LETTERS[1:4],5) y1<-rep(c(5,2000,30,99),5) df1<-data.frame(x1,y1) df1 x1 y1 1 A 5 2 B 2000 3 C 30 4 D 99 5 A 5 6 B 2000 7 C 30 8 D 99 9 A 5 10 B 2000 11 C 30 12 D 99 13 A 5 14 B 2000 15 C 30 16 D 99 17 A 5 18 B 2000 19 C 30 20 D 99 Performing analysis of variance − ANOVA<-aov(y1~x1,data=df1) summary(ANOVA) Df Sum Sq Mean Sq F value Pr(>F) x1 3 14361185 4787062 1.07e+32 <2e-16 *** Residuals 16 0 0 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Performing tukey HSD − TukeyHSD(ANOVA) Tukey multiple comparisons of means 95% family-wise confidence level Fit: aov(formula = y1 ~ x1, data = df1) $x1 diff lwr upr p adj B-A 1995 1995 1995 0 C-A 25 25 25 0 D-A 94 94 94 0 C-B -1970 -1970 -1970 0 D-B -1901 -1901 -1901 0 D-C 69 69 69 0 Consider the PlantGrowth data in base R − Live Demo str(PlantGrowth) 'data.frame': 30 obs. of 2 variables: $ weight: num 4.17 5.58 5.18 6.11 4.5 4.61 5.17 4.53 5.33 5.14 ... $ group : Factor w/ 3 levels "ctrl","trt1",..: 1 1 1 1 1 1 1 1 1 1 ... Live Demo head(PlantGrowth,20) weight group 1 4.17 ctrl 2 5.58 ctrl 3 5.18 ctrl 4 6.11 ctrl 5 4.50 ctrl 6 4.61 ctrl 7 5.17 ctrl 8 4.53 ctrl 9 5.33 ctrl 10 5.14 ctrl 11 4.81 trt1 12 4.17 trt1 13 4.41 trt1 14 3.59 trt1 15 5.87 trt1 16 3.83 trt1 17 6.03 trt1 18 4.89 trt1 19 4.32 trt1 20 4.69 trt1 Performing analysis of variance − Live Demo ANOVA<-aov(weight~group,data=PlantGrowth) summary(ANOVA) Df Sum Sq Mean Sq F value Pr(>F) group 2 3.766 1.8832 4.846 0.0159 * Residuals 27 10.492 0.3886 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Performing tukey HSD − TukeyHSD(ANOVA) Tukey multiple comparisons of means 95% family-wise confidence level Fit: aov(formula = weight ~ group, data = PlantGrowth) $group diff lwr upr p adj trt1-ctrl -0.371 -1.0622161 0.3202161 0.3908711 trt2-ctrl 0.494 -0.1972161 1.1852161 0.1979960 trt2-trt1 0.865 0.1737839 1.5562161 0.0120064
[ { "code": null, "e": 1492, "s": 1187, "text": "First thing you must remember while moving on to post hoc analysis is the null hypothesis of the analysis of variance must be rejected, so that we can claim there exists a difference in the group means. Now, once we achieve that the tukey HSD can be performed simply by using TukeyHSD function in base R." }, { "code": null, "e": 1524, "s": 1492, "text": "Consider the below data frame −" }, { "code": null, "e": 1535, "s": 1524, "text": " Live Demo" }, { "code": null, "e": 1613, "s": 1535, "text": "x1<-rep(LETTERS[1:4],5)\ny1<-rep(c(5,2000,30,99),5)\ndf1<-data.frame(x1,y1)\ndf1" }, { "code": null, "e": 1786, "s": 1613, "text": " x1 y1\n1 A 5\n2 B 2000\n3 C 30\n4 D 99\n5 A 5\n6 B 2000\n7 C 30\n8 D 99\n9 A 5\n10 B 2000\n11 C 30\n12 D 99\n13 A 5\n14 B 2000\n15 C 30\n16 D 99\n17 A 5\n18 B 2000\n19 C 30\n20 D 99" }, { "code": null, "e": 1820, "s": 1786, "text": "Performing analysis of variance −" }, { "code": null, "e": 1862, "s": 1820, "text": "ANOVA<-aov(y1~x1,data=df1)\nsummary(ANOVA)" }, { "code": null, "e": 2020, "s": 1862, "text": "Df Sum Sq Mean Sq F value Pr(>F)\nx1 3 14361185 4787062 1.07e+32 <2e-16 ***\nResiduals 16 0 0\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1" }, { "code": null, "e": 2043, "s": 2020, "text": "Performing tukey HSD −" }, { "code": null, "e": 2059, "s": 2043, "text": "TukeyHSD(ANOVA)" }, { "code": null, "e": 2305, "s": 2059, "text": "Tukey multiple comparisons of means\n95% family-wise confidence level\nFit: aov(formula = y1 ~ x1, data = df1)\n$x1\ndiff lwr upr p adj\nB-A 1995 1995 1995 0\nC-A 25 25 25 0\nD-A 94 94 94 0\nC-B -1970 -1970 -1970 0\nD-B -1901 -1901 -1901 0\nD-C 69 69 69 0" }, { "code": null, "e": 2347, "s": 2305, "text": "Consider the PlantGrowth data in base R −" }, { "code": null, "e": 2358, "s": 2347, "text": " Live Demo" }, { "code": null, "e": 2375, "s": 2358, "text": "str(PlantGrowth)" }, { "code": null, "e": 2551, "s": 2375, "text": "'data.frame': 30 obs. of 2 variables:\n$ weight: num 4.17 5.58 5.18 6.11 4.5 4.61 5.17 4.53 5.33 5.14 ...\n$ group : Factor w/ 3 levels \"ctrl\",\"trt1\",..: 1 1 1 1 1 1 1 1 1 1 ..." }, { "code": null, "e": 2562, "s": 2551, "text": " Live Demo" }, { "code": null, "e": 2583, "s": 2562, "text": "head(PlantGrowth,20)" }, { "code": null, "e": 2848, "s": 2583, "text": " weight group\n1 4.17 ctrl\n2 5.58 ctrl\n3 5.18 ctrl\n4 6.11 ctrl\n5 4.50 ctrl\n6 4.61 ctrl\n7 5.17 ctrl\n8 4.53 ctrl\n9 5.33 ctrl\n10 5.14 ctrl\n11 4.81 trt1\n12 4.17 trt1\n13 4.41 trt1\n14 3.59 trt1\n15 5.87 trt1\n16 3.83 trt1\n17 6.03 trt1\n18 4.89 trt1\n19 4.32 trt1\n20 4.69 trt1" }, { "code": null, "e": 2882, "s": 2848, "text": "Performing analysis of variance −" }, { "code": null, "e": 2893, "s": 2882, "text": " Live Demo" }, { "code": null, "e": 2950, "s": 2893, "text": "ANOVA<-aov(weight~group,data=PlantGrowth)\nsummary(ANOVA)" }, { "code": null, "e": 3112, "s": 2950, "text": "Df Sum Sq Mean Sq F value Pr(>F)\ngroup 2 3.766 1.8832 4.846 0.0159 *\nResiduals 27 10.492 0.3886\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1" }, { "code": null, "e": 3135, "s": 3112, "text": "Performing tukey HSD −" }, { "code": null, "e": 3151, "s": 3135, "text": "TukeyHSD(ANOVA)" }, { "code": null, "e": 3442, "s": 3151, "text": "Tukey multiple comparisons of means\n95% family-wise confidence level\nFit: aov(formula = weight ~ group, data = PlantGrowth)\n$group\ndiff lwr upr p adj\ntrt1-ctrl -0.371 -1.0622161 0.3202161 0.3908711\ntrt2-ctrl 0.494 -0.1972161 1.1852161 0.1979960\ntrt2-trt1 0.865 0.1737839 1.5562161 0.0120064" } ]
Python | sympy.Derivative() method
02 Aug, 2019 With the help of sympy.Derivative() method, we can create an unevaluated derivative of a SymPy expression. It has the same syntax as diff() method. To evaluate an unevaluated derivative, use the doit() method. Syntax: Derivative(expression, reference variable) Parameters:expression – A SymPy expression whose unevaluated derivative is found.reference variable – Variable with respect to which derivative is found. Returns: Returns an unevaluated derivative of the given expression. Example #1: # import sympy from sympy import * x, y = symbols('x y')expr = x**2 + 2 * y + y**3print("Expression : {} ".format(expr)) # Use sympy.Derivative() method expr_diff = Derivative(expr, x) print("Derivative of expression with respect to x : {}".format(expr_diff)) print("Value of the derivative : {} ".format(expr_diff.doit())) Output: Expression : x**2 + y**3 + 2*y Derivative of expression with respect to x : Derivative(x**2 + y**3 + 2*y, x) Value of the derivative : 2*x Example #2: # import sympy from sympy import * x, y = symbols('x y')expr = y**2 * x**2 + 2 * y*x + x**3 * y**3print("Expression : {} ".format(expr)) # Use sympy.Derivative() method expr_diff = Derivative(expr, x, y) print("Derivative of expression with respect to x : {}".format(expr_diff)) print("Value of the derivative : {} ".format(expr_diff.doit())) Output: Expression : x**3*y**3 + x**2*y**2 + 2*x*y Derivative of expression with respect to x : Derivative(x**3*y**3 + x**2*y**2 + 2*x*y, x, y) Value of the derivative : 9*x**2*y**2 + 4*x*y + 2 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Aug, 2019" }, { "code": null, "e": 238, "s": 28, "text": "With the help of sympy.Derivative() method, we can create an unevaluated derivative of a SymPy expression. It has the same syntax as diff() method. To evaluate an unevaluated derivative, use the doit() method." }, { "code": null, "e": 289, "s": 238, "text": "Syntax: Derivative(expression, reference variable)" }, { "code": null, "e": 443, "s": 289, "text": "Parameters:expression – A SymPy expression whose unevaluated derivative is found.reference variable – Variable with respect to which derivative is found." }, { "code": null, "e": 511, "s": 443, "text": "Returns: Returns an unevaluated derivative of the given expression." }, { "code": null, "e": 523, "s": 511, "text": "Example #1:" }, { "code": "# import sympy from sympy import * x, y = symbols('x y')expr = x**2 + 2 * y + y**3print(\"Expression : {} \".format(expr)) # Use sympy.Derivative() method expr_diff = Derivative(expr, x) print(\"Derivative of expression with respect to x : {}\".format(expr_diff)) print(\"Value of the derivative : {} \".format(expr_diff.doit()))", "e": 859, "s": 523, "text": null }, { "code": null, "e": 867, "s": 859, "text": "Output:" }, { "code": null, "e": 1009, "s": 867, "text": "Expression : x**2 + y**3 + 2*y \nDerivative of expression with respect to x : Derivative(x**2 + y**3 + 2*y, x)\nValue of the derivative : 2*x \n" }, { "code": null, "e": 1021, "s": 1009, "text": "Example #2:" }, { "code": "# import sympy from sympy import * x, y = symbols('x y')expr = y**2 * x**2 + 2 * y*x + x**3 * y**3print(\"Expression : {} \".format(expr)) # Use sympy.Derivative() method expr_diff = Derivative(expr, x, y) print(\"Derivative of expression with respect to x : {}\".format(expr_diff)) print(\"Value of the derivative : {} \".format(expr_diff.doit()))", "e": 1376, "s": 1021, "text": null }, { "code": null, "e": 1384, "s": 1376, "text": "Output:" }, { "code": null, "e": 1573, "s": 1384, "text": "Expression : x**3*y**3 + x**2*y**2 + 2*x*y \nDerivative of expression with respect to x : Derivative(x**3*y**3 + x**2*y**2 + 2*x*y, x, y)\nValue of the derivative : 9*x**2*y**2 + 4*x*y + 2 \n" }, { "code": null, "e": 1579, "s": 1573, "text": "SymPy" }, { "code": null, "e": 1586, "s": 1579, "text": "Python" }, { "code": null, "e": 1684, "s": 1586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1702, "s": 1684, "text": "Python Dictionary" }, { "code": null, "e": 1744, "s": 1702, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1766, "s": 1744, "text": "Enumerate() in Python" }, { "code": null, "e": 1801, "s": 1766, "text": "Read a file line by line in Python" }, { "code": null, "e": 1827, "s": 1801, "text": "Python String | replace()" }, { "code": null, "e": 1859, "s": 1827, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1888, "s": 1859, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1915, "s": 1888, "text": "Python Classes and Objects" }, { "code": null, "e": 1945, "s": 1915, "text": "Iterate over a list in Python" } ]