title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Promoted Fields in Golang Structure - GeeksforGeeks
13 Aug, 2019 In Go structure, promoted fields are just like anonymous fields, the type of the field is the name of the field. We use this concept in the nested structure where a structure is a field in another structure, simply by just adding the name of the structure into another structure and it behaves like the Anonymous Field to the nested structure. And the fields of that structure (other than nested structure) are the part of the nested structure, such type of fields are known as Promoted fields. If the anonymous structure or nested structure and parent structure contains a field that has the same name, then that field doesn’t promote, only different name fields get promoted to the structure. Syntax: type x struct{ // Fields } type y struct{ // Fields of y structure x } Let us discuss this concept with the help of an example: Example: // Go program to illustrate the// concept of the promoted fieldspackage main import "fmt" // Structuretype details struct { // Fields of the // details structure name string age int gender string} // Nested structuretype student struct { branch string year int details} func main() { // Initializing the fields of // the student structure values := student{ branch: "CSE", year: 2010, details: details{ name: "Sumit", age: 28, gender: "Male", }, } // Promoted fields of the student structure fmt.Println("Name: ", values.name) fmt.Println("Age: ", values.age) fmt.Println("Gender: ", values.gender) // Normal fields of // the student structure fmt.Println("Year: ", values.year) fmt.Println("Branch : ", values.branch)} Output: Name: Sumit Age: 28 Gender: Male Year: 2010 Branch : CSE Explanation: In the above example, we have two structures named as details and student. Where details structure is the normal structure and student structure is the nested structure which contains the details structure as fields in it just like anonymous fields. Now, the fields of the details structure, i.e, name, age, and gender are promoted to the student structure and known as promoted fields. Now, you can directly access them with the help of the student structure like values.name, values.age, and values.gender. Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Golang Maps Slices in Golang How to Trim a String in Golang? Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? Interfaces in Golang Pointers in Golang strings.Join() Function in Golang With Examples Time Durations in Golang Data Types in Go
[ { "code": null, "e": 24368, "s": 24340, "text": "\n13 Aug, 2019" }, { "code": null, "e": 25063, "s": 24368, "text": "In Go structure, promoted fields are just like anonymous fields, the type of the field is the name of the field. We use this concept in the nested structure where a structure is a field in another structure, simply by just adding the name of the structure into another structure and it behaves like the Anonymous Field to the nested structure. And the fields of that structure (other than nested structure) are the part of the nested structure, such type of fields are known as Promoted fields. If the anonymous structure or nested structure and parent structure contains a field that has the same name, then that field doesn’t promote, only different name fields get promoted to the structure." }, { "code": null, "e": 25071, "s": 25063, "text": "Syntax:" }, { "code": null, "e": 25144, "s": 25071, "text": "type x struct{\n// Fields\n}\n\ntype y struct{\n// Fields of y structure\nx\n}\n" }, { "code": null, "e": 25201, "s": 25144, "text": "Let us discuss this concept with the help of an example:" }, { "code": null, "e": 25210, "s": 25201, "text": "Example:" }, { "code": "// Go program to illustrate the// concept of the promoted fieldspackage main import \"fmt\" // Structuretype details struct { // Fields of the // details structure name string age int gender string} // Nested structuretype student struct { branch string year int details} func main() { // Initializing the fields of // the student structure values := student{ branch: \"CSE\", year: 2010, details: details{ name: \"Sumit\", age: 28, gender: \"Male\", }, } // Promoted fields of the student structure fmt.Println(\"Name: \", values.name) fmt.Println(\"Age: \", values.age) fmt.Println(\"Gender: \", values.gender) // Normal fields of // the student structure fmt.Println(\"Year: \", values.year) fmt.Println(\"Branch : \", values.branch)}", "e": 26087, "s": 25210, "text": null }, { "code": null, "e": 26095, "s": 26087, "text": "Output:" }, { "code": null, "e": 26158, "s": 26095, "text": "Name: Sumit\nAge: 28\nGender: Male\nYear: 2010\nBranch : CSE\n" }, { "code": null, "e": 26680, "s": 26158, "text": "Explanation: In the above example, we have two structures named as details and student. Where details structure is the normal structure and student structure is the nested structure which contains the details structure as fields in it just like anonymous fields. Now, the fields of the details structure, i.e, name, age, and gender are promoted to the student structure and known as promoted fields. Now, you can directly access them with the help of the student structure like values.name, values.age, and values.gender." }, { "code": null, "e": 26687, "s": 26680, "text": "Golang" }, { "code": null, "e": 26699, "s": 26687, "text": "Go Language" }, { "code": null, "e": 26797, "s": 26699, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26809, "s": 26797, "text": "Golang Maps" }, { "code": null, "e": 26826, "s": 26809, "text": "Slices in Golang" }, { "code": null, "e": 26858, "s": 26826, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 26912, "s": 26858, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 26941, "s": 26912, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 26962, "s": 26941, "text": "Interfaces in Golang" }, { "code": null, "e": 26981, "s": 26962, "text": "Pointers in Golang" }, { "code": null, "e": 27029, "s": 26981, "text": "strings.Join() Function in Golang With Examples" }, { "code": null, "e": 27054, "s": 27029, "text": "Time Durations in Golang" } ]
Nested Loops in C with Examples - GeeksforGeeks
26 Nov, 2019 Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as “loop inside loop“. Syntax for Nested For loop: for ( initialization; condition; increment ) { for ( initialization; condition; increment ) { // statement of inside loop } // statement of outer loop } Syntax for Nested While loop: while(condition) { while(condition) { // statement of inside loop } // statement of outer loop } Syntax for Nested Do-While loop: do{ do{ // statement of inside loop }while(condition); // statement of outer loop }while(condition); Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level. Syntax: do{ while(condition) { for ( initialization; condition; increment ) { // statement of inside for loop } // statement of inside while loop } // statement of outer do-while loop }while(condition); Below are some examples to demonstrate the use of Nested Loops: Example 1: Below program uses a nested for loop to print a 2D matrix of 3×3. // C program that uses nested for loop// to print a 2D matrix #include <stdio.h>#include <stdlib.h> #define ROW 3#define COL 3 // Driver programint main(){ int i, j; // Declare the matrix int matrix[ROW][COL] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; printf("Given matrix is \n"); // Print the matrix using nested loops for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) printf("%d ", matrix[i][j]); printf("\n"); } return 0;} Given matrix is 1 2 3 4 5 6 7 8 9 Example 2: Below program uses a nested for loop to print all prime factors of a number. // C Program to print all prime factors// of a number using nested loop #include <math.h>#include <stdio.h> // A function to print all prime factors of a given number nvoid primeFactors(int n){ // Print the number of 2s that divide n while (n % 2 == 0) { printf("%d ", 2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { printf("%d ", i); n = n / i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) printf("%d ", n);} /* Driver program to test above function */int main(){ int n = 315; primeFactors(n); return 0;} 3 3 5 7 C-Loops & Control Statements C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ UDP Server-Client implementation in C Arrow operator -> in C/C++ with Examples Understanding "extern" keyword in C Storage Classes in C Smart Pointers in C++ and How to Use Them Switch Statement in C/C++
[ { "code": null, "e": 24234, "s": 24206, "text": "\n26 Nov, 2019" }, { "code": null, "e": 24364, "s": 24234, "text": "Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as “loop inside loop“." }, { "code": null, "e": 24392, "s": 24364, "text": "Syntax for Nested For loop:" }, { "code": null, "e": 24570, "s": 24392, "text": "for ( initialization; condition; increment ) {\n\n for ( initialization; condition; increment ) {\n \n // statement of inside loop\n }\n\n // statement of outer loop\n}\n" }, { "code": null, "e": 24600, "s": 24570, "text": "Syntax for Nested While loop:" }, { "code": null, "e": 24722, "s": 24600, "text": "while(condition) {\n\n while(condition) {\n \n // statement of inside loop\n }\n\n // statement of outer loop\n}\n" }, { "code": null, "e": 24755, "s": 24722, "text": "Syntax for Nested Do-While loop:" }, { "code": null, "e": 24881, "s": 24755, "text": "do{\n\n do{\n \n // statement of inside loop\n }while(condition);\n\n // statement of outer loop\n}while(condition);\n" }, { "code": null, "e": 25032, "s": 24881, "text": "Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level." }, { "code": null, "e": 25040, "s": 25032, "text": "Syntax:" }, { "code": null, "e": 25289, "s": 25040, "text": "do{\n\n while(condition) {\n \n for ( initialization; condition; increment ) {\n \n // statement of inside for loop\n }\n\n // statement of inside while loop\n }\n\n // statement of outer do-while loop\n}while(condition);\n" }, { "code": null, "e": 25353, "s": 25289, "text": "Below are some examples to demonstrate the use of Nested Loops:" }, { "code": null, "e": 25430, "s": 25353, "text": "Example 1: Below program uses a nested for loop to print a 2D matrix of 3×3." }, { "code": "// C program that uses nested for loop// to print a 2D matrix #include <stdio.h>#include <stdlib.h> #define ROW 3#define COL 3 // Driver programint main(){ int i, j; // Declare the matrix int matrix[ROW][COL] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; printf(\"Given matrix is \\n\"); // Print the matrix using nested loops for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) printf(\"%d \", matrix[i][j]); printf(\"\\n\"); } return 0;}", "e": 25983, "s": 25430, "text": null }, { "code": null, "e": 26021, "s": 25983, "text": "Given matrix is \n1 2 3 \n4 5 6 \n7 8 9\n" }, { "code": null, "e": 26109, "s": 26021, "text": "Example 2: Below program uses a nested for loop to print all prime factors of a number." }, { "code": "// C Program to print all prime factors// of a number using nested loop #include <math.h>#include <stdio.h> // A function to print all prime factors of a given number nvoid primeFactors(int n){ // Print the number of 2s that divide n while (n % 2 == 0) { printf(\"%d \", 2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { printf(\"%d \", i); n = n / i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) printf(\"%d \", n);} /* Driver program to test above function */int main(){ int n = 315; primeFactors(n); return 0;}", "e": 26932, "s": 26109, "text": null }, { "code": null, "e": 26941, "s": 26932, "text": "3 3 5 7\n" }, { "code": null, "e": 26970, "s": 26941, "text": "C-Loops & Control Statements" }, { "code": null, "e": 26981, "s": 26970, "text": "C Language" }, { "code": null, "e": 27079, "s": 26981, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27088, "s": 27079, "text": "Comments" }, { "code": null, "e": 27101, "s": 27088, "text": "Old Comments" }, { "code": null, "e": 27139, "s": 27101, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27165, "s": 27139, "text": "Exception Handling in C++" }, { "code": null, "e": 27185, "s": 27165, "text": "Multithreading in C" }, { "code": null, "e": 27207, "s": 27185, "text": "'this' pointer in C++" }, { "code": null, "e": 27245, "s": 27207, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27286, "s": 27245, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27322, "s": 27286, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 27343, "s": 27322, "text": "Storage Classes in C" }, { "code": null, "e": 27385, "s": 27343, "text": "Smart Pointers in C++ and How to Use Them" } ]
Reset the primary key to 1 after deleting all the data in MySQL?
To reset the primary key to 1 after deleting the data, use the following syntax alter table yourTableName AUTO_INCREMENT=1; truncate table yourTableName; After doing the above two steps, you will get the primary key beginning from 1. To understand the above concept, let us create a table. The query to create a table is as follows mysql> create table resettingPrimaryKeyDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY -> ); Query OK, 0 rows affected (0.66 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.15 sec) mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.10 sec) mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.08 sec) mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from resettingPrimaryKeyDemo; The following is the output +--------+ | UserId | +--------+ | 1 | | 2 | | 3 | | 4 | +--------+ 4 rows in set (0.00 sec) Here is the query to reset the primary key to 1 mysql> alter table resettingPrimaryKeyDemo AUTO_INCREMENT=1; Query OK, 0 rows affected (0.14 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> truncate table resettingPrimaryKeyDemo; Query OK, 0 rows affected (0.89 sec) Check the records from the table. The query is as follows − mysql> select *from resettingPrimaryKeyDemo; Empty set (0.00 sec) Insert some records from the table using insert command. The query is as follows − mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.12 sec) mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.10 sec) mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.10 sec) Now check the table primary key beginning from 1. The query is as follows − mysql> select *from resettingPrimaryKeyDemo; The following is the output +--------+ | UserId | +--------+ | 1 | | 2 | | 3 | +--------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1142, "s": 1062, "text": "To reset the primary key to 1 after deleting the data, use the following syntax" }, { "code": null, "e": 1216, "s": 1142, "text": "alter table yourTableName AUTO_INCREMENT=1;\ntruncate table yourTableName;" }, { "code": null, "e": 1296, "s": 1216, "text": "After doing the above two steps, you will get the primary key beginning from 1." }, { "code": null, "e": 1394, "s": 1296, "text": "To understand the above concept, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1545, "s": 1394, "text": "mysql> create table resettingPrimaryKeyDemo\n -> (\n -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY\n -> );\nQuery OK, 0 rows affected (0.66 sec)" }, { "code": null, "e": 1626, "s": 1545, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 1982, "s": 1626, "text": "mysql> insert into resettingPrimaryKeyDemo values();\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into resettingPrimaryKeyDemo values();\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into resettingPrimaryKeyDemo values();\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into resettingPrimaryKeyDemo values();\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 2067, "s": 1982, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2112, "s": 2067, "text": "mysql> select *from resettingPrimaryKeyDemo;" }, { "code": null, "e": 2140, "s": 2112, "text": "The following is the output" }, { "code": null, "e": 2253, "s": 2140, "text": "+--------+\n| UserId |\n+--------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2301, "s": 2253, "text": "Here is the query to reset the primary key to 1" }, { "code": null, "e": 2520, "s": 2301, "text": "mysql> alter table resettingPrimaryKeyDemo AUTO_INCREMENT=1;\nQuery OK, 0 rows affected (0.14 sec)\nRecords: 0 Duplicates: 0 Warnings: 0\nmysql> truncate table resettingPrimaryKeyDemo;\nQuery OK, 0 rows affected (0.89 sec)" }, { "code": null, "e": 2580, "s": 2520, "text": "Check the records from the table. The query is as follows −" }, { "code": null, "e": 2646, "s": 2580, "text": "mysql> select *from resettingPrimaryKeyDemo;\nEmpty set (0.00 sec)" }, { "code": null, "e": 2729, "s": 2646, "text": "Insert some records from the table using insert command. The query is as follows −" }, { "code": null, "e": 2996, "s": 2729, "text": "mysql> insert into resettingPrimaryKeyDemo values();\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into resettingPrimaryKeyDemo values();\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into resettingPrimaryKeyDemo values();\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 3072, "s": 2996, "text": "Now check the table primary key beginning from 1. The query is as follows −" }, { "code": null, "e": 3117, "s": 3072, "text": "mysql> select *from resettingPrimaryKeyDemo;" }, { "code": null, "e": 3145, "s": 3117, "text": "The following is the output" }, { "code": null, "e": 3247, "s": 3145, "text": "+--------+\n| UserId |\n+--------+\n| 1 |\n| 2 |\n| 3 |\n+--------+\n3 rows in set (0.00 sec)" } ]
5 Key AI problems related to Data Privacy | by Alexandros Zenonos, PhD | Towards Data Science
Privacy is a concern not only related to Artificial Intelligence (AI) but any data-related field in general. It is about people having control over their personal data and decisions taken based on those. In Europe, the General Data Protection Regulation (GDPR) that came into force in 2018 regulates the collection and use of personal data.[1] Data protection law does not refer explicitly to AI or Machine Learning but there is a significant focus on large-scale automated processing of personal data and automated decision-making. This means that where AI uses personal data it falls within the scope of the regulation and GDPR principles apply. This can be through the use of personal data to train, test or deploy an AI system. Failure to comply with the GDPR may result in enormous penalties for the companies involved. Some examples of personal data would be the date of birth, postcode, gender or even a user’s IP address. Specifically, GDPR gives individuals the right not to be subject to a solely automated decision. The key question for AI experts then is: How can you show that you treated an individual fairly and in a transparent manner when making AI-assisted decision about them, or give them the opportunity to contest such decision? Even though GDPR is most relevant to Europe and the UK, the main principles and ideas should be relevant worldwide. Although fairness and explainability of the models are active research topics in AI, there are at least 5 considerations that you could already be thinking about in relation to data privacy. Class imbalance occurs when your training labels are disproportionally in favour of a specific class. In other words, in a binary classification problem, you have lots of examples for cases where the output is 0 but only a few when the output is 1, or vice versa. This might be due to a bias in the data collection process e.g. data collected only from a local branch, or be inherent in the properties of the domain e.g., identifying anomalous data points in a manufacturing process. Class imbalance is one of the most common reasons for model bias, but it is often ignored by data scientists. This is because, typically, minor imbalance does not pose a huge risk as the models can learn the features of all classes equally well. However, when a severe class imbalance occurs, things can be tricky. Specifically, the minority class will be harder to predict, so your model is biased towards the majority class. For example, when you train an AI system to recognise images you could face a number of potential issues, class imbalance may be one of those. Think of a group of 100,000 images out of which only 100 are images of cats and 99,900 are images of dogs. The AI system you trained is more likely to predict a dog as it is trained to do so more frequently; it doesn’t have enough negative cases to accurately distinguish between the two types of images. This potential issue is not as innocent as wrongly classifying cats and dogs. Imagine you are training a model to accept or reject personal loans and most of the historic loans got rejected (for some reason). Guess what. Your model is likely to reject most or all of the future loan applications as it was more exposed to this sort of information and potentially didn’t learn to differentiate between the two cases. This is an issue from a data privacy perspective as the model does not produce fair results. Mitigation measures: First of all, identifying whether this can be an issue early on is important. You can check that by understanding the volume of data points belonging to each of your classes: df[‘your_label’].value_counts() If you do notice a class imbalance but you still run a simple model on your data anyway, you are likely to get good results in terms of accuracy. Your test data are likely to follow the same distribution as your train data and thus if most instances were mostly from 1 class, just always predicting that class gives good accuracy score. But don’t get fooled by that. Typically a confusion matrix will give you a better picture on what your model is actually doing. One of the main and easiest strategies to mitigate issues related to that is random resampling. You can either reduce your majority class to match the minority (under-sampling) or oversample the minority class. In practice, count_0, count_1 = df.target.value_counts()df_class_0 = df[df[‘your_label’] == 0].sample(count_1)#under sample or df_class_1 = df_class_1.sample(count_0, replace=True)#over sample You could equally use NumPy or other libraries to sample your data like Imblearn. Also, there are many more ways to address this like SMOTE and Tomek links. An adversarial attack on an AI system can completely confuse the system. Image recognition systems, for example, were shown to have weaknesses or being vulnerable to adversarial attacks. Researchers have shown that even if an AI system is trained on thousands of images, a carefully placed pixel in an image can fundamentally alter the perception of it by the AI system, leading to a false prediction.[2] This might have a serious effect on real applications involving the identification of individuals. Imagine a security-camera footage scenario where the AI system misidentifies the offender because of this type of attack. Mitigation measure: We need to make our deep learning models more robust. Unfortunately, this issue is a tough one. It is currently being investigated at a research-level in top universities across the world. However, in theory, you should be able to test your model not just on an unseen test dataset but also emulate these sort of adversarial attacks to assess its robustness. Neurons in the deep learning model that are activated erroneously could potentially be dropped to improve robustness. This article from 2019 discusses such approaches. A common question in AI is how easy it is if at all, to replicate the results we obtained or, the models we generated. Many algorithms have stochastic elements when training their models. So, different training runs result in different models (assuming different random seed), and different models may have different prediction outcomes. How do we make sure that a prediction that concerns an individual won’t be reversed by the next model trained on the same data? Also, a system that is shown to perform well on our local machine with our data, may perform poorly when tested in the field. How do we make sure that the performance we initially had is propagated to the deployed application? How do we make sure that the system’s performance does not deteriorate over time, which will impact decisions taken about individuals? Mitigation measures: These are multiple related issues that require a number of approaches. To ensure consistency in your results, you should typically employ a cross-validation technique to make sure your results are not based on a lucky split of your train and test set. See this post for practical guidance. Also, for forecasting models, you could do a backward test and assess what the performance would have been if it was deployed at some point in the past given only train data up to that point. Also, it is a good idea to assess your model on a totally different dataset with similar input to check its generalisability outside of the given dataset it was trained on. Importantly though, when you deploy a model the real-world, the data should be expected to follow the same distributions as your training one. In any other case, the performance will drop unpredictably. Finally, it is always a good practice to monitor a deployed model and assess its performance on new data. In case of sudden drops or drifts in performance, it might be a sign that the model needs to be retrained. Of course, this will also depend on the specific application. Depending on the application you might have a re-training strategy in place to have a new model daily, weekly, quarterly, yearly and so on. Key questions when building AI systems should be “How do we evaluate the system?”. One of the most common metrics is accuracy. In other words, whatever your model predicted correctly over the total samples it was tested on. But is accuracy a good metric? Think about a problem where you have 100 women of which 10 are pregnant. Imagine you have some information about these women and, you try to build a model to predict who is pregnant and who is not. You do that and your model has an accuracy of 85%. Does this mean that you have a good model? On the other hand, let’s assume you have no model and what you rather do is predict all women being non-pregnant. Surprisingly, this has an accuracy of 90% as you will be correct 90 out of 100 times. Is that better than the actual model you created above? So, what metrics do we use and, how can we assess the performance of our models? Would you rely on just accuracy for decisions that affect individuals? Mitigation measures: The answer is obviously no. In fact, usually, the best approach is to compare multiple metrics and ideally examine the confusion matrix closely to understand the strengths and weaknesses of your model. So for the naive approach above that has 90% accuracy, F1-score would actually be 0 as there no True Positives (only True Negatives). On the contrary, your model of 85% accuracy could, in fact, has 67% F1-score, which might or might not be acceptable in specific applications. Other metrics to look for is the area under the curve (AUC) of a Receiver Operating Characteristic (ROC), Precision, Recall and Specificity, just to name a few. Relying on historic data to make predictions for the future does not always work. A great example is trying to predict the stock market. This is intrinsically difficult for a number of reasons. Using data that had for so long a certain outcome creates models that work within the boundaries of their history. This means that if you train a model in a period of no market crashes, there is no way that the model would be able to ever forecast a crash. Even if you trained it over periods of a market crash, it is still very unlikely for the model to learn when one would happen due to the rarity of the event and the lack of a clear signal pointing towards that direction. Now, think about models making decisions that impact individuals during the times of a global pandemic. Since all of the models have seen no similar data in the past, it is unlikely to make decisions about individuals as accurately as they did before the pandemic. Mitigation measures: In such situations, the models are likely to require re-training with data taken from the new situation, in order to operate within the new reality. This might work temporarily until perhaps the behaviour shifts again to the old standard. If re-training is not possible then decisions shouldn’t be taken automatically as they are likely to be wrong. This needs to be tested and validated though. All in all, predicting black swan events is not possible with the current assumptions that our models operate within. Making predictions and taking decisions about individuals, given that you know that the data you are predicting on do not follow the same distribution as the data you trained on would be irresponsible to do. That is not to say that the models cannot be useful as a consulting tool. Besides “all models are wrong, just some are useful” — George Box.
[ { "code": null, "e": 376, "s": 172, "text": "Privacy is a concern not only related to Artificial Intelligence (AI) but any data-related field in general. It is about people having control over their personal data and decisions taken based on those." }, { "code": null, "e": 997, "s": 376, "text": "In Europe, the General Data Protection Regulation (GDPR) that came into force in 2018 regulates the collection and use of personal data.[1] Data protection law does not refer explicitly to AI or Machine Learning but there is a significant focus on large-scale automated processing of personal data and automated decision-making. This means that where AI uses personal data it falls within the scope of the regulation and GDPR principles apply. This can be through the use of personal data to train, test or deploy an AI system. Failure to comply with the GDPR may result in enormous penalties for the companies involved." }, { "code": null, "e": 1102, "s": 997, "text": "Some examples of personal data would be the date of birth, postcode, gender or even a user’s IP address." }, { "code": null, "e": 1423, "s": 1102, "text": "Specifically, GDPR gives individuals the right not to be subject to a solely automated decision. The key question for AI experts then is: How can you show that you treated an individual fairly and in a transparent manner when making AI-assisted decision about them, or give them the opportunity to contest such decision?" }, { "code": null, "e": 1539, "s": 1423, "text": "Even though GDPR is most relevant to Europe and the UK, the main principles and ideas should be relevant worldwide." }, { "code": null, "e": 1730, "s": 1539, "text": "Although fairness and explainability of the models are active research topics in AI, there are at least 5 considerations that you could already be thinking about in relation to data privacy." }, { "code": null, "e": 2214, "s": 1730, "text": "Class imbalance occurs when your training labels are disproportionally in favour of a specific class. In other words, in a binary classification problem, you have lots of examples for cases where the output is 0 but only a few when the output is 1, or vice versa. This might be due to a bias in the data collection process e.g. data collected only from a local branch, or be inherent in the properties of the domain e.g., identifying anomalous data points in a manufacturing process." }, { "code": null, "e": 2641, "s": 2214, "text": "Class imbalance is one of the most common reasons for model bias, but it is often ignored by data scientists. This is because, typically, minor imbalance does not pose a huge risk as the models can learn the features of all classes equally well. However, when a severe class imbalance occurs, things can be tricky. Specifically, the minority class will be harder to predict, so your model is biased towards the majority class." }, { "code": null, "e": 3089, "s": 2641, "text": "For example, when you train an AI system to recognise images you could face a number of potential issues, class imbalance may be one of those. Think of a group of 100,000 images out of which only 100 are images of cats and 99,900 are images of dogs. The AI system you trained is more likely to predict a dog as it is trained to do so more frequently; it doesn’t have enough negative cases to accurately distinguish between the two types of images." }, { "code": null, "e": 3598, "s": 3089, "text": "This potential issue is not as innocent as wrongly classifying cats and dogs. Imagine you are training a model to accept or reject personal loans and most of the historic loans got rejected (for some reason). Guess what. Your model is likely to reject most or all of the future loan applications as it was more exposed to this sort of information and potentially didn’t learn to differentiate between the two cases. This is an issue from a data privacy perspective as the model does not produce fair results." }, { "code": null, "e": 3619, "s": 3598, "text": "Mitigation measures:" }, { "code": null, "e": 3826, "s": 3619, "text": "First of all, identifying whether this can be an issue early on is important. You can check that by understanding the volume of data points belonging to each of your classes: df[‘your_label’].value_counts()" }, { "code": null, "e": 4163, "s": 3826, "text": "If you do notice a class imbalance but you still run a simple model on your data anyway, you are likely to get good results in terms of accuracy. Your test data are likely to follow the same distribution as your train data and thus if most instances were mostly from 1 class, just always predicting that class gives good accuracy score." }, { "code": null, "e": 4502, "s": 4163, "text": "But don’t get fooled by that. Typically a confusion matrix will give you a better picture on what your model is actually doing. One of the main and easiest strategies to mitigate issues related to that is random resampling. You can either reduce your majority class to match the minority (under-sampling) or oversample the minority class." }, { "code": null, "e": 4515, "s": 4502, "text": "In practice," }, { "code": null, "e": 4626, "s": 4515, "text": "count_0, count_1 = df.target.value_counts()df_class_0 = df[df[‘your_label’] == 0].sample(count_1)#under sample" }, { "code": null, "e": 4629, "s": 4626, "text": "or" }, { "code": null, "e": 4695, "s": 4629, "text": "df_class_1 = df_class_1.sample(count_0, replace=True)#over sample" }, { "code": null, "e": 4852, "s": 4695, "text": "You could equally use NumPy or other libraries to sample your data like Imblearn. Also, there are many more ways to address this like SMOTE and Tomek links." }, { "code": null, "e": 5478, "s": 4852, "text": "An adversarial attack on an AI system can completely confuse the system. Image recognition systems, for example, were shown to have weaknesses or being vulnerable to adversarial attacks. Researchers have shown that even if an AI system is trained on thousands of images, a carefully placed pixel in an image can fundamentally alter the perception of it by the AI system, leading to a false prediction.[2] This might have a serious effect on real applications involving the identification of individuals. Imagine a security-camera footage scenario where the AI system misidentifies the offender because of this type of attack." }, { "code": null, "e": 5498, "s": 5478, "text": "Mitigation measure:" }, { "code": null, "e": 6025, "s": 5498, "text": "We need to make our deep learning models more robust. Unfortunately, this issue is a tough one. It is currently being investigated at a research-level in top universities across the world. However, in theory, you should be able to test your model not just on an unseen test dataset but also emulate these sort of adversarial attacks to assess its robustness. Neurons in the deep learning model that are activated erroneously could potentially be dropped to improve robustness. This article from 2019 discusses such approaches." }, { "code": null, "e": 6491, "s": 6025, "text": "A common question in AI is how easy it is if at all, to replicate the results we obtained or, the models we generated. Many algorithms have stochastic elements when training their models. So, different training runs result in different models (assuming different random seed), and different models may have different prediction outcomes. How do we make sure that a prediction that concerns an individual won’t be reversed by the next model trained on the same data?" }, { "code": null, "e": 6853, "s": 6491, "text": "Also, a system that is shown to perform well on our local machine with our data, may perform poorly when tested in the field. How do we make sure that the performance we initially had is propagated to the deployed application? How do we make sure that the system’s performance does not deteriorate over time, which will impact decisions taken about individuals?" }, { "code": null, "e": 6874, "s": 6853, "text": "Mitigation measures:" }, { "code": null, "e": 7164, "s": 6874, "text": "These are multiple related issues that require a number of approaches. To ensure consistency in your results, you should typically employ a cross-validation technique to make sure your results are not based on a lucky split of your train and test set. See this post for practical guidance." }, { "code": null, "e": 7356, "s": 7164, "text": "Also, for forecasting models, you could do a backward test and assess what the performance would have been if it was deployed at some point in the past given only train data up to that point." }, { "code": null, "e": 7732, "s": 7356, "text": "Also, it is a good idea to assess your model on a totally different dataset with similar input to check its generalisability outside of the given dataset it was trained on. Importantly though, when you deploy a model the real-world, the data should be expected to follow the same distributions as your training one. In any other case, the performance will drop unpredictably." }, { "code": null, "e": 8147, "s": 7732, "text": "Finally, it is always a good practice to monitor a deployed model and assess its performance on new data. In case of sudden drops or drifts in performance, it might be a sign that the model needs to be retrained. Of course, this will also depend on the specific application. Depending on the application you might have a re-training strategy in place to have a new model daily, weekly, quarterly, yearly and so on." }, { "code": null, "e": 9102, "s": 8147, "text": "Key questions when building AI systems should be “How do we evaluate the system?”. One of the most common metrics is accuracy. In other words, whatever your model predicted correctly over the total samples it was tested on. But is accuracy a good metric? Think about a problem where you have 100 women of which 10 are pregnant. Imagine you have some information about these women and, you try to build a model to predict who is pregnant and who is not. You do that and your model has an accuracy of 85%. Does this mean that you have a good model? On the other hand, let’s assume you have no model and what you rather do is predict all women being non-pregnant. Surprisingly, this has an accuracy of 90% as you will be correct 90 out of 100 times. Is that better than the actual model you created above? So, what metrics do we use and, how can we assess the performance of our models? Would you rely on just accuracy for decisions that affect individuals?" }, { "code": null, "e": 9123, "s": 9102, "text": "Mitigation measures:" }, { "code": null, "e": 9325, "s": 9123, "text": "The answer is obviously no. In fact, usually, the best approach is to compare multiple metrics and ideally examine the confusion matrix closely to understand the strengths and weaknesses of your model." }, { "code": null, "e": 9763, "s": 9325, "text": "So for the naive approach above that has 90% accuracy, F1-score would actually be 0 as there no True Positives (only True Negatives). On the contrary, your model of 85% accuracy could, in fact, has 67% F1-score, which might or might not be acceptable in specific applications. Other metrics to look for is the area under the curve (AUC) of a Receiver Operating Characteristic (ROC), Precision, Recall and Specificity, just to name a few." }, { "code": null, "e": 10700, "s": 9763, "text": "Relying on historic data to make predictions for the future does not always work. A great example is trying to predict the stock market. This is intrinsically difficult for a number of reasons. Using data that had for so long a certain outcome creates models that work within the boundaries of their history. This means that if you train a model in a period of no market crashes, there is no way that the model would be able to ever forecast a crash. Even if you trained it over periods of a market crash, it is still very unlikely for the model to learn when one would happen due to the rarity of the event and the lack of a clear signal pointing towards that direction. Now, think about models making decisions that impact individuals during the times of a global pandemic. Since all of the models have seen no similar data in the past, it is unlikely to make decisions about individuals as accurately as they did before the pandemic." }, { "code": null, "e": 10721, "s": 10700, "text": "Mitigation measures:" }, { "code": null, "e": 11117, "s": 10721, "text": "In such situations, the models are likely to require re-training with data taken from the new situation, in order to operate within the new reality. This might work temporarily until perhaps the behaviour shifts again to the old standard. If re-training is not possible then decisions shouldn’t be taken automatically as they are likely to be wrong. This needs to be tested and validated though." } ]
2-PCA vs 3-PCA. Does Having 3 Principal Components... | by Arun Prasad | Towards Data Science
Principal Component Analysis is used to reduce the number of dimensions (features) in a dataset. Say, we have 10 dimensions/features in our dataset. It's not a smart way to just drop 7–8 features based on an assumption (or a wild guess). One method to tackle this problem could be a feature selection technique (say, Chi-Squared). Feature Selection Techniques help us select the most important ‘k’ features corresponding to the target feature. But again, this will not be an overall representation of all the features (instead, it would be just a few features selected from ‘n’ number of features). To tackle this problem, we have the Principal Component Analysis (PCA) Dimensionality reduction technique. The principal components we shall have would be an overall representation of all the features in the dataset. In this way, information loss can be minimised. Now that we have understood the importance of PCA, we shall dive deeper to check if having 3 principal components and plotting them in a 3-Dimensional graph is more fruitful than having a 2 component PCA and a 2-Dimensional graph? To keep things simple, I am not showing the dataset I have used, instead directly showing the three principal components which I obtained by using the PCA technique (with n=3) on my dataset. The Principal Components are as follows Principal component 1 Principal component 2 Principal component 30 -0.593113 0.877027 1.7824261 -0.582788 0.926408 0.2358752 -0.593406 0.885406 1.0263933 -0.590781 0.913825 1.0575994 -0.557457 1.003013 0.7719945 -0.590091 0.892999 1.7547616 -0.532054 1.071892 0.6143117 -0.600141 0.873119 1.3740948 -0.604967 0.862305 1.6899379 -0.590725 0.910980 1.15160010 -0.571536 0.955599 1.26903511 -0.612102 0.921839 0.60181012 -0.638983 1.028594 -0.65870113 -0.538442 1.069557 -0.31585814 -0.545885 1.042621 -0.43917715 -0.213216 -1.068956 1.62484716 -0.585643 0.958585 0.56633817 -0.528046 1.081252 0.81483618 -0.586254 1.015987 0.56042719 -0.588309 0.893676 1.74815520 -0.545498 1.042484 0.04420721 -0.525951 1.099272 -0.23981522 -0.545391 1.036316 0.24982923 -0.553054 1.015097 1.36101524 -0.549921 1.043496 -0.02877225 -0.541706 1.044087 0.50017326 -0.580348 0.927584 0.69396127 -0.565069 0.983091 -0.06093128 -0.569777 0.958700 0.70642729 -0.572816 0.956895 0.263877... ... ... ...38991 4.154215 0.411276 2.07402338992 -0.405145 -0.943906 -0.97919938993 -0.294493 -0.724124 0.18259038994 0.946546 -0.426986 -2.31542738995 3.755563 0.385886 -2.34363838996 1.362237 -0.325860 0.13543638997 3.085934 0.127931 0.23375838998 5.803189 0.739613 -0.59875038999 4.126051 0.320192 -1.14289239000 5.285017 0.732141 -2.11322839001 4.235777 0.488489 -2.42217439002 5.337110 0.681343 -1.86533939003 2.046786 -0.255520 0.51248539004 6.575937 1.052580 0.41412839005 -0.549162 -0.773501 -0.45389939006 -0.489873 -0.747580 -2.54333239007 -0.403737 -0.943530 -0.97913339008 5.632072 0.761396 -1.41929839009 1.532861 -0.252514 -1.25933139010 0.283742 -0.684903 -0.72987839011 13.207580 2.725922 0.23752339012 -0.558653 -0.799741 -0.61854639013 -0.734531 -0.815442 0.75588239014 -0.563215 -0.746943 -1.34988139015 -0.600636 -0.858194 -1.31946439016 1.536320 -0.299190 -0.16450239017 -0.553627 -0.785324 -0.57675939018 -0.554424 -0.957772 -0.89779539019 -0.744299 -0.842957 0.63108839020 -0.558107 -0.957167 -1.901427 You can see that I have 39020 tuples. Let us also look at the variance ratios for the three Principal Components. The Variance Ratios are[0.24679625 0.16479195 0.15822251] Let us imagine that you are used to only 2-Component PCA and you haven’t got the 3rd Component in your analysis. Which now means in our scenario, you have only the first two principal components. Okay! Let us plot the first two principal components. Consider finding clusters within the dataset is our primary goal, then we can clearly see from the above plot (Figure 1) that there are no obvious clusters that are occurring. Which means, 2-Component PCA has now failed to fulfil our expectations here. Okay, can the Three-Component PCA fulfil it? Why doubt it, let us check it out by plotting all the three components now. But again I am not able to find any clusters as such in the plot. What we shall do now is try to rotate the plots along all the three axes and try to find some insight in them. Voila! From the above plots (Figure 3), I am able to come to the assertion that there are two possible clusters within my dataset. Suppose that my dataset is a survey of school students and primarily talks about them using laptops and mobile phones, then clearly I can see that there are two separate groups of students and we can now proceed to further analysis with this assertion that one large group of students and one small group of students are present in the dataset and the former or the later is more comfortable with either laptops or mobile phones. Okay, why could the Three-component PCA give us more insights than that of the Two-Component PCA? Check out the Variance Ratios which we had obtained. When considering only the first two components, the ratios add up to ~0.4 (40%). Meaning, the first two components together only represent 40% of the overall data. But when we add up all the three ratios, it is around ~0.55 (55%). A visibly higher percentage overall representation of the dataset features. To conclude, when the overall sum of the two variance ratios is extremely low and the plot doesn’t give us any insight, then using a 3rd Principal Component is mostly very fruitful. When even 3-PCA doesn’t give us insights then considering other Dimensionality reduction techniques is a better option. In one another analysis of mine, using only the very first principal component (0.99 variance ratio), meaningful insights could be obtained from the plot. (Link: https://towardsdatascience.com/an-insight-into-performing-fundamental-data-analysis-9c67c62e0766 ). Hence the variance ratios do play a very vital role in determining the number of principal components which we shall use for plotting. Thanks for your time! If you liked the story, do share it with your friends. You can follow me on LinkedIn. Thank you once again!
[ { "code": null, "e": 771, "s": 172, "text": "Principal Component Analysis is used to reduce the number of dimensions (features) in a dataset. Say, we have 10 dimensions/features in our dataset. It's not a smart way to just drop 7–8 features based on an assumption (or a wild guess). One method to tackle this problem could be a feature selection technique (say, Chi-Squared). Feature Selection Techniques help us select the most important ‘k’ features corresponding to the target feature. But again, this will not be an overall representation of all the features (instead, it would be just a few features selected from ‘n’ number of features)." }, { "code": null, "e": 1036, "s": 771, "text": "To tackle this problem, we have the Principal Component Analysis (PCA) Dimensionality reduction technique. The principal components we shall have would be an overall representation of all the features in the dataset. In this way, information loss can be minimised." }, { "code": null, "e": 1267, "s": 1036, "text": "Now that we have understood the importance of PCA, we shall dive deeper to check if having 3 principal components and plotting them in a 3-Dimensional graph is more fruitful than having a 2 component PCA and a 2-Dimensional graph?" }, { "code": null, "e": 1458, "s": 1267, "text": "To keep things simple, I am not showing the dataset I have used, instead directly showing the three principal components which I obtained by using the PCA technique (with n=3) on my dataset." }, { "code": null, "e": 6086, "s": 1458, "text": "The Principal Components are as follows Principal component 1 Principal component 2 Principal component 30 -0.593113 0.877027 1.7824261 -0.582788 0.926408 0.2358752 -0.593406 0.885406 1.0263933 -0.590781 0.913825 1.0575994 -0.557457 1.003013 0.7719945 -0.590091 0.892999 1.7547616 -0.532054 1.071892 0.6143117 -0.600141 0.873119 1.3740948 -0.604967 0.862305 1.6899379 -0.590725 0.910980 1.15160010 -0.571536 0.955599 1.26903511 -0.612102 0.921839 0.60181012 -0.638983 1.028594 -0.65870113 -0.538442 1.069557 -0.31585814 -0.545885 1.042621 -0.43917715 -0.213216 -1.068956 1.62484716 -0.585643 0.958585 0.56633817 -0.528046 1.081252 0.81483618 -0.586254 1.015987 0.56042719 -0.588309 0.893676 1.74815520 -0.545498 1.042484 0.04420721 -0.525951 1.099272 -0.23981522 -0.545391 1.036316 0.24982923 -0.553054 1.015097 1.36101524 -0.549921 1.043496 -0.02877225 -0.541706 1.044087 0.50017326 -0.580348 0.927584 0.69396127 -0.565069 0.983091 -0.06093128 -0.569777 0.958700 0.70642729 -0.572816 0.956895 0.263877... ... ... ...38991 4.154215 0.411276 2.07402338992 -0.405145 -0.943906 -0.97919938993 -0.294493 -0.724124 0.18259038994 0.946546 -0.426986 -2.31542738995 3.755563 0.385886 -2.34363838996 1.362237 -0.325860 0.13543638997 3.085934 0.127931 0.23375838998 5.803189 0.739613 -0.59875038999 4.126051 0.320192 -1.14289239000 5.285017 0.732141 -2.11322839001 4.235777 0.488489 -2.42217439002 5.337110 0.681343 -1.86533939003 2.046786 -0.255520 0.51248539004 6.575937 1.052580 0.41412839005 -0.549162 -0.773501 -0.45389939006 -0.489873 -0.747580 -2.54333239007 -0.403737 -0.943530 -0.97913339008 5.632072 0.761396 -1.41929839009 1.532861 -0.252514 -1.25933139010 0.283742 -0.684903 -0.72987839011 13.207580 2.725922 0.23752339012 -0.558653 -0.799741 -0.61854639013 -0.734531 -0.815442 0.75588239014 -0.563215 -0.746943 -1.34988139015 -0.600636 -0.858194 -1.31946439016 1.536320 -0.299190 -0.16450239017 -0.553627 -0.785324 -0.57675939018 -0.554424 -0.957772 -0.89779539019 -0.744299 -0.842957 0.63108839020 -0.558107 -0.957167 -1.901427" }, { "code": null, "e": 6200, "s": 6086, "text": "You can see that I have 39020 tuples. Let us also look at the variance ratios for the three Principal Components." }, { "code": null, "e": 6258, "s": 6200, "text": "The Variance Ratios are[0.24679625 0.16479195 0.15822251]" }, { "code": null, "e": 6508, "s": 6258, "text": "Let us imagine that you are used to only 2-Component PCA and you haven’t got the 3rd Component in your analysis. Which now means in our scenario, you have only the first two principal components. Okay! Let us plot the first two principal components." }, { "code": null, "e": 6761, "s": 6508, "text": "Consider finding clusters within the dataset is our primary goal, then we can clearly see from the above plot (Figure 1) that there are no obvious clusters that are occurring. Which means, 2-Component PCA has now failed to fulfil our expectations here." }, { "code": null, "e": 6882, "s": 6761, "text": "Okay, can the Three-Component PCA fulfil it? Why doubt it, let us check it out by plotting all the three components now." }, { "code": null, "e": 7059, "s": 6882, "text": "But again I am not able to find any clusters as such in the plot. What we shall do now is try to rotate the plots along all the three axes and try to find some insight in them." }, { "code": null, "e": 7620, "s": 7059, "text": "Voila! From the above plots (Figure 3), I am able to come to the assertion that there are two possible clusters within my dataset. Suppose that my dataset is a survey of school students and primarily talks about them using laptops and mobile phones, then clearly I can see that there are two separate groups of students and we can now proceed to further analysis with this assertion that one large group of students and one small group of students are present in the dataset and the former or the later is more comfortable with either laptops or mobile phones." }, { "code": null, "e": 8078, "s": 7620, "text": "Okay, why could the Three-component PCA give us more insights than that of the Two-Component PCA? Check out the Variance Ratios which we had obtained. When considering only the first two components, the ratios add up to ~0.4 (40%). Meaning, the first two components together only represent 40% of the overall data. But when we add up all the three ratios, it is around ~0.55 (55%). A visibly higher percentage overall representation of the dataset features." }, { "code": null, "e": 8777, "s": 8078, "text": "To conclude, when the overall sum of the two variance ratios is extremely low and the plot doesn’t give us any insight, then using a 3rd Principal Component is mostly very fruitful. When even 3-PCA doesn’t give us insights then considering other Dimensionality reduction techniques is a better option. In one another analysis of mine, using only the very first principal component (0.99 variance ratio), meaningful insights could be obtained from the plot. (Link: https://towardsdatascience.com/an-insight-into-performing-fundamental-data-analysis-9c67c62e0766 ). Hence the variance ratios do play a very vital role in determining the number of principal components which we shall use for plotting." }, { "code": null, "e": 8854, "s": 8777, "text": "Thanks for your time! If you liked the story, do share it with your friends." } ]
SQLite - VACUUM
VACUUM command cleans the main database by copying its contents to a temporary database file and reloading the original database file from the copy. This eliminates free pages, aligns table data to be contiguous, and otherwise cleans up the database file structure. VACUUM command may change the ROWID of entries in tables that do not have an explicit INTEGER PRIMARY KEY. The VACUUM command only works on the main database. It is not possible to VACUUM an attached database file. VACUUM command will fail if there is an active transaction. VACUUM command is a no-op for in-memory databases. As the VACUUM command rebuilds the database file from scratch, VACUUM can also be used to modify many database-specific configuration parameters. Following is a simple syntax to issue a VACUUM command for the whole database from command prompt − $sqlite3 database_name "VACUUM;" You can run VACUUM from SQLite prompt as well as follows − sqlite> VACUUM; You can also run VACUUM on a particular table as follows − sqlite> VACUUM table_name; SQLite Auto-VACUUM does not do the same as VACUUM rather it only moves free pages to the end of the database thereby reducing the database size. By doing so it can significantly fragment the database while VACUUM ensures defragmentation. Hence, Auto-VACUUM just keeps the database small. You can enable/disable SQLite auto-vacuuming by the following pragmas running at SQLite prompt − sqlite> PRAGMA auto_vacuum = NONE; -- 0 means disable auto vacuum sqlite> PRAGMA auto_vacuum = FULL; -- 1 means enable full auto vacuum sqlite> PRAGMA auto_vacuum = INCREMENTAL; -- 2 means enable incremental vacuum You can run the following command from the command prompt to check the auto-vacuum setting − $sqlite3 database_name "PRAGMA auto_vacuum;" 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2904, "s": 2638, "text": "VACUUM command cleans the main database by copying its contents to a temporary database file and reloading the original database file from the copy. This eliminates free pages, aligns table data to be contiguous, and otherwise cleans up the database file structure." }, { "code": null, "e": 3119, "s": 2904, "text": "VACUUM command may change the ROWID of entries in tables that do not have an explicit INTEGER PRIMARY KEY. The VACUUM command only works on the main database. It is not possible to VACUUM an attached database file." }, { "code": null, "e": 3376, "s": 3119, "text": "VACUUM command will fail if there is an active transaction. VACUUM command is a no-op for in-memory databases. As the VACUUM command rebuilds the database file from scratch, VACUUM can also be used to modify many database-specific configuration parameters." }, { "code": null, "e": 3476, "s": 3376, "text": "Following is a simple syntax to issue a VACUUM command for the whole database from command prompt −" }, { "code": null, "e": 3510, "s": 3476, "text": "$sqlite3 database_name \"VACUUM;\"\n" }, { "code": null, "e": 3569, "s": 3510, "text": "You can run VACUUM from SQLite prompt as well as follows −" }, { "code": null, "e": 3585, "s": 3569, "text": "sqlite> VACUUM;" }, { "code": null, "e": 3644, "s": 3585, "text": "You can also run VACUUM on a particular table as follows −" }, { "code": null, "e": 3671, "s": 3644, "text": "sqlite> VACUUM table_name;" }, { "code": null, "e": 3959, "s": 3671, "text": "SQLite Auto-VACUUM does not do the same as VACUUM rather it only moves free pages to the end of the database thereby reducing the database size. By doing so it can significantly fragment the database while VACUUM ensures defragmentation. Hence, Auto-VACUUM just keeps the database small." }, { "code": null, "e": 4056, "s": 3959, "text": "You can enable/disable SQLite auto-vacuuming by the following pragmas running at SQLite prompt −" }, { "code": null, "e": 4271, "s": 4056, "text": "sqlite> PRAGMA auto_vacuum = NONE; -- 0 means disable auto vacuum\nsqlite> PRAGMA auto_vacuum = FULL; -- 1 means enable full auto vacuum\nsqlite> PRAGMA auto_vacuum = INCREMENTAL; -- 2 means enable incremental vacuum" }, { "code": null, "e": 4364, "s": 4271, "text": "You can run the following command from the command prompt to check the auto-vacuum setting −" }, { "code": null, "e": 4410, "s": 4364, "text": "$sqlite3 database_name \"PRAGMA auto_vacuum;\"\n" }, { "code": null, "e": 4445, "s": 4410, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4466, "s": 4445, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4499, "s": 4466, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4516, "s": 4499, "text": " Laurence Svekis" }, { "code": null, "e": 4547, "s": 4516, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 4560, "s": 4547, "text": " Vinay Kumar" }, { "code": null, "e": 4567, "s": 4560, "text": " Print" }, { "code": null, "e": 4578, "s": 4567, "text": " Add Notes" } ]
Google Charts - Basic Column Chart
Following is an example of a basic column chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example. We've used BarChart class to show area based chart. //column chart var chart = new google.visualization.ColumnChart(document.getElementById('container')); googlecharts_column_basic.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['corechart']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> <script language = "JavaScript"> function drawChart() { // Define the chart to be drawn. var data = google.visualization.arrayToDataTable([ ['Year', 'Asia'], ['2012', 900], ['2013', 1000], ['2014', 1170], ['2015', 1250], ['2016', 1530] ]); var options = {title: 'Population (in millions)'}; // Instantiate and draw the chart. var chart = new google.visualization.ColumnChart(document.getElementById('container')); chart.draw(data, options); } google.charts.setOnLoadCallback(drawChart); </script> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2454, "s": 2261, "text": "Following is an example of a basic column chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example." }, { "code": null, "e": 2506, "s": 2454, "text": "We've used BarChart class to show area based chart." }, { "code": null, "e": 2610, "s": 2506, "text": "//column chart\nvar chart = new google.visualization.ColumnChart(document.getElementById('container'));\n" }, { "code": null, "e": 2640, "s": 2610, "text": "googlecharts_column_basic.htm" }, { "code": null, "e": 3792, "s": 2640, "text": "<html>\n <head>\n <title>Google Charts Tutorial</title>\n <script type = \"text/javascript\" src = \"https://www.gstatic.com/charts/loader.js\">\n </script>\n <script type = \"text/javascript\">\n google.charts.load('current', {packages: ['corechart']}); \n </script>\n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\">\n </div>\n <script language = \"JavaScript\">\n function drawChart() {\n // Define the chart to be drawn.\n var data = google.visualization.arrayToDataTable([\n ['Year', 'Asia'],\n ['2012', 900],\n ['2013', 1000],\n ['2014', 1170],\n ['2015', 1250],\n ['2016', 1530]\n ]);\n\n var options = {title: 'Population (in millions)'}; \n\n // Instantiate and draw the chart.\n var chart = new google.visualization.ColumnChart(document.getElementById('container'));\n chart.draw(data, options);\n }\n google.charts.setOnLoadCallback(drawChart);\n </script>\n </body>\n</html>" }, { "code": null, "e": 3811, "s": 3792, "text": "Verify the result." }, { "code": null, "e": 3818, "s": 3811, "text": " Print" }, { "code": null, "e": 3829, "s": 3818, "text": " Add Notes" } ]
The best Machine Learning algorithm for Email Classification | by Mahnoor Javed | Towards Data Science
Email Classification is a Machine Learning problem that falls under the category of Supervised Learning. This mini-project of Email Classification is inspired by J.K. Rowling’s publishing of a book under a pen-name. Udacity’s “Introduction to Machine Learning” provides a comprehensive study of the algorithms and the project. www.udacity.com A couple of years ago, Rowling wrote a book, “The Cuckoo’s Calling,” under the name Robert Galbraith. The book received some good reviews, but no one paid much attention to it — until an anonymous tipster on Twitter said it was J.K. Rowling. The London Sunday Times enlisted two experts to compare the linguistic patterns of “Cuckoo” to Rowling’s “The Casual Vacancy,” as well as to books by several other authors. After the results of their analysis pointed strongly toward Rowling as the author, the Times directly asked the publisher if they were the same person, and the publisher confirmed. The book exploded in popularity overnight. Email Classification works on the same basic concepts. By going through the text of the email, we will use Machine Learning algorithms to predict whether the email has been written by one person or the other. The dataset may be taken from the following GitHub repository: github.com In this dataset, we have a set of emails, half of which are written by one person (Sara) and the other half by another person (Chris) at the same company. The data is based on a list of strings. Each string is the text of an email, which has undergone some basic preprocessing. We will classify the emails as written by one person or the other based only on the text of the email. We will use the following algorithms one by one: Naïve Bayes, Support Vector Machine, Decision Trees, Random Forest, KNN, and AdaBoost Classifier. The repository has 2 pickle files: word_data and email_authors. The email_preprocess python file serves to process the data from the pickles files. It splits the data into train/test with 0.1 test data. Naïve Bayes methods are a set of supervised learning algorithms based on Bayes’ theorem and assuming conditional independence and equal contribution between every pair of features given the value of the class variable. Bayes’ Theorem is a simple mathematical formula used for calculating conditional probabilities. Gaussian Naïve Bayes is a type of Naïve Bayes where the likelihood of the features is assumed to be Gaussian. The continuous values associated with each feature are assumed to be distributed according to a Gaussian distribution. When plotted, it gives a bell-shaped curve which is symmetric about the mean of the feature values. We will use Gaussian Naïve Bayes Algorithm from the scikit-learn library to classify the emails among the 2 authors. Following is the python code which you may implement on any Python IDE, with the required libraries installed on your system. import sysfrom time import timesys.path.append("C:\\Users\\HP\\Desktop\\ML Code\\")from email_preprocess import preprocessimport numpy as np# using the Gaussian Bayes algorithm for classification of emails.# the algorithm is imported from the sklearn libraryfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import accuracy_score# initializaing the test and train features and labels# the function preprocess is imported from email_preprocess.py features_train, features_test, labels_train, labels_test = preprocess()# defining the classifierclf = GaussianNB()#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print("\nTraining time:", round(time()-t0, 3), "s\n")t1 = time()pred = clf.predict(features_test)print("Predicting time:", round(time()-t1, 3), "s\n")#calculating and printing the accuracy of the algorithmprint("Accuracy of Naive Bayes: ", accuracy_score(pred,labels_test)) Running the code gives us the following results: The accuracy of Naïve Bayes for this particular problem in 0.9203. Pretty good right? Even the training and predicting times of the algorithm are quite reasonable. Support Vector Machines is also a type of Supervised Learning used for classification, regression as well as outlier detection. We can use the SVM algorithm to classify data points into 2 classes, through a plane that separates them. SVM has a straight decision boundary. The SVM algorithm is quite versatile, different Kernel functions can be specified for the decision function. SVM algorithm is based on the hyperplane that separates the two classes, the greater the margin, the better the classification (also called margin maximization). Our classifier is the C-Support Vector Classification with linear kernel and value of C = 1 clf = SVC(kernel = ‘linear’, C=1) import sysfrom time import timesys.path.append("C:\\Users\\HP\\Desktop\\ML Code\\")from email_preprocess import preprocessfrom sklearn.svm import SVCfrom sklearn.metrics import accuracy_score### features_train and features_test are the features for the training### and testing datasets, respectively### labels_train and labels_test are the corresponding item labelsfeatures_train, features_test, labels_train, labels_test = preprocess()#defining the classifierclf = SVC(kernel = 'linear', C=1)#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print("\nTraining time:", round(time()-t0, 3), "s\n")t1 = time()pred = clf.predict(features_test)print("Predicting time:", round(time()-t1, 3), "s\n")#calculating and printing the accuracy of the algorithmprint("Accuracy of SVM Algorithm: ", clf.score(features_test, labels_test)) The accuracy of the SVM algorithm is 0.9596. We can see a visible tradeoff between the accuracy and the training time. An increase in the accuracy of the algorithm is a result of the longer training time (22.7s as compared to 0.13s in the case of Naïve Bayes). We can play with the training data as well as the kernels to come to an optimum selection which would yield a good accuracy score with less training time! We will first slice the training dataset down to 1% of its original size tossing out 99% of the training data. With the rest of the code unchanged, we can observe a significant reduction in the training time and a consequent reduction in accuracy. The tradeoff is that the accuracy almost always goes down when we slice down the training data. Use the following code to slice the training data to 1%: features_train = features_train[:len(features_train)//100]labels_train = labels_train[:len(labels_train)//100] As can be seen, with 1% training data, the training time of the algorithm has been reduced to 0.01s with reduced accuracy of 0.9055. With 10% Training Data, the accuracy is 0.9550 with training time 0.47s. We may also change the kernels and the value of C in the scikit-learn’s C-Support Vector Classification. With 100% Training Data, RBF kernel, and the value of C set to 10000, we get an accuracy of 0.9891 with a training time of 14.718. Decision Trees are a non-parametric supervised learning method used for classification and regression. Decision Trees can perform multi-class classification on a dataset. Data is classified stepwise on each node using some decision rules inferred from the data features. Decision Trees are easy to visualize. We may understand the algorithm by visualizing a dataset run through the tree, with a decision to be made at the various nodes. Let’s see how this algorithm works on our dataset. import sysfrom time import timesys.path.append("C:\\Users\\HP\\Desktop\\ML Code\\")from email_preprocess import preprocessfrom sklearn import treefrom sklearn.metrics import accuracy_score### features_train and features_test are the features for the training### and testing datasets, respectively### labels_train and labels_test are the corresponding item labelsfeatures_train, features_test, labels_train, labels_test = preprocess()# defining the classifierclf = tree.DecisionTreeClassifier()print("\nLength of Features Train", len(features_train[0]))#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print("\nTraining time:", round(time()-t0, 3), "s\n")t1 = time()pred = clf.predict(features_test)print("Predicting time:", round(time()-t1, 3), "s\n")#calculating and printing the accuracy of the algorithmprint("Accuracy of Decision Trees Algorithm: ", accuracy_score(pred,labels_test)) Running the code above gives us an accuracy of 0.9880 and a training time of 6.116s. That is a very good accuracy score, isn't it? We have 100% of the training data taken for training the model. Random forests are an ensemble Supervised Learning algorithm built on Decision trees. Random Forests are used for regression and classification tasks. The algorithm takes its name from the random selection of features. We can use the Random Forests algorithm from the sklearn library on our dataset: RandomForestClassifier(). The following is the code used for running the random forest algorithm on our email classification problem. import sysfrom time import timesys.path.append("C:\\Users\\HP\\Desktop\\ML Code\\")from email_preprocess import preprocessfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_score### features_train and features_test are the features for the training### and testing datasets, respectively### labels_train and labels_test are the corresponding item labelsfeatures_train, features_test, labels_train, labels_test = preprocess()# defining the classifierclf = RandomForestClassifier(max_depth=2, random_state=0)#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print("\nTraining time:", round(time()-t0, 3), "s\n")t1 = time()pred = clf.predict(features_test)print("Predicting time:", round(time()-t1, 3), "s\n")#calculating and printing the accuracy of the algorithmprint("Accuracy of Random Forest Algorithm: ", accuracy_score(pred,labels_test)) The accuracy of the algorithm is quite low, ie; 0.7707. The training time is 1.2s, which is reasonable but overall, it doesn't prove to be a good tool for our problem. The reason for the low accuracy is the randomness of feature selection, which is a property of random forests. The random forest is a model made up of many decision trees. Rather than just simply averaging the prediction of trees (which we could call a “forest”), this model uses two key concepts that give it the name random: Random sampling of training data points when building trees. K Nearest Neighbor is a Supervised Machine Learning algorithm that may be used for both classification and regression predictive problems. KNN is a lazy learner. It relies on distance for classification, so normalizing the training data can improve its accuracy dramatically. Let us see the results of classifying emails using the KNN algorithm from sklearn library KNeighborsClassifier() with 5 nearest neighbors and the Euclidean metric. import sysfrom time import timesys.path.append("C:\\Users\\HP\\Desktop\\ML Code\\")from email_preprocess import preprocessfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.metrics import accuracy_score### features_train and features_test are the features for the training### and testing datasets, respectively### labels_train and labels_test are the corresponding item labelsfeatures_train, features_test, labels_train, labels_test = preprocess()# defining the classifierclf = KNeighborsClassifier(n_neighbors=5, metric='euclidean')#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print("\nTraining time:", round(time()-t0, 3), "s\n")t1 = time()pred = clf.predict(features_test)print("Predicting time:", round(time()-t1, 3), "s\n")#calculating and printing the accuracy of the algorithmprint("Accuracy of KNN Algorithm: ", accuracy_score(pred,labels_test)) The accuracy of the algorithm is 0.9379 with a training time of 2.883s. However, it may be noticed that the model tool a considerably longer time to predict the classes. Ada-boost or Adaptive Boosting is also an ensemble boosting classifier. It is a meta-estimator that begins by fitting a classifier on the original dataset and then fits additional copies of the classifier on the same dataset but where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases. We will use the classifier from the scikit library. Following is the code: import sysfrom time import timesys.path.append("C:\\Users\\HP\\Desktop\\ML Code\\")from email_preprocess import preprocessfrom sklearn.ensemble import AdaBoostClassifierfrom sklearn.metrics import accuracy_score### features_train and features_test are the features for the training### and testing datasets, respectively### labels_train and labels_test are the corresponding item labelsfeatures_train, features_test, labels_train, labels_test = preprocess()# defining the classifierclf = AdaBoostClassifier(n_estimators=100, random_state=0)#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print("\nTraining time:", round(time()-t0, 3), "s\n")t1 = time()pred = clf.predict(features_test)print("Predicting time:", round(time()-t1, 3), "s\n")#calculating and printing the accuracy of the algorithmprint("Accuracy of Ada Boost Classifier: ", accuracy_score(pred,labels_test)) The accuracy of the classifier has come out to be 0.9653 with a training time of 17.946s. The accuracy is quite good, however, the training time is a bit longer than what is required. Throughout this article, we have used several Machine Learning algorithms to classify emails between Chris and Sara. The algorithms resulted in different accuracy scores between the range of 0.77–0.98. As can be seen from the table below, where the models are arranged by increasing accuracy: the Random Forests algorithm had the lowest accuracy score SVM algorithm had the longest training time the SVM algorithm with optimized parameters of C=10000 and RBF kernel had the highest accuracy score Naive Bayes algorithm had the quickest predicting time Although there are many other classification algorithms that may be used for our task here, a comparison of the basic algorithms run on the dataset concludes that for our particular problem, SVM is the most accurate, considering its parameters are optimized according to the task we are dealing with. Do you think other algorithms or models would do the job better, or maybe equally well? Share your experience and follow me for more articles!
[ { "code": null, "e": 277, "s": 172, "text": "Email Classification is a Machine Learning problem that falls under the category of Supervised Learning." }, { "code": null, "e": 499, "s": 277, "text": "This mini-project of Email Classification is inspired by J.K. Rowling’s publishing of a book under a pen-name. Udacity’s “Introduction to Machine Learning” provides a comprehensive study of the algorithms and the project." }, { "code": null, "e": 515, "s": 499, "text": "www.udacity.com" }, { "code": null, "e": 1154, "s": 515, "text": "A couple of years ago, Rowling wrote a book, “The Cuckoo’s Calling,” under the name Robert Galbraith. The book received some good reviews, but no one paid much attention to it — until an anonymous tipster on Twitter said it was J.K. Rowling. The London Sunday Times enlisted two experts to compare the linguistic patterns of “Cuckoo” to Rowling’s “The Casual Vacancy,” as well as to books by several other authors. After the results of their analysis pointed strongly toward Rowling as the author, the Times directly asked the publisher if they were the same person, and the publisher confirmed. The book exploded in popularity overnight." }, { "code": null, "e": 1363, "s": 1154, "text": "Email Classification works on the same basic concepts. By going through the text of the email, we will use Machine Learning algorithms to predict whether the email has been written by one person or the other." }, { "code": null, "e": 1426, "s": 1363, "text": "The dataset may be taken from the following GitHub repository:" }, { "code": null, "e": 1437, "s": 1426, "text": "github.com" }, { "code": null, "e": 1715, "s": 1437, "text": "In this dataset, we have a set of emails, half of which are written by one person (Sara) and the other half by another person (Chris) at the same company. The data is based on a list of strings. Each string is the text of an email, which has undergone some basic preprocessing." }, { "code": null, "e": 1966, "s": 1715, "text": "We will classify the emails as written by one person or the other based only on the text of the email. We will use the following algorithms one by one: Naïve Bayes, Support Vector Machine, Decision Trees, Random Forest, KNN, and AdaBoost Classifier." }, { "code": null, "e": 2030, "s": 1966, "text": "The repository has 2 pickle files: word_data and email_authors." }, { "code": null, "e": 2169, "s": 2030, "text": "The email_preprocess python file serves to process the data from the pickles files. It splits the data into train/test with 0.1 test data." }, { "code": null, "e": 2485, "s": 2169, "text": "Naïve Bayes methods are a set of supervised learning algorithms based on Bayes’ theorem and assuming conditional independence and equal contribution between every pair of features given the value of the class variable. Bayes’ Theorem is a simple mathematical formula used for calculating conditional probabilities." }, { "code": null, "e": 2816, "s": 2485, "text": "Gaussian Naïve Bayes is a type of Naïve Bayes where the likelihood of the features is assumed to be Gaussian. The continuous values associated with each feature are assumed to be distributed according to a Gaussian distribution. When plotted, it gives a bell-shaped curve which is symmetric about the mean of the feature values." }, { "code": null, "e": 2934, "s": 2816, "text": "We will use Gaussian Naïve Bayes Algorithm from the scikit-learn library to classify the emails among the 2 authors." }, { "code": null, "e": 3060, "s": 2934, "text": "Following is the python code which you may implement on any Python IDE, with the required libraries installed on your system." }, { "code": null, "e": 3996, "s": 3060, "text": "import sysfrom time import timesys.path.append(\"C:\\\\Users\\\\HP\\\\Desktop\\\\ML Code\\\\\")from email_preprocess import preprocessimport numpy as np# using the Gaussian Bayes algorithm for classification of emails.# the algorithm is imported from the sklearn libraryfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import accuracy_score# initializaing the test and train features and labels# the function preprocess is imported from email_preprocess.py features_train, features_test, labels_train, labels_test = preprocess()# defining the classifierclf = GaussianNB()#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print(\"\\nTraining time:\", round(time()-t0, 3), \"s\\n\")t1 = time()pred = clf.predict(features_test)print(\"Predicting time:\", round(time()-t1, 3), \"s\\n\")#calculating and printing the accuracy of the algorithmprint(\"Accuracy of Naive Bayes: \", accuracy_score(pred,labels_test))" }, { "code": null, "e": 4045, "s": 3996, "text": "Running the code gives us the following results:" }, { "code": null, "e": 4210, "s": 4045, "text": "The accuracy of Naïve Bayes for this particular problem in 0.9203. Pretty good right? Even the training and predicting times of the algorithm are quite reasonable." }, { "code": null, "e": 4591, "s": 4210, "text": "Support Vector Machines is also a type of Supervised Learning used for classification, regression as well as outlier detection. We can use the SVM algorithm to classify data points into 2 classes, through a plane that separates them. SVM has a straight decision boundary. The SVM algorithm is quite versatile, different Kernel functions can be specified for the decision function." }, { "code": null, "e": 4753, "s": 4591, "text": "SVM algorithm is based on the hyperplane that separates the two classes, the greater the margin, the better the classification (also called margin maximization)." }, { "code": null, "e": 4845, "s": 4753, "text": "Our classifier is the C-Support Vector Classification with linear kernel and value of C = 1" }, { "code": null, "e": 4879, "s": 4845, "text": "clf = SVC(kernel = ‘linear’, C=1)" }, { "code": null, "e": 5742, "s": 4879, "text": "import sysfrom time import timesys.path.append(\"C:\\\\Users\\\\HP\\\\Desktop\\\\ML Code\\\\\")from email_preprocess import preprocessfrom sklearn.svm import SVCfrom sklearn.metrics import accuracy_score### features_train and features_test are the features for the training### and testing datasets, respectively### labels_train and labels_test are the corresponding item labelsfeatures_train, features_test, labels_train, labels_test = preprocess()#defining the classifierclf = SVC(kernel = 'linear', C=1)#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print(\"\\nTraining time:\", round(time()-t0, 3), \"s\\n\")t1 = time()pred = clf.predict(features_test)print(\"Predicting time:\", round(time()-t1, 3), \"s\\n\")#calculating and printing the accuracy of the algorithmprint(\"Accuracy of SVM Algorithm: \", clf.score(features_test, labels_test))" }, { "code": null, "e": 6159, "s": 5742, "text": "The accuracy of the SVM algorithm is 0.9596. We can see a visible tradeoff between the accuracy and the training time. An increase in the accuracy of the algorithm is a result of the longer training time (22.7s as compared to 0.13s in the case of Naïve Bayes). We can play with the training data as well as the kernels to come to an optimum selection which would yield a good accuracy score with less training time!" }, { "code": null, "e": 6503, "s": 6159, "text": "We will first slice the training dataset down to 1% of its original size tossing out 99% of the training data. With the rest of the code unchanged, we can observe a significant reduction in the training time and a consequent reduction in accuracy. The tradeoff is that the accuracy almost always goes down when we slice down the training data." }, { "code": null, "e": 6560, "s": 6503, "text": "Use the following code to slice the training data to 1%:" }, { "code": null, "e": 6671, "s": 6560, "text": "features_train = features_train[:len(features_train)//100]labels_train = labels_train[:len(labels_train)//100]" }, { "code": null, "e": 6804, "s": 6671, "text": "As can be seen, with 1% training data, the training time of the algorithm has been reduced to 0.01s with reduced accuracy of 0.9055." }, { "code": null, "e": 6877, "s": 6804, "text": "With 10% Training Data, the accuracy is 0.9550 with training time 0.47s." }, { "code": null, "e": 6982, "s": 6877, "text": "We may also change the kernels and the value of C in the scikit-learn’s C-Support Vector Classification." }, { "code": null, "e": 7113, "s": 6982, "text": "With 100% Training Data, RBF kernel, and the value of C set to 10000, we get an accuracy of 0.9891 with a training time of 14.718." }, { "code": null, "e": 7550, "s": 7113, "text": "Decision Trees are a non-parametric supervised learning method used for classification and regression. Decision Trees can perform multi-class classification on a dataset. Data is classified stepwise on each node using some decision rules inferred from the data features. Decision Trees are easy to visualize. We may understand the algorithm by visualizing a dataset run through the tree, with a decision to be made at the various nodes." }, { "code": null, "e": 7601, "s": 7550, "text": "Let’s see how this algorithm works on our dataset." }, { "code": null, "e": 8529, "s": 7601, "text": "import sysfrom time import timesys.path.append(\"C:\\\\Users\\\\HP\\\\Desktop\\\\ML Code\\\\\")from email_preprocess import preprocessfrom sklearn import treefrom sklearn.metrics import accuracy_score### features_train and features_test are the features for the training### and testing datasets, respectively### labels_train and labels_test are the corresponding item labelsfeatures_train, features_test, labels_train, labels_test = preprocess()# defining the classifierclf = tree.DecisionTreeClassifier()print(\"\\nLength of Features Train\", len(features_train[0]))#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print(\"\\nTraining time:\", round(time()-t0, 3), \"s\\n\")t1 = time()pred = clf.predict(features_test)print(\"Predicting time:\", round(time()-t1, 3), \"s\\n\")#calculating and printing the accuracy of the algorithmprint(\"Accuracy of Decision Trees Algorithm: \", accuracy_score(pred,labels_test))" }, { "code": null, "e": 8724, "s": 8529, "text": "Running the code above gives us an accuracy of 0.9880 and a training time of 6.116s. That is a very good accuracy score, isn't it? We have 100% of the training data taken for training the model." }, { "code": null, "e": 8943, "s": 8724, "text": "Random forests are an ensemble Supervised Learning algorithm built on Decision trees. Random Forests are used for regression and classification tasks. The algorithm takes its name from the random selection of features." }, { "code": null, "e": 9050, "s": 8943, "text": "We can use the Random Forests algorithm from the sklearn library on our dataset: RandomForestClassifier()." }, { "code": null, "e": 9158, "s": 9050, "text": "The following is the code used for running the random forest algorithm on our email classification problem." }, { "code": null, "e": 10075, "s": 9158, "text": "import sysfrom time import timesys.path.append(\"C:\\\\Users\\\\HP\\\\Desktop\\\\ML Code\\\\\")from email_preprocess import preprocessfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_score### features_train and features_test are the features for the training### and testing datasets, respectively### labels_train and labels_test are the corresponding item labelsfeatures_train, features_test, labels_train, labels_test = preprocess()# defining the classifierclf = RandomForestClassifier(max_depth=2, random_state=0)#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print(\"\\nTraining time:\", round(time()-t0, 3), \"s\\n\")t1 = time()pred = clf.predict(features_test)print(\"Predicting time:\", round(time()-t1, 3), \"s\\n\")#calculating and printing the accuracy of the algorithmprint(\"Accuracy of Random Forest Algorithm: \", accuracy_score(pred,labels_test))" }, { "code": null, "e": 10631, "s": 10075, "text": "The accuracy of the algorithm is quite low, ie; 0.7707. The training time is 1.2s, which is reasonable but overall, it doesn't prove to be a good tool for our problem. The reason for the low accuracy is the randomness of feature selection, which is a property of random forests. The random forest is a model made up of many decision trees. Rather than just simply averaging the prediction of trees (which we could call a “forest”), this model uses two key concepts that give it the name random: Random sampling of training data points when building trees." }, { "code": null, "e": 10907, "s": 10631, "text": "K Nearest Neighbor is a Supervised Machine Learning algorithm that may be used for both classification and regression predictive problems. KNN is a lazy learner. It relies on distance for classification, so normalizing the training data can improve its accuracy dramatically." }, { "code": null, "e": 11071, "s": 10907, "text": "Let us see the results of classifying emails using the KNN algorithm from sklearn library KNeighborsClassifier() with 5 nearest neighbors and the Euclidean metric." }, { "code": null, "e": 11981, "s": 11071, "text": "import sysfrom time import timesys.path.append(\"C:\\\\Users\\\\HP\\\\Desktop\\\\ML Code\\\\\")from email_preprocess import preprocessfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.metrics import accuracy_score### features_train and features_test are the features for the training### and testing datasets, respectively### labels_train and labels_test are the corresponding item labelsfeatures_train, features_test, labels_train, labels_test = preprocess()# defining the classifierclf = KNeighborsClassifier(n_neighbors=5, metric='euclidean')#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print(\"\\nTraining time:\", round(time()-t0, 3), \"s\\n\")t1 = time()pred = clf.predict(features_test)print(\"Predicting time:\", round(time()-t1, 3), \"s\\n\")#calculating and printing the accuracy of the algorithmprint(\"Accuracy of KNN Algorithm: \", accuracy_score(pred,labels_test))" }, { "code": null, "e": 12151, "s": 11981, "text": "The accuracy of the algorithm is 0.9379 with a training time of 2.883s. However, it may be noticed that the model tool a considerably longer time to predict the classes." }, { "code": null, "e": 12511, "s": 12151, "text": "Ada-boost or Adaptive Boosting is also an ensemble boosting classifier. It is a meta-estimator that begins by fitting a classifier on the original dataset and then fits additional copies of the classifier on the same dataset but where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases." }, { "code": null, "e": 12586, "s": 12511, "text": "We will use the classifier from the scikit library. Following is the code:" }, { "code": null, "e": 13497, "s": 12586, "text": "import sysfrom time import timesys.path.append(\"C:\\\\Users\\\\HP\\\\Desktop\\\\ML Code\\\\\")from email_preprocess import preprocessfrom sklearn.ensemble import AdaBoostClassifierfrom sklearn.metrics import accuracy_score### features_train and features_test are the features for the training### and testing datasets, respectively### labels_train and labels_test are the corresponding item labelsfeatures_train, features_test, labels_train, labels_test = preprocess()# defining the classifierclf = AdaBoostClassifier(n_estimators=100, random_state=0)#predicting the time of train and testingt0 = time()clf.fit(features_train, labels_train)print(\"\\nTraining time:\", round(time()-t0, 3), \"s\\n\")t1 = time()pred = clf.predict(features_test)print(\"Predicting time:\", round(time()-t1, 3), \"s\\n\")#calculating and printing the accuracy of the algorithmprint(\"Accuracy of Ada Boost Classifier: \", accuracy_score(pred,labels_test))" }, { "code": null, "e": 13681, "s": 13497, "text": "The accuracy of the classifier has come out to be 0.9653 with a training time of 17.946s. The accuracy is quite good, however, the training time is a bit longer than what is required." }, { "code": null, "e": 13974, "s": 13681, "text": "Throughout this article, we have used several Machine Learning algorithms to classify emails between Chris and Sara. The algorithms resulted in different accuracy scores between the range of 0.77–0.98. As can be seen from the table below, where the models are arranged by increasing accuracy:" }, { "code": null, "e": 14033, "s": 13974, "text": "the Random Forests algorithm had the lowest accuracy score" }, { "code": null, "e": 14077, "s": 14033, "text": "SVM algorithm had the longest training time" }, { "code": null, "e": 14178, "s": 14077, "text": "the SVM algorithm with optimized parameters of C=10000 and RBF kernel had the highest accuracy score" }, { "code": null, "e": 14233, "s": 14178, "text": "Naive Bayes algorithm had the quickest predicting time" }, { "code": null, "e": 14534, "s": 14233, "text": "Although there are many other classification algorithms that may be used for our task here, a comparison of the basic algorithms run on the dataset concludes that for our particular problem, SVM is the most accurate, considering its parameters are optimized according to the task we are dealing with." }, { "code": null, "e": 14622, "s": 14534, "text": "Do you think other algorithms or models would do the job better, or maybe equally well?" } ]
How do I print and have user input in a text box in Tkinter?
We can use the Tkinter text widget to insert text, display information, and get the output from the text widget. To get the user input in a text widget, we've to use the get() method. Let's take an example to see how it works. # Import the required library from tkinter import * from tkinter import ttk # Create an instance of tkinter frame win=Tk() # Set the geometry win.geometry("700x350") def get_input(): label.config(text=""+text.get(1.0, "end-1c")) # Add a text widget text=Text(win, width=80, height=15) text.insert(END, "") text.pack() # Create a button to get the text input b=ttk.Button(win, text="Print", command=get_input) b.pack() # Create a Label widget label=Label(win, text="", font=('Calibri 15')) label.pack() win.mainloop() Running the above code will display a window containing a text widget. Type something in the text widget and click the "Print" button to display the output.
[ { "code": null, "e": 1289, "s": 1062, "text": "We can use the Tkinter text widget to insert text, display information, and get the output from the text widget. To get the user input in a text widget, we've to use the get() method. Let's take an example to see how it works." }, { "code": null, "e": 1816, "s": 1289, "text": "# Import the required library\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin=Tk()\n\n# Set the geometry\nwin.geometry(\"700x350\")\n\ndef get_input():\n label.config(text=\"\"+text.get(1.0, \"end-1c\"))\n\n# Add a text widget\ntext=Text(win, width=80, height=15)\ntext.insert(END, \"\")\ntext.pack()\n\n# Create a button to get the text input\nb=ttk.Button(win, text=\"Print\", command=get_input)\nb.pack()\n\n# Create a Label widget\nlabel=Label(win, text=\"\", font=('Calibri 15'))\nlabel.pack()\n\nwin.mainloop()" }, { "code": null, "e": 1973, "s": 1816, "text": "Running the above code will display a window containing a text widget. Type something in the text widget and click the \"Print\" button to display the output." } ]
How to import a SVG file in JavaScript ? - GeeksforGeeks
05 Feb, 2021 In this article, we are going to see and use different ways of using SVGs ( Scalable Vector Graphics). Method 1: The quickest way using HTML <img> element. Syntax: <img src='logo.svg' alt="some file" height='100' width='100' style="color:green;"/> Embedding an SVG through the <img> element, you need: src attribute height attribute (if your SVG has no inherent aspect ratio) width attribute (if your SVG has no inherent aspect ratio) Pros: Easy and quick implementation. Make the SVG image into a hyperlink by nesting <img> & <a> HTML element Caching of SVG file, hence reduced loading time. Cons: Manipulation of SVG file cannot be done. You can only use inline CSS to style your SVG. Cannot use CSS pseudo-classes to style the SVG. Example: HTML <!DOCTYPE html> <html lang="en"> <body> <img src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210205161739/Screenshot-2021-02-05-161721.png" alt="gfg-logo" height="100" width="100" style="background-color: green" /> </body> </html> Output : SVG file using HTML <img> element Method 2: Using SVG as an <object> Syntax: <object type="image/svg+xml" data="logo.svg" class="logo"> Logo </object> Embedding a SVG via a <object> element requires: type attribute data attribute class attribute ( if using external/internal CSS ) Pros : You can use external/internal CSS to style SVG. Easy and quick implementation. Will work great with caching. Cons : To use an external stylesheet, you need to use an <style> element inside the SVG file. Not so familiar with syntax and implementation. HTML code: HTML <!DOCTYPE html> <html lang="en"> <body> <object type="image/svg+xml" data= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210205161739/Screenshot-2021-02-05-161721.png" class="logo"> GFG Logo </object> </body> </html> CSS code:The following is the content for the “styles.css” file used in the above code. .logo { height: 100; width: 100; } Output : SVG file using HTML <object> element Method : Embedding an SVG with an <iframe> Syntax : <iframe src="logo.svg" width="500" height="500"> </iframe> Embedding a SVG via <iframe> element requires src attribute height attribute (if your SVG has no inherent aspect ratio) width attribute (if your SVG has no inherent aspect ratio) Pros : Quick and easy implementation. Same as <object> element. Cons : You can’t use JavaScript to manipulate the SVG. Caching is not great. HTML code : HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="styles.css" /> </head> <body> <iframe src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210205161739/Screenshot-2021-02-05-161721.png" width="150" height="150"> </iframe> </body> </html> Output : JavaScript-Questions Picked Technical Scripter 2020 JavaScript Technical Scripter 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 Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24981, "s": 24950, "text": " \n05 Feb, 2021\n" }, { "code": null, "e": 25084, "s": 24981, "text": "In this article, we are going to see and use different ways of using SVGs ( Scalable Vector Graphics)." }, { "code": null, "e": 25137, "s": 25084, "text": "Method 1: The quickest way using HTML <img> element." }, { "code": null, "e": 25146, "s": 25137, "text": "Syntax: " }, { "code": null, "e": 25232, "s": 25146, "text": " <img src='logo.svg' alt=\"some file\" height='100'\nwidth='100' style=\"color:green;\"/>" }, { "code": null, "e": 25286, "s": 25232, "text": "Embedding an SVG through the <img> element, you need:" }, { "code": null, "e": 25300, "s": 25286, "text": "src attribute" }, { "code": null, "e": 25360, "s": 25300, "text": "height attribute (if your SVG has no inherent aspect ratio)" }, { "code": null, "e": 25420, "s": 25360, "text": "width attribute (if your SVG has no inherent aspect ratio)" }, { "code": null, "e": 25426, "s": 25420, "text": "Pros:" }, { "code": null, "e": 25457, "s": 25426, "text": "Easy and quick implementation." }, { "code": null, "e": 25529, "s": 25457, "text": "Make the SVG image into a hyperlink by nesting <img> & <a> HTML element" }, { "code": null, "e": 25578, "s": 25529, "text": "Caching of SVG file, hence reduced loading time." }, { "code": null, "e": 25584, "s": 25578, "text": "Cons:" }, { "code": null, "e": 25625, "s": 25584, "text": "Manipulation of SVG file cannot be done." }, { "code": null, "e": 25672, "s": 25625, "text": "You can only use inline CSS to style your SVG." }, { "code": null, "e": 25720, "s": 25672, "text": "Cannot use CSS pseudo-classes to style the SVG." }, { "code": null, "e": 25729, "s": 25720, "text": "Example:" }, { "code": null, "e": 25734, "s": 25729, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html lang=\"en\"> \n <body> \n <img\n src= \n\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210205161739/Screenshot-2021-02-05-161721.png\"\n alt=\"gfg-logo\"\n height=\"100\"\n width=\"100\"\n style=\"background-color: green\"\n /> \n </body> \n</html>\n\n\n\n\n\n", "e": 26051, "s": 25744, "text": null }, { "code": null, "e": 26060, "s": 26051, "text": "Output :" }, { "code": null, "e": 26094, "s": 26060, "text": "SVG file using HTML <img> element" }, { "code": null, "e": 26129, "s": 26094, "text": "Method 2: Using SVG as an <object>" }, { "code": null, "e": 26138, "s": 26129, "text": "Syntax: " }, { "code": null, "e": 26214, "s": 26138, "text": "<object type=\"image/svg+xml\" data=\"logo.svg\" class=\"logo\">\n Logo\n</object>" }, { "code": null, "e": 26263, "s": 26214, "text": "Embedding a SVG via a <object> element requires:" }, { "code": null, "e": 26278, "s": 26263, "text": "type attribute" }, { "code": null, "e": 26293, "s": 26278, "text": "data attribute" }, { "code": null, "e": 26344, "s": 26293, "text": "class attribute ( if using external/internal CSS )" }, { "code": null, "e": 26351, "s": 26344, "text": "Pros :" }, { "code": null, "e": 26399, "s": 26351, "text": "You can use external/internal CSS to style SVG." }, { "code": null, "e": 26430, "s": 26399, "text": "Easy and quick implementation." }, { "code": null, "e": 26460, "s": 26430, "text": "Will work great with caching." }, { "code": null, "e": 26467, "s": 26460, "text": "Cons :" }, { "code": null, "e": 26554, "s": 26467, "text": "To use an external stylesheet, you need to use an <style> element inside the SVG file." }, { "code": null, "e": 26602, "s": 26554, "text": "Not so familiar with syntax and implementation." }, { "code": null, "e": 26613, "s": 26602, "text": "HTML code:" }, { "code": null, "e": 26618, "s": 26613, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html lang=\"en\"> \n<body> \n <object type=\"image/svg+xml\" \n data= \n\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210205161739/Screenshot-2021-02-05-161721.png\" \n class=\"logo\"> \n GFG Logo \n </object> \n \n</body> \n \n</html>\n\n\n\n\n\n", "e": 26916, "s": 26628, "text": null }, { "code": null, "e": 27004, "s": 26916, "text": "CSS code:The following is the content for the “styles.css” file used in the above code." }, { "code": null, "e": 27043, "s": 27004, "text": ".logo {\n height: 100;\n width: 100;\n}" }, { "code": null, "e": 27052, "s": 27043, "text": "Output :" }, { "code": null, "e": 27089, "s": 27052, "text": "SVG file using HTML <object> element" }, { "code": null, "e": 27132, "s": 27089, "text": "Method : Embedding an SVG with an <iframe>" }, { "code": null, "e": 27142, "s": 27132, "text": "Syntax : " }, { "code": null, "e": 27202, "s": 27142, "text": "<iframe src=\"logo.svg\" width=\"500\" height=\"500\">\n\n</iframe>" }, { "code": null, "e": 27248, "s": 27202, "text": "Embedding a SVG via <iframe> element requires" }, { "code": null, "e": 27262, "s": 27248, "text": "src attribute" }, { "code": null, "e": 27322, "s": 27262, "text": "height attribute (if your SVG has no inherent aspect ratio)" }, { "code": null, "e": 27382, "s": 27322, "text": "width attribute (if your SVG has no inherent aspect ratio)" }, { "code": null, "e": 27389, "s": 27382, "text": "Pros :" }, { "code": null, "e": 27420, "s": 27389, "text": "Quick and easy implementation." }, { "code": null, "e": 27446, "s": 27420, "text": "Same as <object> element." }, { "code": null, "e": 27453, "s": 27446, "text": "Cons :" }, { "code": null, "e": 27501, "s": 27453, "text": "You can’t use JavaScript to manipulate the SVG." }, { "code": null, "e": 27523, "s": 27501, "text": "Caching is not great." }, { "code": null, "e": 27535, "s": 27523, "text": "HTML code :" }, { "code": null, "e": 27540, "s": 27535, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html lang=\"en\"> \n <head> \n <meta charset=\"UTF-8\" /> \n <meta name=\"viewport\" content=\"width=device-width, \n initial-scale=1.0\" /> \n <link rel=\"stylesheet\" href=\"styles.css\" /> \n </head> \n \n <body> \n <iframe\n src= \n\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210205161739/Screenshot-2021-02-05-161721.png\"\n width=\"150\"\n height=\"150\"> \n </iframe> \n </body> \n</html> \n\n\n\n\n\n", "e": 28029, "s": 27550, "text": null }, { "code": null, "e": 28038, "s": 28029, "text": "Output :" }, { "code": null, "e": 28061, "s": 28038, "text": "\nJavaScript-Questions\n" }, { "code": null, "e": 28070, "s": 28061, "text": "\nPicked\n" }, { "code": null, "e": 28096, "s": 28070, "text": "\nTechnical Scripter 2020\n" }, { "code": null, "e": 28109, "s": 28096, "text": "\nJavaScript\n" }, { "code": null, "e": 28130, "s": 28109, "text": "\nTechnical Scripter\n" }, { "code": null, "e": 28149, "s": 28130, "text": "\nWeb Technologies\n" }, { "code": null, "e": 28354, "s": 28149, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 28415, "s": 28354, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28456, "s": 28415, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28510, "s": 28456, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28550, "s": 28510, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28612, "s": 28550, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 28668, "s": 28612, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28701, "s": 28668, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28763, "s": 28701, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28806, "s": 28763, "text": "How to fetch data from an API in ReactJS ?" } ]
String Ignorance | Practice | GeeksforGeeks
Given a string of both uppercase and lowercase alphabets, the task is to print the string with alternate occurrences of any character dropped(including space and consider upper and lowercase as same). Input: First line consists of T test cases. First line of every test case consists of String S. Output: Single line output, print the updated string. Constraints: 1<=T<=100 1<=|String|<=10000 Example: Input: 2 It is a long day dear. Geeks for geeks Output: It sa longdy ear. Geks fore Explanation: For the 1st test case. Print first "I" and then ignore next "i". Similarly print first space then ignore next space. and so on. 0 adityagagtiwari3 weeks ago Easy solution using HashSets static String findans(String si){ HashSet<Character> map = new HashSet<>(); String result = ""; for(char ch:si.toCharArray()) { //ch = Character.toLowerCase(ch); //handling spaces separately if(ch==' ') { if(map.contains('$')) { map.remove('$'); } else { result+=ch; map.add('$'); } } else { //be it lowercase or upper case the element should be pushed in both ways //to satisfy the incoming criteria for next same element with a different case if(map.contains(ch)) { map.remove(Character.toUpperCase(ch)); map.remove(Character.toLowerCase(ch)); } else { result+=ch; map.add(Character.toUpperCase(ch)); map.add(Character.toLowerCase(ch)); } } } return result; } 0 ritikj12 months ago T=int(input()) for i in range(T): s=input() a=[] s1="" for j in s: if j.lower() not in a: a.append(j.lower()) s1=s1+j else:a.remove(j.lower()) print(s1) 0 ritikj1 This comment was deleted. 0 kumarsaket6705 months ago import java.util.*;import java.lang.*;import java.io.*; class GFG {public static void main (String[] args) { //code Scanner sc = new Scanner(System.in);String a;int t = sc.nextInt();sc.nextLine(); while(t>0){ String s = sc.nextLine(); a = findans(s); System.out.println(a); t--;}}static String findans(String si){ String s = si; int i = 0; while(i < s.length()){ char ch = s.charAt(i); int first = s.indexOf(ch); int second1 = s.indexOf(String.valueOf(ch).toLowerCase(), i + 1); int second2 = s.indexOf(String.valueOf(ch).toUpperCase(), i + 1); int sec; if(second2 == -1 && second1 == -1){ sec = -1; }else if(second2 == -1 && second1 != -1){ sec = second1; }else if(second1 == -1 && second2 != -1){ sec = second2; }else{ sec = second1>=second2?second2:second1; } if(sec>=0){ s = charRemoveAt(s,sec); } i++; } return s;} public static String charRemoveAt(String str, int p) { return str.substring(0, p) + str.substring(p + 1); } } 0 e20040805 months ago runtime: 0.2/3.2 for _ in range(int(input())): s = input() S = '' arr = [] for c in s: flag = True for i in range(len(arr)): if c.lower() == arr[i]: del arr[i] flag = False break if flag: arr += [c.lower()] S = S + c print(S) +5 badgujarsachin835 months ago #include<iostream> using namespace std; string help(string s){ string res=""; int arr[256]={0}; for(int i=0;i<s.size();i++){ arr[tolower(s[i])]++; if(arr[tolower(s[i])]%2!=0){ res+=s[i]; } } return res; } int main() { //code int t; cin>>t; cin.ignore(); while(t--){ string s; getline(cin,s); cout<<help(s)<<endl; } return 0; } -2 rohitpendse1386 months ago #include <bits/stdc++.h> #define int long long using namespace std; string solve(string &s) { unordered_map<char, int> mp; string ans; for (int i = 0; i < s.length(); i++) { char temp = tolower(s[i]); mp[temp]++; if (mp[temp] & 1) ans += s[i]; } return ans; } int32_t main() { cin.tie(nullptr); cout.tie(nullptr); ios_base::sync_with_stdio(false); int t; cin >> t; cin.ignore(); while (t--) { string s; getline(cin, s); cout << solve(s) << '\n'; } return 0; } -1 gjayanta2367 months ago how to implement the code? 0 Imran Wahid8 months ago Imran Wahid Easy C++ solution https://uploads.disquscdn.c... 0 vivek kumar10 months ago vivek kumar #include <bits stdc++.h="">using namespace std;int main() { int t; cin>>t; cin.ignore(); while(t--) { string str; getline(cin,str); unordered_map<int,int> m; string res=""; for(int i=0;i<str.size();i++) {="" char="" k="tolower(str[i]);" if(m[k]="=0)" {="" res+="str[i];" m[k]="1;" }="" else="" {="" m[k]="0;" }="" }="" cout<<res<<endl;="" }="" return="" 0;="" }<="" code=""> 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": 439, "s": 238, "text": "Given a string of both uppercase and lowercase alphabets, the task is to print the string with alternate occurrences of any character dropped(including space and consider upper and lowercase as same)." }, { "code": null, "e": 535, "s": 439, "text": "Input:\nFirst line consists of T test cases. First line of every test case consists of String S." }, { "code": null, "e": 589, "s": 535, "text": "Output:\nSingle line output, print the updated string." }, { "code": null, "e": 631, "s": 589, "text": "Constraints:\n1<=T<=100\n1<=|String|<=10000" }, { "code": null, "e": 724, "s": 631, "text": "Example:\nInput:\n2\nIt is a long day dear.\nGeeks for geeks\nOutput:\nIt sa longdy ear.\nGeks fore" }, { "code": null, "e": 866, "s": 724, "text": "Explanation:\nFor the 1st test case. \nPrint first \"I\" and then ignore next \"i\". Similarly print first space then ignore next space. and so on." }, { "code": null, "e": 868, "s": 866, "text": "0" }, { "code": null, "e": 895, "s": 868, "text": "adityagagtiwari3 weeks ago" }, { "code": null, "e": 1956, "s": 895, "text": "Easy solution using HashSets\nstatic String findans(String si){\n HashSet<Character> map = new HashSet<>();\n String result = \"\";\n for(char ch:si.toCharArray())\n {\n //ch = Character.toLowerCase(ch);\n //handling spaces separately\n if(ch==' ')\n {\n if(map.contains('$'))\n {\n map.remove('$');\n }\n else\n {\n result+=ch;\n map.add('$');\n }\n }\n else \n {\n //be it lowercase or upper case the element should be pushed in both ways \n //to satisfy the incoming criteria for next same element with a different case\n if(map.contains(ch))\n {\n \n map.remove(Character.toUpperCase(ch));\n map.remove(Character.toLowerCase(ch));\n }\n else\n {\n result+=ch;\n map.add(Character.toUpperCase(ch));\n map.add(Character.toLowerCase(ch));\n \n }\n }\n }\n return result;\n}" }, { "code": null, "e": 1958, "s": 1956, "text": "0" }, { "code": null, "e": 1978, "s": 1958, "text": "ritikj12 months ago" }, { "code": null, "e": 2191, "s": 1978, "text": "T=int(input())\nfor i in range(T):\n s=input()\n a=[]\n s1=\"\"\n for j in s:\n if j.lower() not in a:\n a.append(j.lower())\n s1=s1+j\n else:a.remove(j.lower())\n print(s1)" }, { "code": null, "e": 2193, "s": 2191, "text": "0" }, { "code": null, "e": 2201, "s": 2193, "text": "ritikj1" }, { "code": null, "e": 2227, "s": 2201, "text": "This comment was deleted." }, { "code": null, "e": 2229, "s": 2227, "text": "0" }, { "code": null, "e": 2255, "s": 2229, "text": "kumarsaket6705 months ago" }, { "code": null, "e": 2311, "s": 2255, "text": "import java.util.*;import java.lang.*;import java.io.*;" }, { "code": null, "e": 3393, "s": 2311, "text": "class GFG {public static void main (String[] args) { //code Scanner sc = new Scanner(System.in);String a;int t = sc.nextInt();sc.nextLine(); while(t>0){ String s = sc.nextLine(); a = findans(s); System.out.println(a); t--;}}static String findans(String si){ String s = si; int i = 0; while(i < s.length()){ char ch = s.charAt(i); int first = s.indexOf(ch); int second1 = s.indexOf(String.valueOf(ch).toLowerCase(), i + 1); int second2 = s.indexOf(String.valueOf(ch).toUpperCase(), i + 1); int sec; if(second2 == -1 && second1 == -1){ sec = -1; }else if(second2 == -1 && second1 != -1){ sec = second1; }else if(second1 == -1 && second2 != -1){ sec = second2; }else{ sec = second1>=second2?second2:second1; } if(sec>=0){ s = charRemoveAt(s,sec); } i++; } return s;} public static String charRemoveAt(String str, int p) { return str.substring(0, p) + str.substring(p + 1); } }" }, { "code": null, "e": 3395, "s": 3393, "text": "0" }, { "code": null, "e": 3416, "s": 3395, "text": "e20040805 months ago" }, { "code": null, "e": 3433, "s": 3416, "text": "runtime: 0.2/3.2" }, { "code": null, "e": 3770, "s": 3433, "text": "for _ in range(int(input())):\n s = input()\n S = ''\n arr = []\n for c in s:\n flag = True\n for i in range(len(arr)):\n if c.lower() == arr[i]:\n del arr[i]\n flag = False\n break\n if flag:\n arr += [c.lower()]\n S = S + c\n print(S)" }, { "code": null, "e": 3773, "s": 3770, "text": "+5" }, { "code": null, "e": 3802, "s": 3773, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 4208, "s": 3802, "text": "#include<iostream>\nusing namespace std;\nstring help(string s){\n string res=\"\";\n int arr[256]={0};\n for(int i=0;i<s.size();i++){\n arr[tolower(s[i])]++;\n if(arr[tolower(s[i])]%2!=0){\n res+=s[i];\n }\n }\n return res;\n}\nint main()\n {\n\t//code\n\tint t;\n\tcin>>t;\n\tcin.ignore();\n\twhile(t--){\n\t string s;\n\t getline(cin,s);\n\t cout<<help(s)<<endl;\n\t}\n\treturn 0;\n}" }, { "code": null, "e": 4211, "s": 4208, "text": "-2" }, { "code": null, "e": 4238, "s": 4211, "text": "rohitpendse1386 months ago" }, { "code": null, "e": 4805, "s": 4238, "text": "#include <bits/stdc++.h>\n\n#define int long long\nusing namespace std;\n\nstring solve(string &s) {\n unordered_map<char, int> mp;\n string ans;\n for (int i = 0; i < s.length(); i++) {\n char temp = tolower(s[i]);\n mp[temp]++;\n if (mp[temp] & 1) ans += s[i];\n }\n return ans;\n}\n\nint32_t main() {\n cin.tie(nullptr);\n cout.tie(nullptr);\n ios_base::sync_with_stdio(false);\n int t;\n cin >> t;\n cin.ignore();\n while (t--) {\n string s;\n getline(cin, s);\n cout << solve(s) << '\\n';\n }\n return 0;\n}" }, { "code": null, "e": 4808, "s": 4805, "text": "-1" }, { "code": null, "e": 4832, "s": 4808, "text": "gjayanta2367 months ago" }, { "code": null, "e": 4859, "s": 4832, "text": "how to implement the code?" }, { "code": null, "e": 4861, "s": 4859, "text": "0" }, { "code": null, "e": 4885, "s": 4861, "text": "Imran Wahid8 months ago" }, { "code": null, "e": 4897, "s": 4885, "text": "Imran Wahid" }, { "code": null, "e": 4946, "s": 4897, "text": "Easy C++ solution https://uploads.disquscdn.c..." }, { "code": null, "e": 4948, "s": 4946, "text": "0" }, { "code": null, "e": 4973, "s": 4948, "text": "vivek kumar10 months ago" }, { "code": null, "e": 4985, "s": 4973, "text": "vivek kumar" }, { "code": null, "e": 5412, "s": 4985, "text": "#include <bits stdc++.h=\"\">using namespace std;int main() { int t; cin>>t; cin.ignore(); while(t--) { string str; getline(cin,str); unordered_map<int,int> m; string res=\"\"; for(int i=0;i<str.size();i++) {=\"\" char=\"\" k=\"tolower(str[i]);\" if(m[k]=\"=0)\" {=\"\" res+=\"str[i];\" m[k]=\"1;\" }=\"\" else=\"\" {=\"\" m[k]=\"0;\" }=\"\" }=\"\" cout<<res<<endl;=\"\" }=\"\" return=\"\" 0;=\"\" }<=\"\" code=\"\">" }, { "code": null, "e": 5558, "s": 5412, "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": 5594, "s": 5558, "text": " Login to access your submissions. " }, { "code": null, "e": 5604, "s": 5594, "text": "\nProblem\n" }, { "code": null, "e": 5614, "s": 5604, "text": "\nContest\n" }, { "code": null, "e": 5677, "s": 5614, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5825, "s": 5677, "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": 6033, "s": 5825, "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": 6139, "s": 6033, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Adjusting Text background transparency in Matplotlib
To adjust text background transparency in matplotlib, we can change the alpha value in the dictionary of bbox with facecolor='red' and alpha='0.4'. Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create x and y data points using numpy. Create x and y data points using numpy. Plot x and y data points using plot() method. Plot x and y data points using plot() method. Now use text() method to adjust the text background with fontdict and bbox dictionaries at x=-1.0 and y=4.0. Now use text() method to adjust the text background with fontdict and bbox dictionaries at x=-1.0 and y=4.0. To display the figure, use show() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-2, 2, 10) y = np.exp(x) plt.plot(x, y) plt.text(-1.0, 4.0, 'y=exp(x)', fontdict=dict(fontsize=15, fontweight='bold'), bbox=dict(facecolor='red', alpha=0.4, edgecolor='black')) plt.show()
[ { "code": null, "e": 1335, "s": 1187, "text": "To adjust text background transparency in matplotlib, we can change the alpha value in the dictionary of bbox with facecolor='red' and alpha='0.4'." }, { "code": null, "e": 1411, "s": 1335, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1487, "s": 1411, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1527, "s": 1487, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1567, "s": 1527, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1613, "s": 1567, "text": "Plot x and y data points using plot() method." }, { "code": null, "e": 1659, "s": 1613, "text": "Plot x and y data points using plot() method." }, { "code": null, "e": 1768, "s": 1659, "text": "Now use text() method to adjust the text background with fontdict and bbox dictionaries at x=-1.0 and y=4.0." }, { "code": null, "e": 1877, "s": 1768, "text": "Now use text() method to adjust the text background with fontdict and bbox dictionaries at x=-1.0 and y=4.0." }, { "code": null, "e": 1919, "s": 1877, "text": "To display the figure, use show() method." }, { "code": null, "e": 1961, "s": 1919, "text": "To display the figure, use show() method." }, { "code": null, "e": 2308, "s": 1961, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-2, 2, 10)\ny = np.exp(x)\nplt.plot(x, y)\nplt.text(-1.0, 4.0, 'y=exp(x)', fontdict=dict(fontsize=15, fontweight='bold'), bbox=dict(facecolor='red', alpha=0.4, edgecolor='black'))\nplt.show()" } ]
p5.js | createVector() function
05 Oct, 2021 The createVector() function in p5.js is used to create the new p5 vector which contains both magnitude and direction. This provides a two or three-dimensional vector, specifically a geometric vector. Syntax: createVector([x], [y], [z]) Parameters: This function accepts three parameters as mentioned above and described below: x: This parameter stores the x component of the vector. y: This parameter stores the y component of the vector. z: This parameter stores the z component of the vector. Below programs illustrate the createVector() function in p5.js: Example 1: This example uses createVector() function to draw a line. Javascript function setup() { // Create a Canvas createCanvas(500, 550);} function draw() { // Vector initialisation // using createVector t1 = createVector(10, 40); t2 = createVector(411, 500); // Set background color background(200); // Set stroke weight strokeWeight(2); // line using vector line(t1.x, t1.y, t2.x, t2.y); translate(12, 54); line(t1.x, t1.y, t2.x, t2.y);} Output: Example 2: This example uses createVector() function to draw a circle. Javascript function setup() { // Create a Canvas createCanvas(500, 550);} function draw() { // Vector initialisation // using createVector t1 = createVector(10, 40); t2 = createVector(41, 50); // Set background color background(200); // Set stroke weight strokeWeight(2); // Fill yellow fill('yellow'); // ellipse using vector ellipse(t1.x*millis() / 1000 * 20, t1.y, t2.x+100, t2.y+100);} Output: Reference: https://p5js.org/reference/#/p5/createVector anikaseth98 ruhelaa48 JavaScript-p5.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 Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners 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": "\n05 Oct, 2021" }, { "code": null, "e": 228, "s": 28, "text": "The createVector() function in p5.js is used to create the new p5 vector which contains both magnitude and direction. This provides a two or three-dimensional vector, specifically a geometric vector." }, { "code": null, "e": 237, "s": 228, "text": "Syntax: " }, { "code": null, "e": 265, "s": 237, "text": "createVector([x], [y], [z])" }, { "code": null, "e": 358, "s": 265, "text": "Parameters: This function accepts three parameters as mentioned above and described below: " }, { "code": null, "e": 414, "s": 358, "text": "x: This parameter stores the x component of the vector." }, { "code": null, "e": 470, "s": 414, "text": "y: This parameter stores the y component of the vector." }, { "code": null, "e": 526, "s": 470, "text": "z: This parameter stores the z component of the vector." }, { "code": null, "e": 590, "s": 526, "text": "Below programs illustrate the createVector() function in p5.js:" }, { "code": null, "e": 661, "s": 590, "text": "Example 1: This example uses createVector() function to draw a line. " }, { "code": null, "e": 672, "s": 661, "text": "Javascript" }, { "code": "function setup() { // Create a Canvas createCanvas(500, 550);} function draw() { // Vector initialisation // using createVector t1 = createVector(10, 40); t2 = createVector(411, 500); // Set background color background(200); // Set stroke weight strokeWeight(2); // line using vector line(t1.x, t1.y, t2.x, t2.y); translate(12, 54); line(t1.x, t1.y, t2.x, t2.y);}", "e": 1102, "s": 672, "text": null }, { "code": null, "e": 1111, "s": 1102, "text": "Output: " }, { "code": null, "e": 1183, "s": 1111, "text": "Example 2: This example uses createVector() function to draw a circle. " }, { "code": null, "e": 1194, "s": 1183, "text": "Javascript" }, { "code": "function setup() { // Create a Canvas createCanvas(500, 550);} function draw() { // Vector initialisation // using createVector t1 = createVector(10, 40); t2 = createVector(41, 50); // Set background color background(200); // Set stroke weight strokeWeight(2); // Fill yellow fill('yellow'); // ellipse using vector ellipse(t1.x*millis() / 1000 * 20, t1.y, t2.x+100, t2.y+100);}", "e": 1649, "s": 1194, "text": null }, { "code": null, "e": 1658, "s": 1649, "text": "Output: " }, { "code": null, "e": 1715, "s": 1658, "text": "Reference: https://p5js.org/reference/#/p5/createVector " }, { "code": null, "e": 1727, "s": 1715, "text": "anikaseth98" }, { "code": null, "e": 1737, "s": 1727, "text": "ruhelaa48" }, { "code": null, "e": 1754, "s": 1737, "text": "JavaScript-p5.js" }, { "code": null, "e": 1765, "s": 1754, "text": "JavaScript" }, { "code": null, "e": 1782, "s": 1765, "text": "Web Technologies" }, { "code": null, "e": 1880, "s": 1782, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1941, "s": 1880, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2013, "s": 1941, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2053, "s": 2013, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2094, "s": 2053, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2136, "s": 2094, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2169, "s": 2136, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2231, "s": 2169, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2292, "s": 2231, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2342, "s": 2292, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Pandas Series.dt.day
20 Mar, 2019 Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.day attribute return a numpy array containing the day of the datetime in the underlying data of the given series object. Syntax: Series.dt.day Parameter : None Returns : numpy array Example #1: Use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr) Output : Now we will use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object. # return the dayresult = sr.dt.day # print the resultprint(result) Output :As we can see in the output, the Series.dt.day attribute has successfully accessed and returned the day of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr) Output : Now we will use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object. # return the dayresult = sr.dt.day # print the resultprint(result) Output :As we can see in the output, the Series.dt.day attribute has successfully accessed and returned the day of the datetime in the underlying data of the given series object. Python pandas-series-datetime Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Mar, 2019" }, { "code": null, "e": 270, "s": 28, "text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.day attribute return a numpy array containing the day of the datetime in the underlying data of the given series object." }, { "code": null, "e": 292, "s": 270, "text": "Syntax: Series.dt.day" }, { "code": null, "e": 309, "s": 292, "text": "Parameter : None" }, { "code": null, "e": 331, "s": 309, "text": "Returns : numpy array" }, { "code": null, "e": 456, "s": 331, "text": "Example #1: Use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)", "e": 850, "s": 456, "text": null }, { "code": null, "e": 859, "s": 850, "text": "Output :" }, { "code": null, "e": 984, "s": 859, "text": "Now we will use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object." }, { "code": "# return the dayresult = sr.dt.day # print the resultprint(result)", "e": 1052, "s": 984, "text": null }, { "code": null, "e": 1357, "s": 1052, "text": "Output :As we can see in the output, the Series.dt.day attribute has successfully accessed and returned the day of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)", "e": 1654, "s": 1357, "text": null }, { "code": null, "e": 1663, "s": 1654, "text": "Output :" }, { "code": null, "e": 1788, "s": 1663, "text": "Now we will use Series.dt.day attribute to return the day of the datetime in the underlying data of the given Series object." }, { "code": "# return the dayresult = sr.dt.day # print the resultprint(result)", "e": 1856, "s": 1788, "text": null }, { "code": null, "e": 2035, "s": 1856, "text": "Output :As we can see in the output, the Series.dt.day attribute has successfully accessed and returned the day of the datetime in the underlying data of the given series object." }, { "code": null, "e": 2065, "s": 2035, "text": "Python pandas-series-datetime" }, { "code": null, "e": 2079, "s": 2065, "text": "Python-pandas" }, { "code": null, "e": 2086, "s": 2079, "text": "Python" }, { "code": null, "e": 2184, "s": 2086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2216, "s": 2184, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2243, "s": 2216, "text": "Python Classes and Objects" }, { "code": null, "e": 2264, "s": 2243, "text": "Python OOPs Concepts" }, { "code": null, "e": 2287, "s": 2264, "text": "Introduction To PYTHON" }, { "code": null, "e": 2343, "s": 2287, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2374, "s": 2343, "text": "Python | os.path.join() method" }, { "code": null, "e": 2416, "s": 2374, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2458, "s": 2416, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2497, "s": 2458, "text": "Python | datetime.timedelta() function" } ]
Exception handling in Julia
10 May, 2022 Any unexpected condition that occurs during the normal program execution is called an Exception. Exception Handling in Julia is the mechanism to overcome this situation by chalking out an alternative path to continue normal program execution. If exceptions are left unhandled, the program terminates abruptly. The actions to be performed in case of occurrence of an exception is not known to the program. The process of avoiding the compiler to crash on such exceptions is termed as Exception Handling. Julia allows exception handling through the use of a try-catch block. The block of code that can possibly throw an exception is placed in the try block and the catch block handles the exception thrown. The exception propagates through the call stack until a try-catch block is found. Let us consider the following code, Here we try to find the square root of -1 which throws “DomainError” and the program terminates. Python3 println(sqrt(-1)) Output: ERROR: LoadError: DomainError: sqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)). Stacktrace: [1] sqrt(::Int64) at ./math.jl:434 while loading /home/cg/root/945981/main.jl, in expression starting on line 1 In absence of a try-catch block the program terminates abruptly. However, we can prevent the termination of program by handling the exception gracefully using a try-catch block. Python3 println("Before Exception")try sqrt(-1)catch println("Cannot find the square root of negative numbers")endprintln("After Exception") Output: Before Exception Cannot find the square root of negative numbers After Exception The try-catch block also allows the exception to be stored in a variable. The method of using the catch block to handle multiple types of Exception is called Canonical method. The following example calculates the square root of the third element of x if x is indexable, otherwise assumes x is a real number and returns its square root. Python3 sqrt_third(x) = try println(sqrt(x[3])) catch y if isa(y, DomainError) println(sqrt(complex(x[3], 0))) elseif isa(y, BoundsError) println(sqrt(x)) end end sqrt_third([1 9 16 25])sqrt_third([1 -4 9 16])sqrt_third(25)sqrt_third(-9) Output: 4.0 3.0 5.0 ERROR: LoadError: DomainError: Stacktrace: [1] sqrt_third(::Int64) at /home/cg/root/945981/main.jl:7 while loading /home/cg/root/945981/main.jl, in expression starting on line 15 The finally block runs irrespective of the occurrence of an exception. Code inside the finally block can be used to close resources like opened files or other cleanup work. Python3 try f = open("file.txt")catch println("No such file exists")finally println("After exception")end Output: No such file exists After exception The throw() function can be used to throw custom exceptions. The following examples shows an error being thrown from a function and handled by the catch block. The error() function is used to produce an ErrorException. Python3 function f(x) if(x < 5) throw(error()) end return sqrt(x)end try println(f(9)) println(f(1))catch e println("Argument less than 5")end Output: 3.0 Argument less than 5 Exceptions can also be thrown from the catch block. The catch block may include some code to handle the caught exception and then rethrow an exception. This exception must be handled by another try-catch block in the same method or any other method in the call stack. The exception propagates all throughout to the main function if it is left uncaught. Python3 function f(x) if(x < 5) throw(error()) end return sqrt(x)end try println(f(9)) println(f(1))catch e println("Argument less than 5") throw(error())end Output: 3.0 Argument less than 5 ERROR: LoadError: Stacktrace: [1] error() at ./error.jl:30 while loading /home/cg/root/945981/main.jl, in expression starting on line 13 Python3 function f(x) if(x < 5) throw(error()) end return sqrt(x)end try try println(f(9)) println(f(1)) catch e println("Argument less than 5") throw(error()) endcatch e println("Second catch block")end Output: 3.0 Argument less than 5 Second catch block try sqrt(x) catch y end This means try sqrt(x), and if an exception is thrown, pass it to the variable y. Now if the value stored in y must be returned then the catch must be followed by a semicolon. try sqrt(x) catch; y end Python3 try println(sqrt(-9)) catch; y end Output: ERROR: LoadError: UndefVarError: y not defined while loading /home/cg/root/945981/main.jl, in expression starting on line 1 Julia provides some built-in Exceptions, which are as follows: sagartomar9927 Picked R Error-handling Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Searching in Array for a given element in Julia String concatenation in Julia Vectors in Julia String to Number Conversion in Julia Getting rounded value of a number in Julia - round() Method Tuples in Julia Formatting of Strings in Julia Creating array with repeated elements in Julia - repeat() Method Storing Output on a File in Julia Working with DataFrames in Julia
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2022" }, { "code": null, "e": 531, "s": 28, "text": "Any unexpected condition that occurs during the normal program execution is called an Exception. Exception Handling in Julia is the mechanism to overcome this situation by chalking out an alternative path to continue normal program execution. If exceptions are left unhandled, the program terminates abruptly. The actions to be performed in case of occurrence of an exception is not known to the program. The process of avoiding the compiler to crash on such exceptions is termed as Exception Handling." }, { "code": null, "e": 949, "s": 531, "text": "Julia allows exception handling through the use of a try-catch block. The block of code that can possibly throw an exception is placed in the try block and the catch block handles the exception thrown. The exception propagates through the call stack until a try-catch block is found. Let us consider the following code, Here we try to find the square root of -1 which throws “DomainError” and the program terminates. " }, { "code": null, "e": 957, "s": 949, "text": "Python3" }, { "code": "println(sqrt(-1))", "e": 975, "s": 957, "text": null }, { "code": null, "e": 983, "s": 975, "text": "Output:" }, { "code": null, "e": 1235, "s": 983, "text": "ERROR: LoadError: DomainError:\nsqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).\nStacktrace:\n [1] sqrt(::Int64) at ./math.jl:434\nwhile loading /home/cg/root/945981/main.jl, in expression starting on line 1" }, { "code": null, "e": 1414, "s": 1235, "text": "In absence of a try-catch block the program terminates abruptly. However, we can prevent the termination of program by handling the exception gracefully using a try-catch block. " }, { "code": null, "e": 1422, "s": 1414, "text": "Python3" }, { "code": "println(\"Before Exception\")try sqrt(-1)catch println(\"Cannot find the square root of negative numbers\")endprintln(\"After Exception\")", "e": 1561, "s": 1422, "text": null }, { "code": null, "e": 1569, "s": 1561, "text": "Output:" }, { "code": null, "e": 1650, "s": 1569, "text": "Before Exception\nCannot find the square root of negative numbers\nAfter Exception" }, { "code": null, "e": 1987, "s": 1650, "text": "The try-catch block also allows the exception to be stored in a variable. The method of using the catch block to handle multiple types of Exception is called Canonical method. The following example calculates the square root of the third element of x if x is indexable, otherwise assumes x is a real number and returns its square root. " }, { "code": null, "e": 1995, "s": 1987, "text": "Python3" }, { "code": "sqrt_third(x) = try println(sqrt(x[3])) catch y if isa(y, DomainError) println(sqrt(complex(x[3], 0))) elseif isa(y, BoundsError) println(sqrt(x)) end end sqrt_third([1 9 16 25])sqrt_third([1 -4 9 16])sqrt_third(25)sqrt_third(-9)", "e": 2282, "s": 1995, "text": null }, { "code": null, "e": 2290, "s": 2282, "text": "Output:" }, { "code": null, "e": 2482, "s": 2290, "text": "4.0\n3.0\n5.0\nERROR: LoadError: DomainError:\nStacktrace:\n [1] sqrt_third(::Int64) at /home/cg/root/945981/main.jl:7\nwhile loading /home/cg/root/945981/main.jl, in expression starting on line 15" }, { "code": null, "e": 2656, "s": 2482, "text": "The finally block runs irrespective of the occurrence of an exception. Code inside the finally block can be used to close resources like opened files or other cleanup work. " }, { "code": null, "e": 2664, "s": 2656, "text": "Python3" }, { "code": "try f = open(\"file.txt\")catch println(\"No such file exists\")finally println(\"After exception\")end", "e": 2771, "s": 2664, "text": null }, { "code": null, "e": 2779, "s": 2771, "text": "Output:" }, { "code": null, "e": 2815, "s": 2779, "text": "No such file exists\nAfter exception" }, { "code": null, "e": 3035, "s": 2815, "text": "The throw() function can be used to throw custom exceptions. The following examples shows an error being thrown from a function and handled by the catch block. The error() function is used to produce an ErrorException. " }, { "code": null, "e": 3043, "s": 3035, "text": "Python3" }, { "code": "function f(x) if(x < 5) throw(error()) end return sqrt(x)end try println(f(9)) println(f(1))catch e println(\"Argument less than 5\")end", "e": 3203, "s": 3043, "text": null }, { "code": null, "e": 3211, "s": 3203, "text": "Output:" }, { "code": null, "e": 3236, "s": 3211, "text": "3.0\nArgument less than 5" }, { "code": null, "e": 3590, "s": 3236, "text": "Exceptions can also be thrown from the catch block. The catch block may include some code to handle the caught exception and then rethrow an exception. This exception must be handled by another try-catch block in the same method or any other method in the call stack. The exception propagates all throughout to the main function if it is left uncaught. " }, { "code": null, "e": 3598, "s": 3590, "text": "Python3" }, { "code": "function f(x) if(x < 5) throw(error()) end return sqrt(x)end try println(f(9)) println(f(1))catch e println(\"Argument less than 5\") throw(error())end", "e": 3776, "s": 3598, "text": null }, { "code": null, "e": 3784, "s": 3776, "text": "Output:" }, { "code": null, "e": 3948, "s": 3784, "text": "3.0\nArgument less than 5\nERROR: LoadError: \nStacktrace:\n [1] error() at ./error.jl:30\nwhile loading /home/cg/root/945981/main.jl, in expression starting on line 13" }, { "code": null, "e": 3956, "s": 3948, "text": "Python3" }, { "code": "function f(x) if(x < 5) throw(error()) end return sqrt(x)end try try println(f(9)) println(f(1)) catch e println(\"Argument less than 5\") throw(error()) endcatch e println(\"Second catch block\")end", "e": 4208, "s": 3956, "text": null }, { "code": null, "e": 4216, "s": 4208, "text": "Output:" }, { "code": null, "e": 4260, "s": 4216, "text": "3.0\nArgument less than 5\nSecond catch block" }, { "code": null, "e": 4284, "s": 4260, "text": "try sqrt(x) catch y end" }, { "code": null, "e": 4460, "s": 4284, "text": "This means try sqrt(x), and if an exception is thrown, pass it to the variable y. Now if the value stored in y must be returned then the catch must be followed by a semicolon." }, { "code": null, "e": 4485, "s": 4460, "text": "try sqrt(x) catch; y end" }, { "code": null, "e": 4493, "s": 4485, "text": "Python3" }, { "code": "try println(sqrt(-9)) catch; y end", "e": 4528, "s": 4493, "text": null }, { "code": null, "e": 4536, "s": 4528, "text": "Output:" }, { "code": null, "e": 4660, "s": 4536, "text": "ERROR: LoadError: UndefVarError: y not defined\nwhile loading /home/cg/root/945981/main.jl, in expression starting on line 1" }, { "code": null, "e": 4723, "s": 4660, "text": "Julia provides some built-in Exceptions, which are as follows:" }, { "code": null, "e": 4738, "s": 4723, "text": "sagartomar9927" }, { "code": null, "e": 4745, "s": 4738, "text": "Picked" }, { "code": null, "e": 4762, "s": 4745, "text": "R Error-handling" }, { "code": null, "e": 4768, "s": 4762, "text": "Julia" }, { "code": null, "e": 4866, "s": 4768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4914, "s": 4866, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 4944, "s": 4914, "text": "String concatenation in Julia" }, { "code": null, "e": 4961, "s": 4944, "text": "Vectors in Julia" }, { "code": null, "e": 4998, "s": 4961, "text": "String to Number Conversion in Julia" }, { "code": null, "e": 5058, "s": 4998, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 5074, "s": 5058, "text": "Tuples in Julia" }, { "code": null, "e": 5105, "s": 5074, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 5170, "s": 5105, "text": "Creating array with repeated elements in Julia - repeat() Method" }, { "code": null, "e": 5204, "s": 5170, "text": "Storing Output on a File in Julia" } ]
JS++ | Static vs. Dynamic Polymorphism
30 Aug, 2018 Static polymorphism is polymorphism that occurs at compile time, and dynamic polymorphism is polymorphism that occurs at runtime (during application execution). An aspect of static polymorphism is early binding. In early binding, the specific method to call is resolved at compile time. (JS++ also supports late binding via virtual functions which we will cover later.) Early binding is faster because there is no runtime overhead. Early binding is the default behavior and most common for JS++. If you want late binding, you have to explicitly specify it. Again, we’ll cover late binding in a later section. In our code, we specified the ‘overwrite’ modifier for our ‘Cat’ and ‘Dog’ class render() methods. This enabled method hiding, but it specifies early binding. Here’s the code from Cat.jspp: overwrite void render() { $element.attr("title", _name); super.render(); } Later, when we changed the type of our cats to ‘Animal’ in main.jspp, the type of our cats was changed from ‘Cat’ to ‘Animal’. You might say, “Yes, but we instantiated our cat objects using the ‘Cat’ class nonetheless.” While this is true, it also means our cat variables can now accept data of any type satisfying the ‘Animal’ constraint (including ‘Animal’ itself if we didn’t specify a protected constructor on ‘Animal’). For example, this now becomes completely acceptable code: import System; import Animals; Animal cat1 = new Cat("Kitty"); if (Math.random(1, 10) > 3) { cat1 = new Dog("Fido"); } cat1.render(); Ignore the ‘System’ import, but it imports the Math.random() function. It’s used for illustrating the example. I also purposefully kept the name of our variable as ‘cat1’ to illustrate the point. ‘cat1’ has type ‘Animal’. Thus, all objects of type ‘Animal’ can be assigned to ‘cat1’ (including objects of type ‘Dog’). If you actually compile, run the code above, and refresh sufficiently, you’ll notice that your “cat” will sometimes be rendered as a dog. As you can observe, when we have a type ‘Animal’, the data can be ‘Cat’ in our program or it can also randomly become a ‘Dog’ based on runtime random number generation. The random numbers are not generated at compile time. The random numbers are generated during application execution (runtime). Thus, from the compiler’s perspective, if we are going to resolve the ‘render’ method, we are going to resolve it to the ‘render’ method of the user-specified type, ‘Animal’, because it is the most correct. Recall that in subtyping, all Cats and Dogs are Animals, but not all Animals are Cats and Dogs. Thus, this should hopefully help you understand early binding and static/compile-time polymorphism. Aside: Data Types as Specifications Data types are also specifications. We are specifying what constitutes a correct program. For instance, you wouldn’t specify a ‘subtract’ function to accept two parameters of type ‘string’. In our case, if we wanted a cat, we should have specified the type ‘Cat’ rather than generalizing to ‘Animal’. While the ability to express algorithms in more general terms is desirable, it may not always be correct. Technically, the program is still type-correct. In both cases (‘Cat’ and ‘Dog’), we have an object of type ‘Animal’. It just happens that our ‘Animal’ was named ‘cat1’ so one potential fix for the code above may be to rename the variable to ‘animal’ or something similar to express our intent. The other potential fix, if we want ‘cat1’ to always be a cat, is to restrict the data type to ‘Cat’ instead of ‘Animal’. If you do this, you’ll get a compile error because ‘Dog’ is not a subtype of ‘Cat’: JSPPE5000: Cannot convert `Animals.Dog' to `Animals.Cat' at line 6 char 8 at main.jspp In runtime polymorphism, the type is determined at runtime. For example, we can use the ‘instanceof’ operator to check the runtime data type. Change your main.jspp file and observe the result: import System; import Animals; external $; Animal animal = new Cat("Kitty"); if (Math.random(1, 10) > 3) { animal = new Dog("Fido"); } if (animal instanceof Cat) { $("#content").text("We have a CAT."); } else { $("#content").text("We have a DOG."); } Keep refreshing and you should see that sometimes we have a ‘Cat’ instance and sometimes we have a ‘Dog’ instance. However, the types (and resulting messages) are determined at runtime — not compile time. JS++ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JS++ | Getters and Setters JS++ | Interfaces JS++ | Abstract Classes and Methods JS++ | Event Handlers JS++ | Constructors JS++ | Fields and Methods JS++ | Classes, OOP, and User-defined Types JS++ | Type System JS++ | How to install JS++ on different Operating Systems JS++ | Inheritance
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Aug, 2018" }, { "code": null, "e": 189, "s": 28, "text": "Static polymorphism is polymorphism that occurs at compile time, and dynamic polymorphism is polymorphism that occurs at runtime (during application execution)." }, { "code": null, "e": 637, "s": 189, "text": "An aspect of static polymorphism is early binding. In early binding, the specific method to call is resolved at compile time. (JS++ also supports late binding via virtual functions which we will cover later.) Early binding is faster because there is no runtime overhead. Early binding is the default behavior and most common for JS++. If you want late binding, you have to explicitly specify it. Again, we’ll cover late binding in a later section." }, { "code": null, "e": 827, "s": 637, "text": "In our code, we specified the ‘overwrite’ modifier for our ‘Cat’ and ‘Dog’ class render() methods. This enabled method hiding, but it specifies early binding. Here’s the code from Cat.jspp:" }, { "code": null, "e": 911, "s": 827, "text": "overwrite void render() {\n $element.attr(\"title\", _name);\n super.render();\n}\n" }, { "code": null, "e": 1394, "s": 911, "text": "Later, when we changed the type of our cats to ‘Animal’ in main.jspp, the type of our cats was changed from ‘Cat’ to ‘Animal’. You might say, “Yes, but we instantiated our cat objects using the ‘Cat’ class nonetheless.” While this is true, it also means our cat variables can now accept data of any type satisfying the ‘Animal’ constraint (including ‘Animal’ itself if we didn’t specify a protected constructor on ‘Animal’). For example, this now becomes completely acceptable code:" }, { "code": null, "e": 1534, "s": 1394, "text": "import System;\nimport Animals;\n\nAnimal cat1 = new Cat(\"Kitty\");\nif (Math.random(1, 10) > 3) {\n cat1 = new Dog(\"Fido\");\n}\ncat1.render();\n" }, { "code": null, "e": 1852, "s": 1534, "text": "Ignore the ‘System’ import, but it imports the Math.random() function. It’s used for illustrating the example. I also purposefully kept the name of our variable as ‘cat1’ to illustrate the point. ‘cat1’ has type ‘Animal’. Thus, all objects of type ‘Animal’ can be assigned to ‘cat1’ (including objects of type ‘Dog’)." }, { "code": null, "e": 1990, "s": 1852, "text": "If you actually compile, run the code above, and refresh sufficiently, you’ll notice that your “cat” will sometimes be rendered as a dog." }, { "code": null, "e": 2589, "s": 1990, "text": "As you can observe, when we have a type ‘Animal’, the data can be ‘Cat’ in our program or it can also randomly become a ‘Dog’ based on runtime random number generation. The random numbers are not generated at compile time. The random numbers are generated during application execution (runtime). Thus, from the compiler’s perspective, if we are going to resolve the ‘render’ method, we are going to resolve it to the ‘render’ method of the user-specified type, ‘Animal’, because it is the most correct. Recall that in subtyping, all Cats and Dogs are Animals, but not all Animals are Cats and Dogs." }, { "code": null, "e": 2689, "s": 2589, "text": "Thus, this should hopefully help you understand early binding and static/compile-time polymorphism." }, { "code": null, "e": 2725, "s": 2689, "text": "Aside: Data Types as Specifications" }, { "code": null, "e": 3132, "s": 2725, "text": "Data types are also specifications. We are specifying what constitutes a correct program. For instance, you wouldn’t specify a ‘subtract’ function to accept two parameters of type ‘string’. In our case, if we wanted a cat, we should have specified the type ‘Cat’ rather than generalizing to ‘Animal’. While the ability to express algorithms in more general terms is desirable, it may not always be correct." }, { "code": null, "e": 3426, "s": 3132, "text": "Technically, the program is still type-correct. In both cases (‘Cat’ and ‘Dog’), we have an object of type ‘Animal’. It just happens that our ‘Animal’ was named ‘cat1’ so one potential fix for the code above may be to rename the variable to ‘animal’ or something similar to express our intent." }, { "code": null, "e": 3632, "s": 3426, "text": "The other potential fix, if we want ‘cat1’ to always be a cat, is to restrict the data type to ‘Cat’ instead of ‘Animal’. If you do this, you’ll get a compile error because ‘Dog’ is not a subtype of ‘Cat’:" }, { "code": null, "e": 3719, "s": 3632, "text": "JSPPE5000: Cannot convert `Animals.Dog' to `Animals.Cat' at line 6 char 8 at main.jspp" }, { "code": null, "e": 3912, "s": 3719, "text": "In runtime polymorphism, the type is determined at runtime. For example, we can use the ‘instanceof’ operator to check the runtime data type. Change your main.jspp file and observe the result:" }, { "code": null, "e": 4179, "s": 3912, "text": "import System;\nimport Animals;\n\nexternal $;\n\nAnimal animal = new Cat(\"Kitty\");\nif (Math.random(1, 10) > 3) {\n animal = new Dog(\"Fido\");\n}\n\nif (animal instanceof Cat) {\n $(\"#content\").text(\"We have a CAT.\");\n}\nelse {\n $(\"#content\").text(\"We have a DOG.\");\n}\n" }, { "code": null, "e": 4384, "s": 4179, "text": "Keep refreshing and you should see that sometimes we have a ‘Cat’ instance and sometimes we have a ‘Dog’ instance. However, the types (and resulting messages) are determined at runtime — not compile time." }, { "code": null, "e": 4389, "s": 4384, "text": "JS++" }, { "code": null, "e": 4487, "s": 4389, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4514, "s": 4487, "text": "JS++ | Getters and Setters" }, { "code": null, "e": 4532, "s": 4514, "text": "JS++ | Interfaces" }, { "code": null, "e": 4568, "s": 4532, "text": "JS++ | Abstract Classes and Methods" }, { "code": null, "e": 4590, "s": 4568, "text": "JS++ | Event Handlers" }, { "code": null, "e": 4610, "s": 4590, "text": "JS++ | Constructors" }, { "code": null, "e": 4636, "s": 4610, "text": "JS++ | Fields and Methods" }, { "code": null, "e": 4680, "s": 4636, "text": "JS++ | Classes, OOP, and User-defined Types" }, { "code": null, "e": 4699, "s": 4680, "text": "JS++ | Type System" }, { "code": null, "e": 4757, "s": 4699, "text": "JS++ | How to install JS++ on different Operating Systems" } ]
localtime() function in C++
01 Oct, 2018 The localtime() function is defined in the ctime header file. The localtime() function converts the given time since epoch to calendar time which is expressed as local time. Syntax: tm* localtime(const time_t* time_ptr); Parameter: This function accepts a parameter time_ptr which represents the pointer to time_t object. Return Value: This function returns a pointer to a tm object on success, Otherwise it returns NullPointerException. Below program illustrate the localtime() function in C++: Example:- // c++ program to demonstrate// example of localtime() function. #include <bits/stdc++.h>using namespace std; int main(){ time_t time_ptr; time_ptr = time(NULL); // Get the localtime tm* tm_local = localtime(&time_ptr); cout << "Current local time is = " << tm_local->tm_hour << ":" << tm_local->tm_min << ":" << tm_local->tm_sec; return 0;} Current local time is = 10:8:10 CPP-Functions CPP-Library C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Substring in C++ Sorting a vector in C++ 2D Vector In C++ With User Defined Size Templates in C++ with Examples Operator Overloading in C++ Multidimensional Arrays in C / C++
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2018" }, { "code": null, "e": 202, "s": 28, "text": "The localtime() function is defined in the ctime header file. The localtime() function converts the given time since epoch to calendar time which is expressed as local time." }, { "code": null, "e": 210, "s": 202, "text": "Syntax:" }, { "code": null, "e": 249, "s": 210, "text": "tm* localtime(const time_t* time_ptr);" }, { "code": null, "e": 350, "s": 249, "text": "Parameter: This function accepts a parameter time_ptr which represents the pointer to time_t object." }, { "code": null, "e": 466, "s": 350, "text": "Return Value: This function returns a pointer to a tm object on success, Otherwise it returns NullPointerException." }, { "code": null, "e": 524, "s": 466, "text": "Below program illustrate the localtime() function in C++:" }, { "code": null, "e": 534, "s": 524, "text": "Example:-" }, { "code": "// c++ program to demonstrate// example of localtime() function. #include <bits/stdc++.h>using namespace std; int main(){ time_t time_ptr; time_ptr = time(NULL); // Get the localtime tm* tm_local = localtime(&time_ptr); cout << \"Current local time is = \" << tm_local->tm_hour << \":\" << tm_local->tm_min << \":\" << tm_local->tm_sec; return 0;}", "e": 926, "s": 534, "text": null }, { "code": null, "e": 959, "s": 926, "text": "Current local time is = 10:8:10\n" }, { "code": null, "e": 973, "s": 959, "text": "CPP-Functions" }, { "code": null, "e": 985, "s": 973, "text": "CPP-Library" }, { "code": null, "e": 989, "s": 985, "text": "C++" }, { "code": null, "e": 993, "s": 989, "text": "CPP" }, { "code": null, "e": 1091, "s": 993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1134, "s": 1091, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 1168, "s": 1134, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1193, "s": 1168, "text": "unordered_map in C++ STL" }, { "code": null, "e": 1247, "s": 1193, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1264, "s": 1247, "text": "Substring in C++" }, { "code": null, "e": 1288, "s": 1264, "text": "Sorting a vector in C++" }, { "code": null, "e": 1328, "s": 1288, "text": "2D Vector In C++ With User Defined Size" }, { "code": null, "e": 1359, "s": 1328, "text": "Templates in C++ with Examples" }, { "code": null, "e": 1387, "s": 1359, "text": "Operator Overloading in C++" } ]
How to calculate number of days between two dates in R ?
16 Jul, 2021 In this article, we will discuss how to Find the number of days between two dates in the R programming language. Example: Input: Date_1 = 2020/03/21 Date_2 = 2020/03/22 Output: 1 Explanation: In Date_1 and Date_2 have only one difference in day.So output will be 1. Here we will use seq() function to get the result. This function is used to create a sequence of elements in a Vector. To get the number of days length() function is employed with seq() as an argument. Syntax: length(seq(from=date_1, to=date_2, by=’day’)) -1 Parameter: seq is function generates a sequence of numbers. from is starting date. to is ending date. by is step, increment. Example 1: R # creating date_1 variable# and storing date in it.date_1<-as.Date("2020-10-10") # creating date_2 variable# and storing date in it.date_2<-as.Date("2020-10-11").a = seq(from = date_1, to = date_2, by = 'day') # Here we are finding length of# a and we are subtracting 1 because# we dont need to include current day.length(a)-1 Output: 1 Example 2: R # creating date_1 variable# and storing date in it.date_1<-as.Date("2020-01-10") # creating date_2 variable# and storing date in it.date_2<-as.Date("2020-02-20") a = seq(from = date_1, to = date_2, by = 'day') # Here we are finding length of a# and we are subtracting 1 because we# dont need to include current day.length(a)-1 Output: 41 singghakshay Picked R-DateTime R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2021" }, { "code": null, "e": 142, "s": 28, "text": "In this article, we will discuss how to Find the number of days between two dates in the R programming language. " }, { "code": null, "e": 151, "s": 142, "text": "Example:" }, { "code": null, "e": 158, "s": 151, "text": "Input:" }, { "code": null, "e": 179, "s": 158, "text": " Date_1 = 2020/03/21" }, { "code": null, "e": 200, "s": 179, "text": " Date_2 = 2020/03/22" }, { "code": null, "e": 210, "s": 200, "text": "Output: 1" }, { "code": null, "e": 297, "s": 210, "text": "Explanation: In Date_1 and Date_2 have only one difference in day.So output will be 1." }, { "code": null, "e": 499, "s": 297, "text": "Here we will use seq() function to get the result. This function is used to create a sequence of elements in a Vector. To get the number of days length() function is employed with seq() as an argument." }, { "code": null, "e": 556, "s": 499, "text": "Syntax: length(seq(from=date_1, to=date_2, by=’day’)) -1" }, { "code": null, "e": 567, "s": 556, "text": "Parameter:" }, { "code": null, "e": 616, "s": 567, "text": "seq is function generates a sequence of numbers." }, { "code": null, "e": 639, "s": 616, "text": "from is starting date." }, { "code": null, "e": 658, "s": 639, "text": "to is ending date." }, { "code": null, "e": 681, "s": 658, "text": "by is step, increment." }, { "code": null, "e": 692, "s": 681, "text": "Example 1:" }, { "code": null, "e": 694, "s": 692, "text": "R" }, { "code": "# creating date_1 variable# and storing date in it.date_1<-as.Date(\"2020-10-10\") # creating date_2 variable# and storing date in it.date_2<-as.Date(\"2020-10-11\").a = seq(from = date_1, to = date_2, by = 'day') # Here we are finding length of# a and we are subtracting 1 because# we dont need to include current day.length(a)-1", "e": 1021, "s": 694, "text": null }, { "code": null, "e": 1029, "s": 1021, "text": "Output:" }, { "code": null, "e": 1031, "s": 1029, "text": "1" }, { "code": null, "e": 1042, "s": 1031, "text": "Example 2:" }, { "code": null, "e": 1044, "s": 1042, "text": "R" }, { "code": "# creating date_1 variable# and storing date in it.date_1<-as.Date(\"2020-01-10\") # creating date_2 variable# and storing date in it.date_2<-as.Date(\"2020-02-20\") a = seq(from = date_1, to = date_2, by = 'day') # Here we are finding length of a# and we are subtracting 1 because we# dont need to include current day.length(a)-1", "e": 1371, "s": 1044, "text": null }, { "code": null, "e": 1379, "s": 1371, "text": "Output:" }, { "code": null, "e": 1382, "s": 1379, "text": "41" }, { "code": null, "e": 1395, "s": 1382, "text": "singghakshay" }, { "code": null, "e": 1402, "s": 1395, "text": "Picked" }, { "code": null, "e": 1413, "s": 1402, "text": "R-DateTime" }, { "code": null, "e": 1424, "s": 1413, "text": "R Language" }, { "code": null, "e": 1522, "s": 1424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1574, "s": 1522, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1632, "s": 1574, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1667, "s": 1632, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1705, "s": 1667, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1754, "s": 1705, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1771, "s": 1754, "text": "R - if statement" }, { "code": null, "e": 1808, "s": 1771, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 1851, "s": 1808, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 1888, "s": 1851, "text": "How to import an Excel File into R ?" } ]
PHP | exit( ) Function
01 Aug, 2021 The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script.The exit() function only terminates the execution of the script. The shutdown functions and object destructors will always be executed even if exit() function is called.The message to be displayed is passed as a parameter to the exit() function and it terminates the script and displays the message.The exit() function is an alias of the die() function. Syntax: exit(message) Parameters Used:The exit() function in PHP accepts one parameter. message : It is a mandatory parameter which specifies the message or status number to write before exiting the script. message : It is a mandatory parameter which specifies the message or status number to write before exiting the script. Return Value: It does not return any value. Errors And Exceptions exit() is a language construct and it can be called without parentheses if no status is passed.If the status passed as a parameter is an integer, that value will be used as the exit status and not be printed.Exit statuses should be in the range 0 to 254 and the exit status 255 should not be used since it is reserved by PHP. exit() is a language construct and it can be called without parentheses if no status is passed. If the status passed as a parameter is an integer, that value will be used as the exit status and not be printed. Exit statuses should be in the range 0 to 254 and the exit status 255 should not be used since it is reserved by PHP. Below programs illustrate the exit() function: Program 1: <?php$link = "https://www.geeksforgeeks.org"; // opening a linkfopen($link, "r") //using exit() to display message and terminate scriptor exit("Unable to establish a connection to $link");?> Output: Unable to establish a connection to https://www.geeksforgeeks.org Program 2: <?php//declaring variables$a=5;$b=5.0; if($a==$b) { //terminating script with a message using exit() exit('variables are equal'); }else { //terminating script with a message using exit() exit('variables are not equal'); }?> Output: variables are equal Reference :http://php.net/manual/en/function.exit.php PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to get parameters from a URL string in PHP? Split a comma delimited string into an array in PHP Download file from URL using PHP 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": "\n01 Aug, 2021" }, { "code": null, "e": 499, "s": 28, "text": "The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script.The exit() function only terminates the execution of the script. The shutdown functions and object destructors will always be executed even if exit() function is called.The message to be displayed is passed as a parameter to the exit() function and it terminates the script and displays the message.The exit() function is an alias of the die() function." }, { "code": null, "e": 507, "s": 499, "text": "Syntax:" }, { "code": null, "e": 521, "s": 507, "text": "exit(message)" }, { "code": null, "e": 587, "s": 521, "text": "Parameters Used:The exit() function in PHP accepts one parameter." }, { "code": null, "e": 706, "s": 587, "text": "message : It is a mandatory parameter which specifies the message or status number to write before exiting the script." }, { "code": null, "e": 825, "s": 706, "text": "message : It is a mandatory parameter which specifies the message or status number to write before exiting the script." }, { "code": null, "e": 869, "s": 825, "text": "Return Value:\nIt does not return any value." }, { "code": null, "e": 891, "s": 869, "text": "Errors And Exceptions" }, { "code": null, "e": 1217, "s": 891, "text": "exit() is a language construct and it can be called without parentheses if no status is passed.If the status passed as a parameter is an integer, that value will be used as the exit status and not be printed.Exit statuses should be in the range 0 to 254 and the exit status 255 should not be used since it is reserved by PHP." }, { "code": null, "e": 1313, "s": 1217, "text": "exit() is a language construct and it can be called without parentheses if no status is passed." }, { "code": null, "e": 1427, "s": 1313, "text": "If the status passed as a parameter is an integer, that value will be used as the exit status and not be printed." }, { "code": null, "e": 1545, "s": 1427, "text": "Exit statuses should be in the range 0 to 254 and the exit status 255 should not be used since it is reserved by PHP." }, { "code": null, "e": 1592, "s": 1545, "text": "Below programs illustrate the exit() function:" }, { "code": null, "e": 1603, "s": 1592, "text": "Program 1:" }, { "code": "<?php$link = \"https://www.geeksforgeeks.org\"; // opening a linkfopen($link, \"r\") //using exit() to display message and terminate scriptor exit(\"Unable to establish a connection to $link\");?>", "e": 1796, "s": 1603, "text": null }, { "code": null, "e": 1804, "s": 1796, "text": "Output:" }, { "code": null, "e": 1871, "s": 1804, "text": "Unable to establish a connection to https://www.geeksforgeeks.org\n" }, { "code": null, "e": 1882, "s": 1871, "text": "Program 2:" }, { "code": "<?php//declaring variables$a=5;$b=5.0; if($a==$b) { //terminating script with a message using exit() exit('variables are equal'); }else { //terminating script with a message using exit() exit('variables are not equal'); }?>", "e": 2119, "s": 1882, "text": null }, { "code": null, "e": 2127, "s": 2119, "text": "Output:" }, { "code": null, "e": 2148, "s": 2127, "text": "variables are equal\n" }, { "code": null, "e": 2202, "s": 2148, "text": "Reference :http://php.net/manual/en/function.exit.php" }, { "code": null, "e": 2371, "s": 2202, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 2375, "s": 2371, "text": "PHP" }, { "code": null, "e": 2392, "s": 2375, "text": "Web Technologies" }, { "code": null, "e": 2396, "s": 2392, "text": "PHP" }, { "code": null, "e": 2494, "s": 2396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2534, "s": 2494, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2579, "s": 2534, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2627, "s": 2579, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 2679, "s": 2627, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 2712, "s": 2679, "text": "Download file from URL using PHP" }, { "code": null, "e": 2745, "s": 2712, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2807, "s": 2745, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2868, "s": 2807, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2918, "s": 2868, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Minimum number of swaps required to sort an array of first N number
16 Aug, 2021 Given an array arr[] of distinct integers from 1 to N. The task is to find the minimum number of swaps required to sort the array. Example: Input: arr[] = { 7, 1, 3, 2, 4, 5, 6 } Output: 5 Explanation: i arr swap (indices) 0 [7, 1, 3, 2, 4, 5, 6] swap (0, 3) 1 [2, 1, 3, 7, 4, 5, 6] swap (0, 1) 2 [1, 2, 3, 7, 4, 5, 6] swap (3, 4) 3 [1, 2, 3, 4, 7, 5, 6] swap (4, 5) 4 [1, 2, 3, 4, 5, 7, 6] swap (5, 6) 5 [1, 2, 3, 4, 5, 6, 7] Therefore, total number of swaps = 5 Input: arr[] = { 2, 3, 4, 1, 5 } Output: 3 Approach: For each index in arr[]. Check if the current element is in it’s right position or not. Since the array contains distinct elements from 1 to N, we can simply compare the element with it’s index in array to check if it is at its right position. If current element is not at it’s right position then swap the element with the element which has occupied its place. Else check for next index. Below is the implementation of the above approach: C++ Java Python3 C# Javascript #include <iostream>using namespace std; // Function to find minimum swapsint minimumSwaps(int arr[],int n){ // Initialise count variable int count = 0; int i = 0; while (i < n) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count;} // Driver codeint main(){ int arr[] = { 2, 3, 4, 1, 5 }; int n = sizeof(arr)/sizeof(arr[0]); // Function to find minimum swaps cout << minimumSwaps(arr,n) ;} // This code is contributed by AnkitRai01 // Java program to find the minimum// number of swaps required to sort// the given arrayimport java.io.*;import java.util.*; class GfG { // Function to find minimum swaps static int minimumSwaps(int[] arr) { // Initialise count variable int count = 0; int i = 0; while (i < arr.length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count; } // Driver code public static void main(String[] args) { int arr[] = { 2, 3, 4, 1, 5 }; // Function to find minimum swaps System.out.println(minimumSwaps(arr)); }} # Python3 program to find the minimum# number of swaps required to sort# the given array # Function to find minimum swapsdef minimumSwaps(arr): # Initialise count variable count = 0; i = 0; while (i < len(arr)): # If current element is # not at the right position if (arr[i] != i + 1): while (arr[i] != i + 1): temp = 0; # Swap current element # with correct position # of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count += 1; # Increment for next index # when current element is at # correct position i += 1; return count; # Driver codeif __name__ == '__main__': arr = [ 2, 3, 4, 1, 5 ]; # Function to find minimum swaps print(minimumSwaps(arr)); # This code is contributed by 29AjayKumar // C# program to find the minimum// number of swaps required to sort// the given arrayusing System; class GfG{ // Function to find minimum swaps static int minimumSwaps(int[] arr) { // Initialise count variable int count = 0; int i = 0; while (i < arr.Length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count; } // Driver code public static void Main(String[] args) { int []arr = { 2, 3, 4, 1, 5 }; // Function to find minimum swaps Console.WriteLine(minimumSwaps(arr)); }} // This code is contributed by 29AjayKumar <script> // javascript program to find the minimum// number of swaps required to sort// the given array // Function to find minimum swapsfunction minimumSwaps(arr){ // Initialise count variable let count = 0; let i = 0; while (i < arr.length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { let temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count;} // Driver code let arr = [2, 3, 4, 1, 5 ]; // Function to find minimum swapsdocument.write(minimumSwaps(arr)); </script> 3 Time Complexity: O(N) where N is the size of array. Auxiliary Space: O(1) 29AjayKumar ankthon mohit kumar 29 anikakapoor Natural Numbers Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Introduction to Data Structures Find Second largest element in an array Search an element in a sorted and rotated array Window Sliding Technique Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Aug, 2021" }, { "code": null, "e": 187, "s": 54, "text": "Given an array arr[] of distinct integers from 1 to N. The task is to find the minimum number of swaps required to sort the array. " }, { "code": null, "e": 198, "s": 187, "text": "Example: " }, { "code": null, "e": 610, "s": 198, "text": "Input: arr[] = { 7, 1, 3, 2, 4, 5, 6 }\nOutput: 5\nExplanation:\ni arr swap (indices)\n0 [7, 1, 3, 2, 4, 5, 6] swap (0, 3)\n1 [2, 1, 3, 7, 4, 5, 6] swap (0, 1)\n2 [1, 2, 3, 7, 4, 5, 6] swap (3, 4)\n3 [1, 2, 3, 4, 7, 5, 6] swap (4, 5)\n4 [1, 2, 3, 4, 5, 7, 6] swap (5, 6)\n5 [1, 2, 3, 4, 5, 6, 7]\nTherefore, total number of swaps = 5\n\nInput: arr[] = { 2, 3, 4, 1, 5 }\nOutput: 3" }, { "code": null, "e": 624, "s": 612, "text": "Approach: " }, { "code": null, "e": 649, "s": 624, "text": "For each index in arr[]." }, { "code": null, "e": 868, "s": 649, "text": "Check if the current element is in it’s right position or not. Since the array contains distinct elements from 1 to N, we can simply compare the element with it’s index in array to check if it is at its right position." }, { "code": null, "e": 986, "s": 868, "text": "If current element is not at it’s right position then swap the element with the element which has occupied its place." }, { "code": null, "e": 1013, "s": 986, "text": "Else check for next index." }, { "code": null, "e": 1066, "s": 1013, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1070, "s": 1066, "text": "C++" }, { "code": null, "e": 1075, "s": 1070, "text": "Java" }, { "code": null, "e": 1083, "s": 1075, "text": "Python3" }, { "code": null, "e": 1086, "s": 1083, "text": "C#" }, { "code": null, "e": 1097, "s": 1086, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // Function to find minimum swapsint minimumSwaps(int arr[],int n){ // Initialise count variable int count = 0; int i = 0; while (i < n) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count;} // Driver codeint main(){ int arr[] = { 2, 3, 4, 1, 5 }; int n = sizeof(arr)/sizeof(arr[0]); // Function to find minimum swaps cout << minimumSwaps(arr,n) ;} // This code is contributed by AnkitRai01", "e": 2103, "s": 1097, "text": null }, { "code": "// Java program to find the minimum// number of swaps required to sort// the given arrayimport java.io.*;import java.util.*; class GfG { // Function to find minimum swaps static int minimumSwaps(int[] arr) { // Initialise count variable int count = 0; int i = 0; while (i < arr.length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count; } // Driver code public static void main(String[] args) { int arr[] = { 2, 3, 4, 1, 5 }; // Function to find minimum swaps System.out.println(minimumSwaps(arr)); }}", "e": 3282, "s": 2103, "text": null }, { "code": "# Python3 program to find the minimum# number of swaps required to sort# the given array # Function to find minimum swapsdef minimumSwaps(arr): # Initialise count variable count = 0; i = 0; while (i < len(arr)): # If current element is # not at the right position if (arr[i] != i + 1): while (arr[i] != i + 1): temp = 0; # Swap current element # with correct position # of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count += 1; # Increment for next index # when current element is at # correct position i += 1; return count; # Driver codeif __name__ == '__main__': arr = [ 2, 3, 4, 1, 5 ]; # Function to find minimum swaps print(minimumSwaps(arr)); # This code is contributed by 29AjayKumar", "e": 4243, "s": 3282, "text": null }, { "code": "// C# program to find the minimum// number of swaps required to sort// the given arrayusing System; class GfG{ // Function to find minimum swaps static int minimumSwaps(int[] arr) { // Initialise count variable int count = 0; int i = 0; while (i < arr.Length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { int temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count; } // Driver code public static void Main(String[] args) { int []arr = { 2, 3, 4, 1, 5 }; // Function to find minimum swaps Console.WriteLine(minimumSwaps(arr)); }} // This code is contributed by 29AjayKumar", "e": 5471, "s": 4243, "text": null }, { "code": "<script> // javascript program to find the minimum// number of swaps required to sort// the given array // Function to find minimum swapsfunction minimumSwaps(arr){ // Initialise count variable let count = 0; let i = 0; while (i < arr.length) { // If current element is // not at the right position if (arr[i] != i + 1) { while (arr[i] != i + 1) { let temp = 0; // Swap current element // with correct position // of that element temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; count++; } } // Increment for next index // when current element is at // correct position i++; } return count;} // Driver code let arr = [2, 3, 4, 1, 5 ]; // Function to find minimum swapsdocument.write(minimumSwaps(arr)); </script>", "e": 6442, "s": 5471, "text": null }, { "code": null, "e": 6444, "s": 6442, "text": "3" }, { "code": null, "e": 6520, "s": 6446, "text": "Time Complexity: O(N) where N is the size of array. Auxiliary Space: O(1)" }, { "code": null, "e": 6532, "s": 6520, "text": "29AjayKumar" }, { "code": null, "e": 6540, "s": 6532, "text": "ankthon" }, { "code": null, "e": 6555, "s": 6540, "text": "mohit kumar 29" }, { "code": null, "e": 6567, "s": 6555, "text": "anikakapoor" }, { "code": null, "e": 6583, "s": 6567, "text": "Natural Numbers" }, { "code": null, "e": 6590, "s": 6583, "text": "Arrays" }, { "code": null, "e": 6598, "s": 6590, "text": "Sorting" }, { "code": null, "e": 6605, "s": 6598, "text": "Arrays" }, { "code": null, "e": 6613, "s": 6605, "text": "Sorting" }, { "code": null, "e": 6711, "s": 6613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6734, "s": 6711, "text": "Introduction to Arrays" }, { "code": null, "e": 6766, "s": 6734, "text": "Introduction to Data Structures" }, { "code": null, "e": 6806, "s": 6766, "text": "Find Second largest element in an array" }, { "code": null, "e": 6854, "s": 6806, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 6879, "s": 6854, "text": "Window Sliding Technique" }, { "code": null, "e": 6890, "s": 6879, "text": "Merge Sort" }, { "code": null, "e": 6912, "s": 6890, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 6922, "s": 6912, "text": "QuickSort" }, { "code": null, "e": 6937, "s": 6922, "text": "Insertion Sort" } ]
ML – Swish Function by Google in Keras
26 May, 2020 ReLU has been the best activation function in the deep learning community for a long time, but Google’s brain team announced Swish as an alternative to ReLU in 2017. Research by the authors of the papers shows that simply be substituting ReLU units with Swish units improves the classification accuracy on ImageNet by 0.6% for Inception-ResNet-v2, hence, it outperforms ReLU in many deep neural nets. Swish Activation function: Mathematical formula: Y = X * sigmoid(X) Bounded below but Unbounded above: Y approach to constant value at X approaches negative infinity but Y approach to infinity as X approaches infinity. Derivative of Swish, Y’ = Y + sigmoid(X) * (1-Y) Soft curve and non-monotonic function. Swish vs ReLU Advantages over RelU Activation Function: Having no bounds is desirable for activation functions as it avoids problems when gradients are nearly zero. The ReLU function is bounded above but when we consider the below region then being bounded below may regularize the model up to an extent, also functions that approach zero in a limit to negative infinity are great at regularization because large negative inputs are discarded. The swish function provides it along with being non-monotonous which enhances the expression of input data and weight to be learnt.Below is the performance metric of Swish function over many community dominant activation functions like ReLU, SeLU, Leaky ReLU and others. Implementation of Swish activation function in keras:Swish is implemented as a custom function in Keras, which after defining has to be registered with a key in the Activation Class. Code: # Code from between to demonstrate the implementation of Swish # Our aim is to use "swish" in place of "relu" and make compiler understand itmodel.add(Dense(64, activation = "relu"))model.add(Dense(16, activation = "relu")) Now We will be creating a custom function named Swish which can give the output according to the mathematical formula of Swish activation function as follows: # Importing the sigmoid function from# Keras backend and using itfrom keras.backend import sigmoid def swish(x, beta = 1): return (x * sigmoid(beta * x)) Now as we have the custom-designed function which can process the input as Swish activation, we need to register this custom object with Keras. For this, we pass it in a dictionary with a key of what we want to call it and the activation function for it. The Activation class will actually build the function. Code: # Getting the Custom object and updating themfrom keras.utils.generic_utils import get_custom_objectsfrom keras.layers import Activation # Below in place of swish you can take any custom key for the name get_custom_objects().update({'swish': Activation(swish)}) Code: Implementing the custom-designed activation function model.add(Dense(64, activation = "swish"))model.add(Dense(16, activation = "swish")) Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Introduction to Recurrent Neural Network Markov Decision Process Support Vector Machine Algorithm DBSCAN Clustering in ML | Density based clustering Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2020" }, { "code": null, "e": 429, "s": 28, "text": "ReLU has been the best activation function in the deep learning community for a long time, but Google’s brain team announced Swish as an alternative to ReLU in 2017. Research by the authors of the papers shows that simply be substituting ReLU units with Swish units improves the classification accuracy on ImageNet by 0.6% for Inception-ResNet-v2, hence, it outperforms ReLU in many deep neural nets." }, { "code": null, "e": 456, "s": 429, "text": "Swish Activation function:" }, { "code": null, "e": 497, "s": 456, "text": "Mathematical formula: Y = X * sigmoid(X)" }, { "code": null, "e": 648, "s": 497, "text": "Bounded below but Unbounded above: Y approach to constant value at X approaches negative infinity but Y approach to infinity as X approaches infinity." }, { "code": null, "e": 697, "s": 648, "text": "Derivative of Swish, Y’ = Y + sigmoid(X) * (1-Y)" }, { "code": null, "e": 736, "s": 697, "text": "Soft curve and non-monotonic function." }, { "code": null, "e": 750, "s": 736, "text": "Swish vs ReLU" }, { "code": null, "e": 792, "s": 750, "text": "Advantages over RelU Activation Function:" }, { "code": null, "e": 1451, "s": 792, "text": "Having no bounds is desirable for activation functions as it avoids problems when gradients are nearly zero. The ReLU function is bounded above but when we consider the below region then being bounded below may regularize the model up to an extent, also functions that approach zero in a limit to negative infinity are great at regularization because large negative inputs are discarded. The swish function provides it along with being non-monotonous which enhances the expression of input data and weight to be learnt.Below is the performance metric of Swish function over many community dominant activation functions like ReLU, SeLU, Leaky ReLU and others." }, { "code": null, "e": 1634, "s": 1451, "text": "Implementation of Swish activation function in keras:Swish is implemented as a custom function in Keras, which after defining has to be registered with a key in the Activation Class." }, { "code": null, "e": 1640, "s": 1634, "text": "Code:" }, { "code": "# Code from between to demonstrate the implementation of Swish # Our aim is to use \"swish\" in place of \"relu\" and make compiler understand itmodel.add(Dense(64, activation = \"relu\"))model.add(Dense(16, activation = \"relu\"))", "e": 1865, "s": 1640, "text": null }, { "code": null, "e": 2024, "s": 1865, "text": "Now We will be creating a custom function named Swish which can give the output according to the mathematical formula of Swish activation function as follows:" }, { "code": "# Importing the sigmoid function from# Keras backend and using itfrom keras.backend import sigmoid def swish(x, beta = 1): return (x * sigmoid(beta * x))", "e": 2182, "s": 2024, "text": null }, { "code": null, "e": 2492, "s": 2182, "text": "Now as we have the custom-designed function which can process the input as Swish activation, we need to register this custom object with Keras. For this, we pass it in a dictionary with a key of what we want to call it and the activation function for it. The Activation class will actually build the function." }, { "code": null, "e": 2498, "s": 2492, "text": "Code:" }, { "code": "# Getting the Custom object and updating themfrom keras.utils.generic_utils import get_custom_objectsfrom keras.layers import Activation # Below in place of swish you can take any custom key for the name get_custom_objects().update({'swish': Activation(swish)})", "e": 2761, "s": 2498, "text": null }, { "code": null, "e": 2820, "s": 2761, "text": "Code: Implementing the custom-designed activation function" }, { "code": "model.add(Dense(64, activation = \"swish\"))model.add(Dense(16, activation = \"swish\"))", "e": 2905, "s": 2820, "text": null }, { "code": null, "e": 2922, "s": 2905, "text": "Machine Learning" }, { "code": null, "e": 2929, "s": 2922, "text": "Python" }, { "code": null, "e": 2946, "s": 2929, "text": "Machine Learning" }, { "code": null, "e": 3044, "s": 2946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3080, "s": 3044, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 3121, "s": 3080, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 3145, "s": 3121, "text": "Markov Decision Process" }, { "code": null, "e": 3178, "s": 3145, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 3229, "s": 3178, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 3257, "s": 3229, "text": "Read JSON file using Python" }, { "code": null, "e": 3307, "s": 3257, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3329, "s": 3307, "text": "Python map() function" } ]
Java Program to Demonstrate the Call By Value
28 Jan, 2022 Functions can be summoned in two ways: Call by Value and Call by Reference. Call by Value method parameters values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value where actual value does not change User cases: Calling methods in programming where the method needs to be called for using its functionality. There can be three situations when a method is called or the method returns to the code that invoked it in conditions depicted below: It completes all the statements in the methodIt reaches a return statementThrows an exception It completes all the statements in the method It reaches a return statement Throws an exception Remember: Java is Call By Value always Implementation: Swapping of numbers is called by value is taken as example to illustrate call by value method Example 1: illustrates the swapping of numbers by creating an auxiliary space in memory known as temporary variable Java // Java Program showcasing uses of call by value in examples // Importing java input output classesimport java.io.*; // Classpublic class GFG { // Method to swap numbers static void swap(int a, int b) { // Creating a temporary variable in stack memory // and updating values in it. // Step 1 int temp = a; // Step 2 a = b; // Step 3 b = temp; // This variables vanishes as scope is over } // Main driver method public static void main(String[] args) { // Custom inputs/numbers to be swapped int x = 5; int y = 7; // Display message before swapping numbers System.out.println("before swapping x = " + x + " and y = " + y); // Using above created method to swap numbers swap(x, y); // Display message after swapping numbers System.out.println("after swapping x = " + x + " and y = " + y); }} before swapping x = 5 and y = 7 after swapping x = 5 and y = 7 Output explanation: After calling method swap(5,7), integer values 5 and 7 are got copied into another variable. That’s why original value does not change. Example 2: illustrates the swapping of numbers by sum and deletion mathematics computations without creating any auxiliary space. Java // Java Program showcasing uses of call by value in examples // Importing java input output classesimport java.io.*; // Classclass GFG { // Method to update value when called in main method static void change(int a) { // Random updation a = a + 50; } // Main driver method public static void main(String[] args) { // Random assassination int a = 30; // Printing value of variable // before calling change() method System.out.println("before change a = " + a); // Calling above method in main() method change(a); // Printing value of variable // after calling change() method System.out.println("after change a = " + a); }} before change a = 30 after change a = 30 surinderdawra388 surindertarika1234 saurabh1990aror Java Java Programs 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 Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jan, 2022" }, { "code": null, "e": 309, "s": 52, "text": " Functions can be summoned in two ways: Call by Value and Call by Reference. Call by Value method parameters values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value where actual value does not change" }, { "code": null, "e": 551, "s": 309, "text": "User cases: Calling methods in programming where the method needs to be called for using its functionality. There can be three situations when a method is called or the method returns to the code that invoked it in conditions depicted below:" }, { "code": null, "e": 645, "s": 551, "text": "It completes all the statements in the methodIt reaches a return statementThrows an exception" }, { "code": null, "e": 691, "s": 645, "text": "It completes all the statements in the method" }, { "code": null, "e": 721, "s": 691, "text": "It reaches a return statement" }, { "code": null, "e": 741, "s": 721, "text": "Throws an exception" }, { "code": null, "e": 780, "s": 741, "text": "Remember: Java is Call By Value always" }, { "code": null, "e": 891, "s": 780, "text": " Implementation: Swapping of numbers is called by value is taken as example to illustrate call by value method" }, { "code": null, "e": 1007, "s": 891, "text": "Example 1: illustrates the swapping of numbers by creating an auxiliary space in memory known as temporary variable" }, { "code": null, "e": 1012, "s": 1007, "text": "Java" }, { "code": "// Java Program showcasing uses of call by value in examples // Importing java input output classesimport java.io.*; // Classpublic class GFG { // Method to swap numbers static void swap(int a, int b) { // Creating a temporary variable in stack memory // and updating values in it. // Step 1 int temp = a; // Step 2 a = b; // Step 3 b = temp; // This variables vanishes as scope is over } // Main driver method public static void main(String[] args) { // Custom inputs/numbers to be swapped int x = 5; int y = 7; // Display message before swapping numbers System.out.println(\"before swapping x = \" + x + \" and y = \" + y); // Using above created method to swap numbers swap(x, y); // Display message after swapping numbers System.out.println(\"after swapping x = \" + x + \" and y = \" + y); }}", "e": 2012, "s": 1012, "text": null }, { "code": null, "e": 2076, "s": 2012, "text": "before swapping x = 5 and y = 7\nafter swapping x = 5 and y = 7\n" }, { "code": null, "e": 2232, "s": 2076, "text": "Output explanation: After calling method swap(5,7), integer values 5 and 7 are got copied into another variable. That’s why original value does not change." }, { "code": null, "e": 2362, "s": 2232, "text": "Example 2: illustrates the swapping of numbers by sum and deletion mathematics computations without creating any auxiliary space." }, { "code": null, "e": 2367, "s": 2362, "text": "Java" }, { "code": "// Java Program showcasing uses of call by value in examples // Importing java input output classesimport java.io.*; // Classclass GFG { // Method to update value when called in main method static void change(int a) { // Random updation a = a + 50; } // Main driver method public static void main(String[] args) { // Random assassination int a = 30; // Printing value of variable // before calling change() method System.out.println(\"before change a = \" + a); // Calling above method in main() method change(a); // Printing value of variable // after calling change() method System.out.println(\"after change a = \" + a); }}", "e": 3106, "s": 2367, "text": null }, { "code": null, "e": 3147, "s": 3106, "text": "before change a = 30\nafter change a = 30" }, { "code": null, "e": 3164, "s": 3147, "text": "surinderdawra388" }, { "code": null, "e": 3183, "s": 3164, "text": "surindertarika1234" }, { "code": null, "e": 3199, "s": 3183, "text": "saurabh1990aror" }, { "code": null, "e": 3204, "s": 3199, "text": "Java" }, { "code": null, "e": 3218, "s": 3204, "text": "Java Programs" }, { "code": null, "e": 3223, "s": 3218, "text": "Java" }, { "code": null, "e": 3321, "s": 3223, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3336, "s": 3321, "text": "Stream In Java" }, { "code": null, "e": 3357, "s": 3336, "text": "Introduction to Java" }, { "code": null, "e": 3378, "s": 3357, "text": "Constructors in Java" }, { "code": null, "e": 3397, "s": 3378, "text": "Exceptions in Java" }, { "code": null, "e": 3414, "s": 3397, "text": "Generics in Java" }, { "code": null, "e": 3440, "s": 3414, "text": "Java Programming Examples" }, { "code": null, "e": 3474, "s": 3440, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3521, "s": 3474, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3559, "s": 3521, "text": "Factory method design pattern in Java" } ]
Ruby | Array reverse() function
06 Dec, 2019 Array#reverse() : reverse() is a Array class method which returns a new array containing self’s elements in reverse order. Syntax: Array.reverse() Parameter: Array Return: a new array containing self’s elements in reverse order. Example #1 : # Ruby code for reverse() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # reverse method exampleputs "reverse() method form : #{a.reverse()}\n\n" puts "reverse() method form : #{b.reverse()}\n\n" puts "reverse() method form : #{c.reverse()}\n\n" Output : reverse() method form : [6, 5, nil, 33, 22, 18] reverse() method form : [9, 88, 1, 1, 4, 1] reverse() method form : [6, 50, 22, 18] Example #2 : # Ruby code for reverse() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayc = ["cat", nil] # declaring arrayb = ["cow", nil, "dog"] # reverse method exampleputs "reverse() method form : #{a.reverse()}\n\n" puts "reverse() method form : #{b.reverse()}\n\n" puts "reverse() method form : #{c.reverse()}\n\n" Output : reverse() method form : ["dog", "nil", "abc"] reverse() method form : ["dog", nil, "cow"] reverse() method form : [nil, "cat"] Ruby Array-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Array count() operation Include v/s Extend in Ruby Global Variable in Ruby Ruby | Array select() function Ruby | Data Types Ruby | Enumerator each_with_index function Ruby | Hash delete() function Ruby | Case Statement Ruby | String gsub! Method
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2019" }, { "code": null, "e": 151, "s": 28, "text": "Array#reverse() : reverse() is a Array class method which returns a new array containing self’s elements in reverse order." }, { "code": null, "e": 175, "s": 151, "text": "Syntax: Array.reverse()" }, { "code": null, "e": 192, "s": 175, "text": "Parameter: Array" }, { "code": null, "e": 257, "s": 192, "text": "Return: a new array containing self’s elements in reverse order." }, { "code": null, "e": 270, "s": 257, "text": "Example #1 :" }, { "code": "# Ruby code for reverse() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # reverse method exampleputs \"reverse() method form : #{a.reverse()}\\n\\n\" puts \"reverse() method form : #{b.reverse()}\\n\\n\" puts \"reverse() method form : #{c.reverse()}\\n\\n\"", "e": 606, "s": 270, "text": null }, { "code": null, "e": 615, "s": 606, "text": "Output :" }, { "code": null, "e": 751, "s": 615, "text": "reverse() method form : [6, 5, nil, 33, 22, 18]\n\nreverse() method form : [9, 88, 1, 1, 4, 1]\n\nreverse() method form : [6, 50, 22, 18]\n\n" }, { "code": null, "e": 764, "s": 751, "text": "Example #2 :" }, { "code": "# Ruby code for reverse() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayc = [\"cat\", nil] # declaring arrayb = [\"cow\", nil, \"dog\"] # reverse method exampleputs \"reverse() method form : #{a.reverse()}\\n\\n\" puts \"reverse() method form : #{b.reverse()}\\n\\n\" puts \"reverse() method form : #{c.reverse()}\\n\\n\"", "e": 1095, "s": 764, "text": null }, { "code": null, "e": 1104, "s": 1095, "text": "Output :" }, { "code": null, "e": 1235, "s": 1104, "text": "reverse() method form : [\"dog\", \"nil\", \"abc\"]\n\nreverse() method form : [\"dog\", nil, \"cow\"]\n\nreverse() method form : [nil, \"cat\"]\n\n" }, { "code": null, "e": 1252, "s": 1235, "text": "Ruby Array-class" }, { "code": null, "e": 1265, "s": 1252, "text": "Ruby-Methods" }, { "code": null, "e": 1270, "s": 1265, "text": "Ruby" }, { "code": null, "e": 1368, "s": 1270, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1414, "s": 1368, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 1445, "s": 1414, "text": "Ruby | Array count() operation" }, { "code": null, "e": 1472, "s": 1445, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 1496, "s": 1472, "text": "Global Variable in Ruby" }, { "code": null, "e": 1527, "s": 1496, "text": "Ruby | Array select() function" }, { "code": null, "e": 1545, "s": 1527, "text": "Ruby | Data Types" }, { "code": null, "e": 1588, "s": 1545, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 1618, "s": 1588, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 1640, "s": 1618, "text": "Ruby | Case Statement" } ]
Python | Decimal to binary list conversion
26 Feb, 2019 The conversion of a binary list to a decimal number has been dealt in a previous article. This article aims at presenting certain shorthand to do the opposite, i.e binary to decimal conversion. Let’s discuss certain ways in which this can be done. Method #1 : Using list comprehension + format()In this method, the conversion of the decimal to binary is handled by the format function. The logic of conversion to the list is done by the list comprehension function. # Python3 code to demonstrate # decimal to binary number conversion# using format() + list comprehension # initializing number test_num = 38 # printing original numberprint ("The original number is : " + str(test_num)) # using format() + list comprehension# decimal to binary number conversion res = [int(i) for i in list('{0:0b}'.format(test_num))] # printing result print ("The converted binary list is : " + str(res)) The original number is : 38 The converted binary list is : [1, 0, 0, 1, 1, 0] Method #2 : Using bin() + list comprehensionThe inbuilt function bin performs the function of conversion to binary and the list comprehension handles the logic to convert the binary number to the list. # Python3 code to demonstrate # decimal to binary number conversion# using bin() + list comprehension # initializing number test_num = 38 # printing original numberprint ("The original number is : " + str(test_num)) # using bin() + list comprehension# decimal to binary number conversion res = [int(i) for i in bin(test_num)[2:]] # printing result print ("The converted binary list is : " + str(res)) The original number is : 38 The converted binary list is : [1, 0, 0, 1, 1, 0] Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Feb, 2019" }, { "code": null, "e": 276, "s": 28, "text": "The conversion of a binary list to a decimal number has been dealt in a previous article. This article aims at presenting certain shorthand to do the opposite, i.e binary to decimal conversion. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 494, "s": 276, "text": "Method #1 : Using list comprehension + format()In this method, the conversion of the decimal to binary is handled by the format function. The logic of conversion to the list is done by the list comprehension function." }, { "code": "# Python3 code to demonstrate # decimal to binary number conversion# using format() + list comprehension # initializing number test_num = 38 # printing original numberprint (\"The original number is : \" + str(test_num)) # using format() + list comprehension# decimal to binary number conversion res = [int(i) for i in list('{0:0b}'.format(test_num))] # printing result print (\"The converted binary list is : \" + str(res))", "e": 920, "s": 494, "text": null }, { "code": null, "e": 999, "s": 920, "text": "The original number is : 38\nThe converted binary list is : [1, 0, 0, 1, 1, 0]\n" }, { "code": null, "e": 1202, "s": 999, "text": " Method #2 : Using bin() + list comprehensionThe inbuilt function bin performs the function of conversion to binary and the list comprehension handles the logic to convert the binary number to the list." }, { "code": "# Python3 code to demonstrate # decimal to binary number conversion# using bin() + list comprehension # initializing number test_num = 38 # printing original numberprint (\"The original number is : \" + str(test_num)) # using bin() + list comprehension# decimal to binary number conversion res = [int(i) for i in bin(test_num)[2:]] # printing result print (\"The converted binary list is : \" + str(res))", "e": 1608, "s": 1202, "text": null }, { "code": null, "e": 1687, "s": 1608, "text": "The original number is : 38\nThe converted binary list is : [1, 0, 0, 1, 1, 0]\n" }, { "code": null, "e": 1694, "s": 1687, "text": "Python" }, { "code": null, "e": 1710, "s": 1694, "text": "Python Programs" }, { "code": null, "e": 1808, "s": 1710, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1826, "s": 1808, "text": "Python Dictionary" }, { "code": null, "e": 1868, "s": 1826, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1890, "s": 1868, "text": "Enumerate() in Python" }, { "code": null, "e": 1925, "s": 1890, "text": "Read a file line by line in Python" }, { "code": null, "e": 1957, "s": 1925, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2000, "s": 1957, "text": "Python program to convert a list to string" }, { "code": null, "e": 2022, "s": 2000, "text": "Defaultdict in Python" }, { "code": null, "e": 2061, "s": 2022, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2099, "s": 2061, "text": "Python | Convert a list to dictionary" } ]
How to add icons in project using Bootstrap ?
14 Feb, 2022 Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites. An icon is a visual representation that helps to understand the website & also helps to navigate through the website. In order words, an icon is a cue the specifies the particular task for which the icon is used, is to be performed. The Bootstrap icons decorate the webpage/website in a standard format that gives a nice look. A bootstrap icon library contains over 1300 icons with a high-quality design & free to use. In order to use such icons, we will use the Bootstrap CDN link to include it in the HTML document. Syntax: <i class="bi bi-icon_name"></i> <link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css”/> Bootstrap Font Icon CSS link: <link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css” /> Approach: Go to the official site of Bootstrap & copy the Bootstrap CDN for CSS, JS, Popper.js, and jQuery links. Add the CDN link along with add font icon link inside the <head> tag Add the class with bi bi-icon_name followed by the name of the icon. Example 1: This example illustrates the Globe Icon. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1" /> <title>Bootstrap Icons in HTML</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" /> <!-- Bootstrap Font Icon CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" /></head> <body> <center> <h1 style="color: green"> Geeks For Geeks </h1> <h1 class="m-4">Globe Icon: <i class="bi-globe"></i> </h1> </center></body> </html> Output: Example 2: This example illustrates the Search Icon. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1" /> <title>Bootstrap Icons in HTML</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" /> <!-- Bootstrap Font Icon CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" /></head> <body> <center> <h1 style="color: green"> Geeks For Geeks </h1> <h1 class="m-4">Search Icon: <i class="bi-search"></i> </h1> </center></body> </html> Output: Example 3: This example illustrates the Alarm Icon. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1" /> <title>Bootstrap Icons in HTML</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" /> <!-- Bootstrap Font Icon CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" /></head> <body style="margin-top: 45px"> <center> <h1 style="color: green"> Geeks For Geeks </h1> <h1 class="m-4">Alarm Icon: <i class="bi-alarm"></i> </h1> </center></body> </html> Output: Example 4: This example illustrates the Cart Icon. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1" /> <title>Bootstrap Icons in HTML</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" /> <!-- Bootstrap Font Icon CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" /></head> <body> <center> <h1 style="color: green"> Geeks For Geeks </h1> <h1 class="m-4">Cart Icon: <i class="bi-cart"></i> </h1> </center></body> </html> Output: Reference: https://icons.getbootstrap.com/ rkbhola5 Bootstrap-4 Bootstrap-Questions HTML-Questions Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set vertical alignment in Bootstrap ? Tailwind CSS vs Bootstrap How to toggle password visibility in forms using Bootstrap-icons ? 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": 52, "s": 24, "text": "\n14 Feb, 2022" }, { "code": null, "e": 787, "s": 52, "text": "Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites. An icon is a visual representation that helps to understand the website & also helps to navigate through the website. In order words, an icon is a cue the specifies the particular task for which the icon is used, is to be performed. The Bootstrap icons decorate the webpage/website in a standard format that gives a nice look. A bootstrap icon library contains over 1300 icons with a high-quality design & free to use. In order to use such icons, we will use the Bootstrap CDN link to include it in the HTML document. " }, { "code": null, "e": 795, "s": 787, "text": "Syntax:" }, { "code": null, "e": 827, "s": 795, "text": "<i class=\"bi bi-icon_name\"></i>" }, { "code": null, "e": 931, "s": 827, "text": "<link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css”/>" }, { "code": null, "e": 961, "s": 931, "text": "Bootstrap Font Icon CSS link:" }, { "code": null, "e": 1070, "s": 961, "text": "<link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css” />" }, { "code": null, "e": 1080, "s": 1070, "text": "Approach:" }, { "code": null, "e": 1184, "s": 1080, "text": "Go to the official site of Bootstrap & copy the Bootstrap CDN for CSS, JS, Popper.js, and jQuery links." }, { "code": null, "e": 1254, "s": 1184, "text": "Add the CDN link along with add font icon link inside the <head> tag" }, { "code": null, "e": 1323, "s": 1254, "text": "Add the class with bi bi-icon_name followed by the name of the icon." }, { "code": null, "e": 1375, "s": 1323, "text": "Example 1: This example illustrates the Globe Icon." }, { "code": null, "e": 1380, "s": 1375, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\" /> <title>Bootstrap Icons in HTML</title> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" /> <!-- Bootstrap Font Icon CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css\" /></head> <body> <center> <h1 style=\"color: green\"> Geeks For Geeks </h1> <h1 class=\"m-4\">Globe Icon: <i class=\"bi-globe\"></i> </h1> </center></body> </html>", "e": 2076, "s": 1380, "text": null }, { "code": null, "e": 2084, "s": 2076, "text": "Output:" }, { "code": null, "e": 2137, "s": 2084, "text": "Example 2: This example illustrates the Search Icon." }, { "code": null, "e": 2142, "s": 2137, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\" /> <title>Bootstrap Icons in HTML</title> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" /> <!-- Bootstrap Font Icon CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css\" /></head> <body> <center> <h1 style=\"color: green\"> Geeks For Geeks </h1> <h1 class=\"m-4\">Search Icon: <i class=\"bi-search\"></i> </h1> </center></body> </html>", "e": 2848, "s": 2142, "text": null }, { "code": null, "e": 2856, "s": 2848, "text": "Output:" }, { "code": null, "e": 2908, "s": 2856, "text": "Example 3: This example illustrates the Alarm Icon." }, { "code": null, "e": 2913, "s": 2908, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\" /> <title>Bootstrap Icons in HTML</title> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" /> <!-- Bootstrap Font Icon CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css\" /></head> <body style=\"margin-top: 45px\"> <center> <h1 style=\"color: green\"> Geeks For Geeks </h1> <h1 class=\"m-4\">Alarm Icon: <i class=\"bi-alarm\"></i> </h1> </center></body> </html>", "e": 3634, "s": 2913, "text": null }, { "code": null, "e": 3642, "s": 3634, "text": "Output:" }, { "code": null, "e": 3693, "s": 3642, "text": "Example 4: This example illustrates the Cart Icon." }, { "code": null, "e": 3698, "s": 3693, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\" /> <title>Bootstrap Icons in HTML</title> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" /> <!-- Bootstrap Font Icon CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css\" /></head> <body> <center> <h1 style=\"color: green\"> Geeks For Geeks </h1> <h1 class=\"m-4\">Cart Icon: <i class=\"bi-cart\"></i> </h1> </center></body> </html>", "e": 4391, "s": 3698, "text": null }, { "code": null, "e": 4399, "s": 4391, "text": "Output:" }, { "code": null, "e": 4442, "s": 4399, "text": "Reference: https://icons.getbootstrap.com/" }, { "code": null, "e": 4451, "s": 4442, "text": "rkbhola5" }, { "code": null, "e": 4463, "s": 4451, "text": "Bootstrap-4" }, { "code": null, "e": 4483, "s": 4463, "text": "Bootstrap-Questions" }, { "code": null, "e": 4498, "s": 4483, "text": "HTML-Questions" }, { "code": null, "e": 4505, "s": 4498, "text": "Picked" }, { "code": null, "e": 4515, "s": 4505, "text": "Bootstrap" }, { "code": null, "e": 4532, "s": 4515, "text": "Web Technologies" }, { "code": null, "e": 4630, "s": 4532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4671, "s": 4630, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 4704, "s": 4671, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 4749, "s": 4704, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 4775, "s": 4749, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 4842, "s": 4775, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 4904, "s": 4842, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4937, "s": 4904, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4998, "s": 4937, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5048, "s": 4998, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Junk File Organizer in Python
10 Aug, 2021 Basically, as a lazy programmer, my desktop is full of files (Junk Files). Due to a large number of files, it is a daunting task to sit and organize each file. To make that task easy the below Python script comes in handy and all the files are organized in a well-manner within seconds. Screenshot before running the script Following are the steps to be followed: Create Dictionaries: The code below will create the defined Directories. DIRECTORIES = { "HTML": [".html5", ".html", ".htm", ".xhtml"], "IMAGES": [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", "svg", ".heif", ".psd"], "VIDEOS": [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng", ".qt", ".mpg", ".mpeg", ".3gp"], "DOCUMENTS": [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods", ".odt", ".pwi", ".xsn", ".xps", ".dotx", ".docm", ".dox", ".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx", ".ppt", "pptx"], "ARCHIVES": [".a", ".ar", ".cpio", ".iso", ".tar", ".gz", ".rz", ".7z", ".dmg", ".rar", ".xar", ".zip"], "AUDIO": [".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3", ".msv", "ogg", "oga", ".raw", ".vox", ".wav", ".wma"], "PLAINTEXT": [".txt", ".in", ".out"], "PDF": [".pdf"], "PYTHON": [".py"], "XML": [".xml"], "EXE": [".exe"], "SHELL": [".sh"] } Mapping: Now we will map the file formats with the directory. FILE_FORMATS = {file_format: directory for directory, file_formats in DIRECTORIES.items() for file_format in file_formats} Here, we map file extensions with the directory. def organize_junk(): for entry in os.scandir(): if entry.is_dir(): continue file_path = Path(entry) file_format = file_path.suffix.lower() if file_format in FILE_FORMATS: directory_path = Path(FILE_FORMATS[file_format]) directory_path.mkdir(exist_ok=True) file_path.rename(directory_path.joinpath(file_path)) for dir in os.scandir(): try: os.rmdir(dir) except: pass The above function will check for the existing directory for the same name we defined. If the existing directory is found then it will continue or else a new directory is created. And it will categorize all the files based on the extension in the appropriate folder. Organizing: Following is the code for Python Lazy Junk Files Organizer. It will organize everything in the appropriate folder in a single go and remove empty directories. python import osfrom pathlib import Path DIRECTORIES = { "HTML": [".html5", ".html", ".htm", ".xhtml"], "IMAGES": [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", "svg", ".heif", ".psd"], "VIDEOS": [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng", ".qt", ".mpg", ".mpeg", ".3gp"], "DOCUMENTS": [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods", ".odt", ".pwi", ".xsn", ".xps", ".dotx", ".docm", ".dox", ".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx", ".ppt", "pptx"], "ARCHIVES": [".a", ".ar", ".cpio", ".iso", ".tar", ".gz", ".rz", ".7z", ".dmg", ".rar", ".xar", ".zip"], "AUDIO": [".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3", ".msv", "ogg", "oga", ".raw", ".vox", ".wav", ".wma"], "PLAINTEXT": [".txt", ".in", ".out"], "PDF": [".pdf"], "PYTHON": [".py"], "XML": [".xml"], "EXE": [".exe"], "SHELL": [".sh"] } FILE_FORMATS = {file_format: directory for directory, file_formats in DIRECTORIES.items() for file_format in file_formats} def organize_junk(): for entry in os.scandir(): if entry.is_dir(): continue file_path = Path(entry) file_format = file_path.suffix.lower() if file_format in FILE_FORMATS: directory_path = Path(FILE_FORMATS[file_format]) directory_path.mkdir(exist_ok=True) file_path.rename(directory_path.joinpath(file_path)) for dir in os.scandir(): try: os.rmdir(dir) except: pass if __name__ == "__main__": organize_junk() Save the above script as orgjunk.py. For example, you want to organize files at desktop then copy and paste the orgjunk.py at Desktop and run. This article is contributed by Srce Cde. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vicky978654 Python-projects python-utility GBlog Project Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial How to Learn Data Science in 10 weeks? SDE SHEET - A Complete Guide for SDE Preparation Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Aug, 2021" }, { "code": null, "e": 342, "s": 54, "text": "Basically, as a lazy programmer, my desktop is full of files (Junk Files). Due to a large number of files, it is a daunting task to sit and organize each file. To make that task easy the below Python script comes in handy and all the files are organized in a well-manner within seconds. " }, { "code": null, "e": 379, "s": 342, "text": "Screenshot before running the script" }, { "code": null, "e": 421, "s": 379, "text": "Following are the steps to be followed: " }, { "code": null, "e": 495, "s": 421, "text": "Create Dictionaries: The code below will create the defined Directories. " }, { "code": null, "e": 1485, "s": 495, "text": "DIRECTORIES = {\n \"HTML\": [\".html5\", \".html\", \".htm\", \".xhtml\"],\n \"IMAGES\": [\".jpeg\", \".jpg\", \".tiff\", \".gif\", \".bmp\", \".png\", \".bpg\", \"svg\",\n \".heif\", \".psd\"],\n \"VIDEOS\": [\".avi\", \".flv\", \".wmv\", \".mov\", \".mp4\", \".webm\", \".vob\", \".mng\",\n \".qt\", \".mpg\", \".mpeg\", \".3gp\"],\n \"DOCUMENTS\": [\".oxps\", \".epub\", \".pages\", \".docx\", \".doc\", \".fdf\", \".ods\",\n \".odt\", \".pwi\", \".xsn\", \".xps\", \".dotx\", \".docm\", \".dox\",\n \".rvg\", \".rtf\", \".rtfd\", \".wpd\", \".xls\", \".xlsx\", \".ppt\",\n \"pptx\"],\n \"ARCHIVES\": [\".a\", \".ar\", \".cpio\", \".iso\", \".tar\", \".gz\", \".rz\", \".7z\",\n \".dmg\", \".rar\", \".xar\", \".zip\"],\n \"AUDIO\": [\".aac\", \".aa\", \".aac\", \".dvf\", \".m4a\", \".m4b\", \".m4p\", \".mp3\",\n \".msv\", \"ogg\", \"oga\", \".raw\", \".vox\", \".wav\", \".wma\"],\n \"PLAINTEXT\": [\".txt\", \".in\", \".out\"],\n \"PDF\": [\".pdf\"],\n \"PYTHON\": [\".py\"],\n \"XML\": [\".xml\"],\n \"EXE\": [\".exe\"],\n \"SHELL\": [\".sh\"]\n\n}" }, { "code": null, "e": 1548, "s": 1485, "text": "Mapping: Now we will map the file formats with the directory. " }, { "code": null, "e": 1703, "s": 1548, "text": "FILE_FORMATS = {file_format: directory\n for directory, file_formats in DIRECTORIES.items()\n for file_format in file_formats}" }, { "code": null, "e": 1753, "s": 1703, "text": "Here, we map file extensions with the directory. " }, { "code": null, "e": 2268, "s": 1753, "text": "def organize_junk():\n for entry in os.scandir():\n if entry.is_dir():\n continue\n file_path = Path(entry)\n file_format = file_path.suffix.lower()\n if file_format in FILE_FORMATS:\n directory_path = Path(FILE_FORMATS[file_format])\n directory_path.mkdir(exist_ok=True)\n file_path.rename(directory_path.joinpath(file_path))\n\n for dir in os.scandir():\n try:\n os.rmdir(dir)\n except:\n pass" }, { "code": null, "e": 2536, "s": 2268, "text": "The above function will check for the existing directory for the same name we defined. If the existing directory is found then it will continue or else a new directory is created. And it will categorize all the files based on the extension in the appropriate folder. " }, { "code": null, "e": 2708, "s": 2536, "text": "Organizing: Following is the code for Python Lazy Junk Files Organizer. It will organize everything in the appropriate folder in a single go and remove empty directories. " }, { "code": null, "e": 2715, "s": 2708, "text": "python" }, { "code": "import osfrom pathlib import Path DIRECTORIES = { \"HTML\": [\".html5\", \".html\", \".htm\", \".xhtml\"], \"IMAGES\": [\".jpeg\", \".jpg\", \".tiff\", \".gif\", \".bmp\", \".png\", \".bpg\", \"svg\", \".heif\", \".psd\"], \"VIDEOS\": [\".avi\", \".flv\", \".wmv\", \".mov\", \".mp4\", \".webm\", \".vob\", \".mng\", \".qt\", \".mpg\", \".mpeg\", \".3gp\"], \"DOCUMENTS\": [\".oxps\", \".epub\", \".pages\", \".docx\", \".doc\", \".fdf\", \".ods\", \".odt\", \".pwi\", \".xsn\", \".xps\", \".dotx\", \".docm\", \".dox\", \".rvg\", \".rtf\", \".rtfd\", \".wpd\", \".xls\", \".xlsx\", \".ppt\", \"pptx\"], \"ARCHIVES\": [\".a\", \".ar\", \".cpio\", \".iso\", \".tar\", \".gz\", \".rz\", \".7z\", \".dmg\", \".rar\", \".xar\", \".zip\"], \"AUDIO\": [\".aac\", \".aa\", \".aac\", \".dvf\", \".m4a\", \".m4b\", \".m4p\", \".mp3\", \".msv\", \"ogg\", \"oga\", \".raw\", \".vox\", \".wav\", \".wma\"], \"PLAINTEXT\": [\".txt\", \".in\", \".out\"], \"PDF\": [\".pdf\"], \"PYTHON\": [\".py\"], \"XML\": [\".xml\"], \"EXE\": [\".exe\"], \"SHELL\": [\".sh\"] } FILE_FORMATS = {file_format: directory for directory, file_formats in DIRECTORIES.items() for file_format in file_formats} def organize_junk(): for entry in os.scandir(): if entry.is_dir(): continue file_path = Path(entry) file_format = file_path.suffix.lower() if file_format in FILE_FORMATS: directory_path = Path(FILE_FORMATS[file_format]) directory_path.mkdir(exist_ok=True) file_path.rename(directory_path.joinpath(file_path)) for dir in os.scandir(): try: os.rmdir(dir) except: pass if __name__ == \"__main__\": organize_junk()", "e": 4419, "s": 2715, "text": null }, { "code": null, "e": 4562, "s": 4419, "text": "Save the above script as orgjunk.py. For example, you want to organize files at desktop then copy and paste the orgjunk.py at Desktop and run." }, { "code": null, "e": 4983, "s": 4562, "text": "This article is contributed by Srce Cde. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 4995, "s": 4983, "text": "vicky978654" }, { "code": null, "e": 5011, "s": 4995, "text": "Python-projects" }, { "code": null, "e": 5026, "s": 5011, "text": "python-utility" }, { "code": null, "e": 5032, "s": 5026, "text": "GBlog" }, { "code": null, "e": 5040, "s": 5032, "text": "Project" }, { "code": null, "e": 5047, "s": 5040, "text": "Python" }, { "code": null, "e": 5066, "s": 5047, "text": "Technical Scripter" }, { "code": null, "e": 5164, "s": 5066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5189, "s": 5164, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 5244, "s": 5189, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 5281, "s": 5244, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 5319, "s": 5281, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 5358, "s": 5319, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 5407, "s": 5358, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 5462, "s": 5407, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 5495, "s": 5462, "text": "Working with zip files in Python" }, { "code": null, "e": 5517, "s": 5495, "text": "XML parsing in Python" } ]
Print a given matrix in reverse spiral form
14 Jun, 2022 Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form. This article discusses how to do the reverse printing. See the following examples. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1 Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Output: 11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1 C++ Java Python3 C# PHP Javascript // This is a modified code of// https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/#include <iostream>#define R 3#define C 6using namespace std; // Function that print matrix in reverse spiral form.void ReversespiralPrint(int m, int n, int a[R][C]){ // Large array to initialize it // with elements of matrix long int b[100]; /* k - starting row index l - starting column index*/ int i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored int z = 0; // Total elements in matrix int size = m*n; while (k < m && l < n) { // Variable to store value of matrix. int val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { // printf("%d ", a[k][i]); val = a[k][i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { // printf("%d ", a[i][n-1]); val = a[i][n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { // printf("%d ", a[m-1][i]); val = a[m-1][i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { // printf("%d ", a[i][l]); val = a[i][l]; b[z] = val; ++z; } l++; } } for (int i=size-1 ; i>=0 ; --i) { cout<<b[i]<<" "; }} /* Driver program to test above functions */int main(){ int a[R][C] = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; ReversespiralPrint(R, C, a); return 0;} // JAVA Code for Print a given matrix in// reverse spiral formclass GFG { public static int R = 3, C = 6; // Function that print matrix in reverse spiral form. public static void ReversespiralPrint(int m, int n, int a[][]) { // Large array to initialize it // with elements of matrix long b[] = new long[100]; /* k - starting row index l - starting column index*/ int i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored int z = 0; // Total elements in matrix int size = m * n; while (k < m && l < n) { // Variable to store value of matrix. int val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { val = a[k][i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { val = a[i][n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { val = a[m-1][i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { val = a[i][l]; b[z] = val; ++z; } l++; } } for (int x = size-1 ; x>=0 ; --x) { System.out.print(b[x]+" "); } } /* Driver program to test above function */ public static void main(String[] args) { int a[][] = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; ReversespiralPrint(R, C, a); } }// This code is contributed by Arnav Kr. Mandal. # Python3 Code to Print a given # matrix in reverse spiral form # This is a modified code of# https:#www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/R, C = 3, 6 def ReversespiralPrint(m, n, a): # Large array to initialize it # with elements of matrix b = [0 for i in range(100)] #/* k - starting row index #l - starting column index*/ i, k, l = 0, 0, 0 # Counter for single dimension array # in which elements will be stored z = 0 # Total elements in matrix size = m * n while (k < m and l < n): # Variable to store value of matrix. val = 0 # Print the first row # from the remaining rows for i in range(l, n): # printf("%d ", a[k][i]) val = a[k][i] b[z] = val z += 1 k += 1 # Print the last column # from the remaining columns for i in range(k, m): # printf("%d ", a[i][n-1]) val = a[i][n - 1] b[z] = val z += 1 n -= 1 # Print the last row # from the remaining rows if (k < m): for i in range(n - 1, l - 1, -1): # printf("%d ", a[m-1][i]) val = a[m - 1][i] b[z] = val z += 1 m -= 1 # Print the first column # from the remaining columns if (l < n): for i in range(m - 1, k - 1, -1): # printf("%d ", a[i][l]) val = a[i][l] b[z] = val z += 1 l += 1 for i in range(size - 1, -1, -1): print(b[i], end = " ") # Driver Codea = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]] ReversespiralPrint(R, C, a) # This code is contributed by mohit kumar // C# Code for Print a given matrix in// reverse spiral formusing System;class GFG { public static int R = 3, C = 6; // Function that print matrix in reverse spiral form. public static void ReversespiralPrint(int m, int n, int [,]a) { // Large array to initialize it // with elements of matrix long []b = new long[100]; /* k - starting row index l - starting column index*/ int i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored int z = 0; // Total elements in matrix int size = m * n; while (k < m && l < n) { // Variable to store value of matrix. int val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { val = a[k,i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { val = a[i,n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { val = a[m-1,i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { val = a[i,l]; b[z] = val; ++z; } l++; } } for (int x = size-1 ; x>=0 ; --x) { Console.Write(b[x]+" "); } } /* Driver program to test above function */ public static void Main() { int [ ,]a = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; ReversespiralPrint(R, C, a); }}// This code is contributed by vt_m. <?php// PHP Code for Print a given // matrix in reverse spiral form$R=3;$C=6; // Function that print matrix// in reverse spiral form.function ReversespiralPrint($m, $n, array $a){ // Large array to initialize it // with elements of matrix $b; // k - starting row index // l - starting column index $k = 0; $l = 0; // Counter for single dimension array // in which elements will be stored $z = 0; // Total elements in matrix $size = $m*$n; while ($k < $m && $l < $n) { // Variable to store // value of matrix. $val; // Print the first row from // the remaining rows for ($i = $l; $i < $n; ++$i) { $val = $a[$k][$i]; $b[$z] = $val; ++$z; } $k++; // Print the last column from // the remaining columns for ($i = $k; $i < $m; ++$i) { // printf("%d ", a[i][n-1]); $val = $a[$i][$n-1]; $b[$z] = $val; ++$z; } $n--; // Print the last row from // the remaining rows if ( $k < $m) { for ($i = $n-1; $i >= $l; --$i) { // printf("%d ", a[m-1][i]); $val = $a[$m-1][$i]; $b[$z] = $val; ++$z; } $m--; } // Print the first column // from the remaining columns if ($l < $n) { for ($i = $m - 1; $i >= $k; --$i) { $val = $a[$i][$l]; $b[$z] = $val; ++$z; } $l++; } } for ($i = $size - 1; $i >= 0; --$i) { echo $b[$i]." "; }} // Driver Code $a= array(array(1, 2, 3, 4, 5, 6), array(7, 8, 9, 10, 11, 12), array(13, 14, 15, 16, 17, 18)); ReversespiralPrint($R, $C, $a); // This Code is contributed by mits?> <script> // This is a modified code of// https://www.geeksforgeeks.org/// print-a-given-matrix-in-spiral-form/ let R = 3;let C = 6; // Function that print matrix in// reverse spiral form.function ReversespiralPrint(m, n, a){ // Large array to initialize it // with elements of matrix let b = new Array(100); /* k - starting row index l - starting column index*/ let i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored let z = 0; // Total elements in matrix let size = m*n; while (k < m && l < n) { // Variable to store value of matrix. let val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { // printf("%d ", a[k][i]); val = a[k][i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { // printf("%d ", a[i][n-1]); val = a[i][n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { // printf("%d ", a[m-1][i]); val = a[m-1][i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { // printf("%d ", a[i][l]); val = a[i][l]; b[z] = val; ++z; } l++; } } for (let i=size-1 ; i>=0 ; --i) { document.write(b[i] + " "); }} /* Driver program to test above functions */ let a = [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]; ReversespiralPrint(R, C, a); </script> Output: 11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1 Time Complexity: O(m*n). To traverse the matrix O(m*n) time is required.Auxiliary Space: O(1). No extra space is required. This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar mohit kumar 29 rishavmahato348 aditya942003patil pattern-printing spiral Matrix School Programming pattern-printing Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. The Celebrity Problem Count all possible paths from top left to bottom right of a mXn matrix Unique paths in a Grid with Obstacles Printing all solutions in N-Queen Problem Min Cost Path | DP-6 Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jun, 2022" }, { "code": null, "e": 253, "s": 54, "text": "Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form. This article discusses how to do the reverse printing. See the following examples. " }, { "code": null, "e": 550, "s": 253, "text": "Input:\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 15 16\nOutput: \n10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1\nInput:\n 1 2 3 4 5 6\n 7 8 9 10 11 12\n 13 14 15 16 17 18\nOutput: \n11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1" }, { "code": null, "e": 558, "s": 554, "text": "C++" }, { "code": null, "e": 563, "s": 558, "text": "Java" }, { "code": null, "e": 571, "s": 563, "text": "Python3" }, { "code": null, "e": 574, "s": 571, "text": "C#" }, { "code": null, "e": 578, "s": 574, "text": "PHP" }, { "code": null, "e": 589, "s": 578, "text": "Javascript" }, { "code": "// This is a modified code of// https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/#include <iostream>#define R 3#define C 6using namespace std; // Function that print matrix in reverse spiral form.void ReversespiralPrint(int m, int n, int a[R][C]){ // Large array to initialize it // with elements of matrix long int b[100]; /* k - starting row index l - starting column index*/ int i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored int z = 0; // Total elements in matrix int size = m*n; while (k < m && l < n) { // Variable to store value of matrix. int val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { // printf(\"%d \", a[k][i]); val = a[k][i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { // printf(\"%d \", a[i][n-1]); val = a[i][n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { // printf(\"%d \", a[m-1][i]); val = a[m-1][i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { // printf(\"%d \", a[i][l]); val = a[i][l]; b[z] = val; ++z; } l++; } } for (int i=size-1 ; i>=0 ; --i) { cout<<b[i]<<\" \"; }} /* Driver program to test above functions */int main(){ int a[R][C] = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; ReversespiralPrint(R, C, a); return 0;}", "e": 2635, "s": 589, "text": null }, { "code": "// JAVA Code for Print a given matrix in// reverse spiral formclass GFG { public static int R = 3, C = 6; // Function that print matrix in reverse spiral form. public static void ReversespiralPrint(int m, int n, int a[][]) { // Large array to initialize it // with elements of matrix long b[] = new long[100]; /* k - starting row index l - starting column index*/ int i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored int z = 0; // Total elements in matrix int size = m * n; while (k < m && l < n) { // Variable to store value of matrix. int val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { val = a[k][i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { val = a[i][n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { val = a[m-1][i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { val = a[i][l]; b[z] = val; ++z; } l++; } } for (int x = size-1 ; x>=0 ; --x) { System.out.print(b[x]+\" \"); } } /* Driver program to test above function */ public static void main(String[] args) { int a[][] = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; ReversespiralPrint(R, C, a); } }// This code is contributed by Arnav Kr. Mandal.", "e": 5079, "s": 2635, "text": null }, { "code": "# Python3 Code to Print a given # matrix in reverse spiral form # This is a modified code of# https:#www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/R, C = 3, 6 def ReversespiralPrint(m, n, a): # Large array to initialize it # with elements of matrix b = [0 for i in range(100)] #/* k - starting row index #l - starting column index*/ i, k, l = 0, 0, 0 # Counter for single dimension array # in which elements will be stored z = 0 # Total elements in matrix size = m * n while (k < m and l < n): # Variable to store value of matrix. val = 0 # Print the first row # from the remaining rows for i in range(l, n): # printf(\"%d \", a[k][i]) val = a[k][i] b[z] = val z += 1 k += 1 # Print the last column # from the remaining columns for i in range(k, m): # printf(\"%d \", a[i][n-1]) val = a[i][n - 1] b[z] = val z += 1 n -= 1 # Print the last row # from the remaining rows if (k < m): for i in range(n - 1, l - 1, -1): # printf(\"%d \", a[m-1][i]) val = a[m - 1][i] b[z] = val z += 1 m -= 1 # Print the first column # from the remaining columns if (l < n): for i in range(m - 1, k - 1, -1): # printf(\"%d \", a[i][l]) val = a[i][l] b[z] = val z += 1 l += 1 for i in range(size - 1, -1, -1): print(b[i], end = \" \") # Driver Codea = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]] ReversespiralPrint(R, C, a) # This code is contributed by mohit kumar", "e": 6933, "s": 5079, "text": null }, { "code": "// C# Code for Print a given matrix in// reverse spiral formusing System;class GFG { public static int R = 3, C = 6; // Function that print matrix in reverse spiral form. public static void ReversespiralPrint(int m, int n, int [,]a) { // Large array to initialize it // with elements of matrix long []b = new long[100]; /* k - starting row index l - starting column index*/ int i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored int z = 0; // Total elements in matrix int size = m * n; while (k < m && l < n) { // Variable to store value of matrix. int val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { val = a[k,i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { val = a[i,n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { val = a[m-1,i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { val = a[i,l]; b[z] = val; ++z; } l++; } } for (int x = size-1 ; x>=0 ; --x) { Console.Write(b[x]+\" \"); } } /* Driver program to test above function */ public static void Main() { int [ ,]a = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; ReversespiralPrint(R, C, a); }}// This code is contributed by vt_m.", "e": 9338, "s": 6933, "text": null }, { "code": "<?php// PHP Code for Print a given // matrix in reverse spiral form$R=3;$C=6; // Function that print matrix// in reverse spiral form.function ReversespiralPrint($m, $n, array $a){ // Large array to initialize it // with elements of matrix $b; // k - starting row index // l - starting column index $k = 0; $l = 0; // Counter for single dimension array // in which elements will be stored $z = 0; // Total elements in matrix $size = $m*$n; while ($k < $m && $l < $n) { // Variable to store // value of matrix. $val; // Print the first row from // the remaining rows for ($i = $l; $i < $n; ++$i) { $val = $a[$k][$i]; $b[$z] = $val; ++$z; } $k++; // Print the last column from // the remaining columns for ($i = $k; $i < $m; ++$i) { // printf(\"%d \", a[i][n-1]); $val = $a[$i][$n-1]; $b[$z] = $val; ++$z; } $n--; // Print the last row from // the remaining rows if ( $k < $m) { for ($i = $n-1; $i >= $l; --$i) { // printf(\"%d \", a[m-1][i]); $val = $a[$m-1][$i]; $b[$z] = $val; ++$z; } $m--; } // Print the first column // from the remaining columns if ($l < $n) { for ($i = $m - 1; $i >= $k; --$i) { $val = $a[$i][$l]; $b[$z] = $val; ++$z; } $l++; } } for ($i = $size - 1; $i >= 0; --$i) { echo $b[$i].\" \"; }} // Driver Code $a= array(array(1, 2, 3, 4, 5, 6), array(7, 8, 9, 10, 11, 12), array(13, 14, 15, 16, 17, 18)); ReversespiralPrint($R, $C, $a); // This Code is contributed by mits?>", "e": 11338, "s": 9338, "text": null }, { "code": "<script> // This is a modified code of// https://www.geeksforgeeks.org/// print-a-given-matrix-in-spiral-form/ let R = 3;let C = 6; // Function that print matrix in// reverse spiral form.function ReversespiralPrint(m, n, a){ // Large array to initialize it // with elements of matrix let b = new Array(100); /* k - starting row index l - starting column index*/ let i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored let z = 0; // Total elements in matrix let size = m*n; while (k < m && l < n) { // Variable to store value of matrix. let val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { // printf(\"%d \", a[k][i]); val = a[k][i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { // printf(\"%d \", a[i][n-1]); val = a[i][n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { // printf(\"%d \", a[m-1][i]); val = a[m-1][i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { // printf(\"%d \", a[i][l]); val = a[i][l]; b[z] = val; ++z; } l++; } } for (let i=size-1 ; i>=0 ; --i) { document.write(b[i] + \" \"); }} /* Driver program to test above functions */ let a = [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]; ReversespiralPrint(R, C, a); </script>", "e": 13381, "s": 11338, "text": null }, { "code": null, "e": 13390, "s": 13381, "text": "Output: " }, { "code": null, "e": 13435, "s": 13390, "text": "11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1" }, { "code": null, "e": 13558, "s": 13435, "text": "Time Complexity: O(m*n). To traverse the matrix O(m*n) time is required.Auxiliary Space: O(1). No extra space is required." }, { "code": null, "e": 13979, "s": 13558, "text": "This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 13992, "s": 13979, "text": "Mithun Kumar" }, { "code": null, "e": 14007, "s": 13992, "text": "mohit kumar 29" }, { "code": null, "e": 14023, "s": 14007, "text": "rishavmahato348" }, { "code": null, "e": 14041, "s": 14023, "text": "aditya942003patil" }, { "code": null, "e": 14058, "s": 14041, "text": "pattern-printing" }, { "code": null, "e": 14065, "s": 14058, "text": "spiral" }, { "code": null, "e": 14072, "s": 14065, "text": "Matrix" }, { "code": null, "e": 14091, "s": 14072, "text": "School Programming" }, { "code": null, "e": 14108, "s": 14091, "text": "pattern-printing" }, { "code": null, "e": 14115, "s": 14108, "text": "Matrix" }, { "code": null, "e": 14213, "s": 14115, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14235, "s": 14213, "text": "The Celebrity Problem" }, { "code": null, "e": 14306, "s": 14235, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 14344, "s": 14306, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 14386, "s": 14344, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 14407, "s": 14386, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 14425, "s": 14407, "text": "Python Dictionary" }, { "code": null, "e": 14450, "s": 14425, "text": "Reverse a string in Java" }, { "code": null, "e": 14466, "s": 14450, "text": "Arrays in C/C++" }, { "code": null, "e": 14489, "s": 14466, "text": "Introduction To PYTHON" } ]
How to use avg and sum in SQLAlchemy Query?
22 Nov, 2021 In this article, we are going to see how to use avg and sum in SQLAlchemy query using Python. SQLAlchemy is available via the pip install package. pip install sqlalchemy However, if you are using flask you can make use of its own implementation of SQLAlchemy. It can be installed using – pip install flask-sqlalchemy Before we move ahead, we need to have a database and a table to work with. For this example, we are using the MySQL database and have created a students table. The table has 3 columns and 6 records as shown below. In the table, we have a float column `percentage` on which we will perform our average and sum operations using SQLAlchemy. First, we import the sqlalchemy library as db for simplicity. All the sqlalchemy objects, methods, etc will be imported using db prefix for better clarity.We then create the engine which will serve as a connection to the database to perform all the database operations.Create the metadata object. The metadata object `metadata` contains all the information about our database.Use the metadata information to fetch the students table from the database.We can now write an SQLAlchemy query to fetch the required records. We first extract the average value of the percentage column using SQLalchemy’s `func.avg()` function. Then we use the `func.sum()` function to get the sum of the values in the percentage column. Note that in both cases we have used the method `func.round(val, 2)` to round off the values to 2 decimal places.Print the output. In the output we can view that we have both the sum and average values for the percentage field. First, we import the sqlalchemy library as db for simplicity. All the sqlalchemy objects, methods, etc will be imported using db prefix for better clarity. We then create the engine which will serve as a connection to the database to perform all the database operations. Create the metadata object. The metadata object `metadata` contains all the information about our database. Use the metadata information to fetch the students table from the database. We can now write an SQLAlchemy query to fetch the required records. We first extract the average value of the percentage column using SQLalchemy’s `func.avg()` function. Then we use the `func.sum()` function to get the sum of the values in the percentage column. Note that in both cases we have used the method `func.round(val, 2)` to round off the values to 2 decimal places. Print the output. In the output we can view that we have both the sum and average values for the percentage field. Python import sqlalchemy as db # Define the Engine (Connection Object)engine = db.create_engine( "mysql+pymysql://root:password@localhost/Geeks4Geeks") # Create the Metadata Objectmeta_data = db.MetaData(bind=engine)db.MetaData.reflect(meta_data) # Get the `students` table from the Metadata objectSTUDENTS = meta_data.tables['students'] # SQLAlchemy Query to get AVGquery = db.select([db.func.round(db.func.avg(STUDENTS.c.percentage), 2)]) # Fetch the recordsavg_result = engine.execute(query).fetchall() # SQLAlchemy Query to get SUMquery = db.select([db.func.round(db.func.sum(STUDENTS.c.percentage), 2)]) # Fetch the recordssum_result = engine.execute(query).fetchall() # View the recordsprint("\nAverage: ", avg_result[0])print("\nSum: ", sum_result[0]) Output: Picked Python-SQLAlchemy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 122, "s": 28, "text": "In this article, we are going to see how to use avg and sum in SQLAlchemy query using Python." }, { "code": null, "e": 175, "s": 122, "text": "SQLAlchemy is available via the pip install package." }, { "code": null, "e": 198, "s": 175, "text": "pip install sqlalchemy" }, { "code": null, "e": 316, "s": 198, "text": "However, if you are using flask you can make use of its own implementation of SQLAlchemy. It can be installed using –" }, { "code": null, "e": 345, "s": 316, "text": "pip install flask-sqlalchemy" }, { "code": null, "e": 559, "s": 345, "text": "Before we move ahead, we need to have a database and a table to work with. For this example, we are using the MySQL database and have created a students table. The table has 3 columns and 6 records as shown below." }, { "code": null, "e": 683, "s": 559, "text": "In the table, we have a float column `percentage` on which we will perform our average and sum operations using SQLAlchemy." }, { "code": null, "e": 1625, "s": 683, "text": "First, we import the sqlalchemy library as db for simplicity. All the sqlalchemy objects, methods, etc will be imported using db prefix for better clarity.We then create the engine which will serve as a connection to the database to perform all the database operations.Create the metadata object. The metadata object `metadata` contains all the information about our database.Use the metadata information to fetch the students table from the database.We can now write an SQLAlchemy query to fetch the required records. We first extract the average value of the percentage column using SQLalchemy’s `func.avg()` function. Then we use the `func.sum()` function to get the sum of the values in the percentage column. Note that in both cases we have used the method `func.round(val, 2)` to round off the values to 2 decimal places.Print the output. In the output we can view that we have both the sum and average values for the percentage field." }, { "code": null, "e": 1781, "s": 1625, "text": "First, we import the sqlalchemy library as db for simplicity. All the sqlalchemy objects, methods, etc will be imported using db prefix for better clarity." }, { "code": null, "e": 1896, "s": 1781, "text": "We then create the engine which will serve as a connection to the database to perform all the database operations." }, { "code": null, "e": 2004, "s": 1896, "text": "Create the metadata object. The metadata object `metadata` contains all the information about our database." }, { "code": null, "e": 2080, "s": 2004, "text": "Use the metadata information to fetch the students table from the database." }, { "code": null, "e": 2457, "s": 2080, "text": "We can now write an SQLAlchemy query to fetch the required records. We first extract the average value of the percentage column using SQLalchemy’s `func.avg()` function. Then we use the `func.sum()` function to get the sum of the values in the percentage column. Note that in both cases we have used the method `func.round(val, 2)` to round off the values to 2 decimal places." }, { "code": null, "e": 2572, "s": 2457, "text": "Print the output. In the output we can view that we have both the sum and average values for the percentage field." }, { "code": null, "e": 2579, "s": 2572, "text": "Python" }, { "code": "import sqlalchemy as db # Define the Engine (Connection Object)engine = db.create_engine( \"mysql+pymysql://root:password@localhost/Geeks4Geeks\") # Create the Metadata Objectmeta_data = db.MetaData(bind=engine)db.MetaData.reflect(meta_data) # Get the `students` table from the Metadata objectSTUDENTS = meta_data.tables['students'] # SQLAlchemy Query to get AVGquery = db.select([db.func.round(db.func.avg(STUDENTS.c.percentage), 2)]) # Fetch the recordsavg_result = engine.execute(query).fetchall() # SQLAlchemy Query to get SUMquery = db.select([db.func.round(db.func.sum(STUDENTS.c.percentage), 2)]) # Fetch the recordssum_result = engine.execute(query).fetchall() # View the recordsprint(\"\\nAverage: \", avg_result[0])print(\"\\nSum: \", sum_result[0])", "e": 3342, "s": 2579, "text": null }, { "code": null, "e": 3350, "s": 3342, "text": "Output:" }, { "code": null, "e": 3357, "s": 3350, "text": "Picked" }, { "code": null, "e": 3375, "s": 3357, "text": "Python-SQLAlchemy" }, { "code": null, "e": 3382, "s": 3375, "text": "Python" }, { "code": null, "e": 3480, "s": 3382, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3512, "s": 3480, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3539, "s": 3512, "text": "Python Classes and Objects" }, { "code": null, "e": 3570, "s": 3539, "text": "Python | os.path.join() method" }, { "code": null, "e": 3593, "s": 3570, "text": "Introduction To PYTHON" }, { "code": null, "e": 3614, "s": 3593, "text": "Python OOPs Concepts" }, { "code": null, "e": 3670, "s": 3614, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3712, "s": 3670, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3754, "s": 3712, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3793, "s": 3754, "text": "Python | Get unique values from a list" } ]
How to Customize Linux Terminal Using powerlevel10k?
01 Jun, 2021 Sometimes we get bored with the normal Linux Terminal and feel like if we can customize the same, so we can use powerlevel10k for that. It is a theme for ZSH. It changes normal shell commands to colorful commands. To install powerlevel10k we need to install Oh My Zsh, both are open-source in GitHub. We can also use nerd font to make the powerlevel10k theme font more beautiful. Install Oh My Zsh To install Oh My Zsh open terminal and run sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" If this curl installation method shows any error use wget method sh -c "$(wget -O- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" Install powerlevel10k powerlevel10k theme installation becomes easy if oh my zsh is installation successful. Just run these two commands. git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k install powerlevel10k In another way, we can install it directly from GitHub and set it up git clone --depth=1 https://gitee.com/romkatv/powerlevel10k.git ~/powerlevel10k echo 'source ~/powerlevel10k/powerlevel10k.zsh-theme' >>~/.zshrc Install Nerd Font For powerlevel10k & Setup It powerlevel10k works well with nerd font they also recommend using nerd font, and it is easy to install the font in Linux. To install nerd font go to the official nerd font GitHub page https://github.com/ryanoasis/nerd-fonts and download font example Hack Nerd Font, JetBrains Mono Nerd Font, Ubuntu Nerd Font, etc. Install “Hack Nerd Font Regular” To set up it nerd font in terminal open terminal preferences and change the custom font to Hack Nerd Font Regular change custom font to Hack Nerd Font RegularSetup Setup powerlevel10k Theme After update powerlevel9k to powerlevel10k, it becomes easy to set up a theme. Do just type “p10k configure” in your terminal after choose options how you want to give looks to your terminal powerlevel10k setup process Note: If the installation fails then just restart your OS again try to install powerlevel10k anindra Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples mv command in Linux with examples chmod command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2021" }, { "code": null, "e": 408, "s": 28, "text": "Sometimes we get bored with the normal Linux Terminal and feel like if we can customize the same, so we can use powerlevel10k for that. It is a theme for ZSH. It changes normal shell commands to colorful commands. To install powerlevel10k we need to install Oh My Zsh, both are open-source in GitHub. We can also use nerd font to make the powerlevel10k theme font more beautiful." }, { "code": null, "e": 426, "s": 408, "text": "Install Oh My Zsh" }, { "code": null, "e": 469, "s": 426, "text": "To install Oh My Zsh open terminal and run" }, { "code": null, "e": 565, "s": 469, "text": "sh -c \"$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)\"" }, { "code": null, "e": 632, "s": 565, "text": " If this curl installation method shows any error use wget method " }, { "code": null, "e": 726, "s": 632, "text": "sh -c \"$(wget -O- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)\"" }, { "code": null, "e": 748, "s": 726, "text": "Install powerlevel10k" }, { "code": null, "e": 864, "s": 748, "text": "powerlevel10k theme installation becomes easy if oh my zsh is installation successful. Just run these two commands." }, { "code": null, "e": 989, "s": 864, "text": "git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k" }, { "code": null, "e": 1011, "s": 989, "text": "install powerlevel10k" }, { "code": null, "e": 1081, "s": 1011, "text": "In another way, we can install it directly from GitHub and set it up " }, { "code": null, "e": 1226, "s": 1081, "text": "git clone --depth=1 https://gitee.com/romkatv/powerlevel10k.git ~/powerlevel10k\necho 'source ~/powerlevel10k/powerlevel10k.zsh-theme' >>~/.zshrc" }, { "code": null, "e": 1273, "s": 1226, "text": "Install Nerd Font For powerlevel10k & Setup It" }, { "code": null, "e": 1588, "s": 1273, "text": "powerlevel10k works well with nerd font they also recommend using nerd font, and it is easy to install the font in Linux. To install nerd font go to the official nerd font GitHub page https://github.com/ryanoasis/nerd-fonts and download font example Hack Nerd Font, JetBrains Mono Nerd Font, Ubuntu Nerd Font, etc." }, { "code": null, "e": 1622, "s": 1588, "text": "Install “Hack Nerd Font Regular”" }, { "code": null, "e": 1736, "s": 1622, "text": "To set up it nerd font in terminal open terminal preferences and change the custom font to Hack Nerd Font Regular" }, { "code": null, "e": 1786, "s": 1736, "text": "change custom font to Hack Nerd Font RegularSetup" }, { "code": null, "e": 1812, "s": 1786, "text": "Setup powerlevel10k Theme" }, { "code": null, "e": 2003, "s": 1812, "text": "After update powerlevel9k to powerlevel10k, it becomes easy to set up a theme. Do just type “p10k configure” in your terminal after choose options how you want to give looks to your terminal" }, { "code": null, "e": 2031, "s": 2003, "text": "powerlevel10k setup process" }, { "code": null, "e": 2124, "s": 2031, "text": "Note: If the installation fails then just restart your OS again try to install powerlevel10k" }, { "code": null, "e": 2132, "s": 2124, "text": "anindra" }, { "code": null, "e": 2143, "s": 2132, "text": "Linux-Unix" }, { "code": null, "e": 2241, "s": 2143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2267, "s": 2241, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2302, "s": 2267, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2339, "s": 2302, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2368, "s": 2339, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2405, "s": 2368, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2439, "s": 2405, "text": "mv command in Linux with examples" }, { "code": null, "e": 2476, "s": 2439, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2516, "s": 2476, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 2555, "s": 2516, "text": "Introduction to Linux Operating System" } ]
How to Convert TreeMap to an ArrayList in Java?
10 Jun, 2022 TreeMap is a part of the Java Collection framework. Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains only unique elements. It cannot have a null key but can have multiple null values. TreeMap is not synchronized, we have to synchronize it explicitly in order to use it in a multi-threading environment. TreeMap maintains the ascending order of the elements. The way to convert TreeMap to ArrayList: TreeMap having keys and values can be converted into two ArrayLists of keys and values. Also, two ArrayLists, one with keys and the other with values, can be converted into a TreeMap. Example: TreeMap : {1=Welcome, 2=To, 3= Geeks, 4=For, 5=Geeks} keyList : [1, 2, 3, 4, 5] valueList : [Welcome, To, Geeks, For, Geeks] Approach: Create a TreeMap object and insert some keys and values. Extract the keys from the TreeMap using TreeMap.keySet() method and put them into an ArrayList object which has been created for storing keys. Extract the values from the TreeMap using TreeMap.values() method and put them into another ArrayList object which has been created for storing values. Example: Java // Java program to demonstrate conversion of// TreeMap to ArrayList import java.util.*;class GFG { // a class level treeMap object static TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // Method to convert TreeMap to ArrayList static void convertMapToList() { // Extract the keys from the TreeMap // using TreeMap.keySet() and // assign them to keyList of type ArrayList ArrayList<Integer> keyList = new ArrayList<Integer>(treeMap.keySet()); // Extract the values from the TreeMap // using TreeMap.values() and // assign them to valueList of type ArrayList ArrayList<String> valueList = new ArrayList<String>(treeMap.values()); // printing the keyList System.out.println( "List of keys of the given Map : " + keyList); // printing the valueList System.out.println( "List of values of the given Map : " + valueList); } // Driver Method public static void main(String args[]) { // inserting data into the TreeMap // using TreeMap.put() method treeMap.put(1, "Welcome"); treeMap.put(2, "To"); treeMap.put(3, "Geeks"); treeMap.put(4, "For"); treeMap.put(5, "Geeks"); // printing the TreeMap System.out.println("The TreeMap is : " + treeMap); // calling convertMapToList() method convertMapToList(); }} The TreeMap is : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks} List of keys of the given Map : [1, 2, 3, 4, 5] List of values of the given Map : [Welcome, To, Geeks, For, Geeks] In the below approach, we directly converted the entire TreeMap to ArrayList with both keys and values together. For this, we have to use Entry object. To use this approach, import the package java.util.Map.Entry. Here the keys and values in the TreeMap will directly get converted to ArrayList and the key and value for each index will be displayed as “key=value” in the ArrayList. Step 1: Declare and add the values in the TreeMap. Step 2: Call the function convertMaptoList(). Step 3: Declare the ArrayList with the Entry object in the function and specify the method TreeMap.entrySet() in the ArrayList constructor. It will convert the TreeMap values to ArrayList. Step 4: Print the converted ArrayList. Java import java.util.*;import java.util.Map.Entry; public class GFG { static TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); static void convertMapToList() { List<Entry> keyList = new ArrayList<Entry>(treeMap.entrySet()); System.out.println("Tree Map to ArrayList :" + keyList); } public static void main(String[] args) { treeMap.put(1, "Welcome"); treeMap.put(2, "To"); treeMap.put(3, "Geeks"); treeMap.put(4, "For"); treeMap.put(5, "Geeks"); // printing the TreeMap System.out.println("The TreeMap is : " + treeMap); // calling convertMapToList() method convertMapToList(); }} The TreeMap is : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks} Tree Map to ArrayList :[1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks] keerthikarathan123 Java-ArrayList Java-Collections java-TreeMap Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Introduction to Java Exceptions in Java Java Programming Examples Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Traverse Through a HashMap in Java Extends vs Implements in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2022" }, { "code": null, "e": 553, "s": 28, "text": "TreeMap is a part of the Java Collection framework. Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains only unique elements. It cannot have a null key but can have multiple null values. TreeMap is not synchronized, we have to synchronize it explicitly in order to use it in a multi-threading environment. TreeMap maintains the ascending order of the elements." }, { "code": null, "e": 594, "s": 553, "text": "The way to convert TreeMap to ArrayList:" }, { "code": null, "e": 682, "s": 594, "text": "TreeMap having keys and values can be converted into two ArrayLists of keys and values." }, { "code": null, "e": 778, "s": 682, "text": "Also, two ArrayLists, one with keys and the other with values, can be converted into a TreeMap." }, { "code": null, "e": 787, "s": 778, "text": "Example:" }, { "code": null, "e": 912, "s": 787, "text": "TreeMap : {1=Welcome, 2=To, 3= Geeks, 4=For, 5=Geeks}\nkeyList : [1, 2, 3, 4, 5]\nvalueList : [Welcome, To, Geeks, For, Geeks]" }, { "code": null, "e": 922, "s": 912, "text": "Approach:" }, { "code": null, "e": 979, "s": 922, "text": "Create a TreeMap object and insert some keys and values." }, { "code": null, "e": 1122, "s": 979, "text": "Extract the keys from the TreeMap using TreeMap.keySet() method and put them into an ArrayList object which has been created for storing keys." }, { "code": null, "e": 1274, "s": 1122, "text": "Extract the values from the TreeMap using TreeMap.values() method and put them into another ArrayList object which has been created for storing values." }, { "code": null, "e": 1283, "s": 1274, "text": "Example:" }, { "code": null, "e": 1288, "s": 1283, "text": "Java" }, { "code": "// Java program to demonstrate conversion of// TreeMap to ArrayList import java.util.*;class GFG { // a class level treeMap object static TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // Method to convert TreeMap to ArrayList static void convertMapToList() { // Extract the keys from the TreeMap // using TreeMap.keySet() and // assign them to keyList of type ArrayList ArrayList<Integer> keyList = new ArrayList<Integer>(treeMap.keySet()); // Extract the values from the TreeMap // using TreeMap.values() and // assign them to valueList of type ArrayList ArrayList<String> valueList = new ArrayList<String>(treeMap.values()); // printing the keyList System.out.println( \"List of keys of the given Map : \" + keyList); // printing the valueList System.out.println( \"List of values of the given Map : \" + valueList); } // Driver Method public static void main(String args[]) { // inserting data into the TreeMap // using TreeMap.put() method treeMap.put(1, \"Welcome\"); treeMap.put(2, \"To\"); treeMap.put(3, \"Geeks\"); treeMap.put(4, \"For\"); treeMap.put(5, \"Geeks\"); // printing the TreeMap System.out.println(\"The TreeMap is : \" + treeMap); // calling convertMapToList() method convertMapToList(); }}", "e": 2766, "s": 1288, "text": null }, { "code": null, "e": 2941, "s": 2766, "text": "The TreeMap is : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}\nList of keys of the given Map : [1, 2, 3, 4, 5]\nList of values of the given Map : [Welcome, To, Geeks, For, Geeks]" }, { "code": null, "e": 3156, "s": 2941, "text": "In the below approach, we directly converted the entire TreeMap to ArrayList with both keys and values together. For this, we have to use Entry object. To use this approach, import the package java.util.Map.Entry. " }, { "code": null, "e": 3325, "s": 3156, "text": "Here the keys and values in the TreeMap will directly get converted to ArrayList and the key and value for each index will be displayed as “key=value” in the ArrayList." }, { "code": null, "e": 3376, "s": 3325, "text": "Step 1: Declare and add the values in the TreeMap." }, { "code": null, "e": 3422, "s": 3376, "text": "Step 2: Call the function convertMaptoList()." }, { "code": null, "e": 3611, "s": 3422, "text": "Step 3: Declare the ArrayList with the Entry object in the function and specify the method TreeMap.entrySet() in the ArrayList constructor. It will convert the TreeMap values to ArrayList." }, { "code": null, "e": 3650, "s": 3611, "text": "Step 4: Print the converted ArrayList." }, { "code": null, "e": 3655, "s": 3650, "text": "Java" }, { "code": "import java.util.*;import java.util.Map.Entry; public class GFG { static TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); static void convertMapToList() { List<Entry> keyList = new ArrayList<Entry>(treeMap.entrySet()); System.out.println(\"Tree Map to ArrayList :\" + keyList); } public static void main(String[] args) { treeMap.put(1, \"Welcome\"); treeMap.put(2, \"To\"); treeMap.put(3, \"Geeks\"); treeMap.put(4, \"For\"); treeMap.put(5, \"Geeks\"); // printing the TreeMap System.out.println(\"The TreeMap is : \" + treeMap); // calling convertMapToList() method convertMapToList(); }}", "e": 4397, "s": 3655, "text": null }, { "code": null, "e": 4524, "s": 4397, "text": "The TreeMap is : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}\nTree Map to ArrayList :[1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks]\n" }, { "code": null, "e": 4543, "s": 4524, "text": "keerthikarathan123" }, { "code": null, "e": 4558, "s": 4543, "text": "Java-ArrayList" }, { "code": null, "e": 4575, "s": 4558, "text": "Java-Collections" }, { "code": null, "e": 4588, "s": 4575, "text": "java-TreeMap" }, { "code": null, "e": 4595, "s": 4588, "text": "Picked" }, { "code": null, "e": 4619, "s": 4595, "text": "Technical Scripter 2020" }, { "code": null, "e": 4624, "s": 4619, "text": "Java" }, { "code": null, "e": 4638, "s": 4624, "text": "Java Programs" }, { "code": null, "e": 4657, "s": 4638, "text": "Technical Scripter" }, { "code": null, "e": 4662, "s": 4657, "text": "Java" }, { "code": null, "e": 4679, "s": 4662, "text": "Java-Collections" }, { "code": null, "e": 4777, "s": 4679, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4792, "s": 4777, "text": "Stream In Java" }, { "code": null, "e": 4813, "s": 4792, "text": "Constructors in Java" }, { "code": null, "e": 4834, "s": 4813, "text": "Introduction to Java" }, { "code": null, "e": 4853, "s": 4834, "text": "Exceptions in Java" }, { "code": null, "e": 4879, "s": 4853, "text": "Java Programming Examples" }, { "code": null, "e": 4905, "s": 4879, "text": "Java Programming Examples" }, { "code": null, "e": 4939, "s": 4905, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4986, "s": 4939, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 5021, "s": 4986, "text": "Traverse Through a HashMap in Java" } ]
GATE-CS-2014-(Set-2) - GeeksforGeeks
11 Oct, 2021 India is a post-colonial country because Column 1 Column 2 1) eradicate P) misrepresent 2) distort Q) soak completely 3) saturate R) use 4) utilize S) destroy utterly From 2 to 198 there are 19 multiples of 10. These are 10,20,30.....180,190. This is an A.P series, whose sum is (n/2{a1 + aN}), where a1 and aN are the 1st and last terms respectively. Putting in the formula, a1 = 10, aN = 190. Sum = Sn = (19/2{10 + 190 }) = 1900 Average = Sum / Total number = 1900 / 19 = 100. let x = the given expression. Now squaring both sides. (x)^2 = 12 + x (x)^2 - x - 12 = 0 Now solve this quadratic equation for finding the roots(value of x, or this expression). (x-4)(x+3) = 0 hence x = 4. A is incorrect because First line says that Kaliningrad (Koenigsberg before war) had a majority of the German population before the war. So, it was historically German and not Russian. B is correct as although Kaliningrad is not contiguous with the rest of Russia (being surrounded by countries of Poland in the south and west, Lithuania in the east and Baltic sea on the north), it has a predominantly Russian population. C cannot be inferred from the passage as it is nowhere in the passage what the original Russian name of Koenigsberg was. D is also not true because no data about the route is mentioned in the passage. A contradicts the conclusion of the municipal authorities. So, A is not the correct choice. B is an incorrect choice because there is no data in the passage relating the reporting of cases and the efficiency of the administrative capabilities of the municipal authorities. C is also incorrect as it contradicts the conclusion of the municipal authorities. D is the correct choice as both malarial fever and dengue fever are caused by mosquito bite. If dengue fever had increased because of some other reason other than that concluded by the municipal authorities, then there would not have been increase in the people with malarial fever. This statement supports the conclusion of the municipal authorities. Here we use the modulus property, which says: |x| = x when x >= 0 |x| = -x when x < 0 i.e. range of a modulus function is always positive. Now, given that |x^2 – 2x + 3| = 11, we can say that x^2 – 2x + 3 = +11 ----------------(1) and x2 – 2x + 3 = -11------------------(2) Solving 1st equation, we get real roots as 4 and -2. Solving 2nd eq, we get imaginary roots, hence we ignore them. Now, for eq |- x^3 + x^2 – x|, we put 4 and -2 in place of x. putting x = 4, we get |-4^3 + 4^2-4| = |-64+16-4| = 52 putting x = -2 we get |-(-2)^3 + (-2)^2 - (-2)| = 14 so |- x^3 + x^2 – x| has possible values as 52 and 14 Let x represent the males and y represent the females. In 2008. x / y = 2.5 -----------(1) In 2009. M / 2y = 3-------------(2) where M is the total number of males in 2009. Now x = 2.5y (from (1)) and M = 6y ( from (2)) hence increased number of males in 2009 are M - x = 6y - 2.5y = 3.5y Now the increase in % of males = (change in no of males / initial number)*100 = (3.5y / x )*100 = (3.5 / 2.5)*100 = 140 (given x/y = 2.5) Hence, B is the right option. Speed of the Hour hand = ( 360 degree ) / ( 12 * 60 minutes ) = 0.5 degree / minute. Speed of the minute hand = ( 360 degree ) / ( 60 minutes ) = 6 degree / minute. (180 - 6t) + 0.5t, when the minute hand is behind the hour hand or, 6t - (180 + 0.5t), when the minute hand is ahead of hour hand, Now the the question asks for angle of 60 degree. Hence, (180 - 6t) + 0.5t = 60 , we get t = 21.8 minute and 6t - ( 180 + 0.5t ) = 60, we get t = 48 minutess 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, ... Software Testing - Web Based Testing What are the different ways of Data Representation? Bash Script - Command Substitution SDE SHEET - A Complete Guide for SDE Preparation 7 Highest Paying Programming Languages For Freelancers in 2022 DSA Sheet by Love Babbar How to Create a Shell Script in linux How To Convert Numpy Array To Tensor? 7 Best React Project Ideas For Beginners in 2022
[ { "code": null, "e": 29577, "s": 29549, "text": "\n11 Oct, 2021" }, { "code": null, "e": 29618, "s": 29577, "text": "India is a post-colonial country because" }, { "code": null, "e": 29786, "s": 29618, "text": " Column 1 Column 2\n1) eradicate P) misrepresent\n2) distort Q) soak completely\n3) saturate R) use\n4) utilize S) destroy utterly " }, { "code": null, "e": 30106, "s": 29786, "text": "From 2 to 198 there are 19 multiples of 10.\n\nThese are 10,20,30.....180,190.\n\nThis is an A.P series, whose sum is (n/2{a1 + aN}), \nwhere a1 and aN are the 1st and last terms respectively.\n\nPutting in the formula,\n\na1 = 10, aN = 190.\n\nSum = Sn = (19/2{10 + 190 }) = 1900\n\nAverage = Sum / Total number = 1900 / 19 = 100. " }, { "code": null, "e": 30317, "s": 30106, "text": "let x = the given expression.\nNow squaring both sides.\n\n(x)^2 = 12 + x\n(x)^2 - x - 12 = 0\n\nNow solve this quadratic equation for finding the \nroots(value of x, or this expression).\n(x-4)(x+3) = 0\n\nhence x = 4.\n" }, { "code": null, "e": 30502, "s": 30317, "text": "A is incorrect because First line says that Kaliningrad (Koenigsberg before war) had a majority of the German population before the war. So, it was historically German and not Russian." }, { "code": null, "e": 30740, "s": 30502, "text": "B is correct as although Kaliningrad is not contiguous with the rest of Russia (being surrounded by countries of Poland in the south and west, Lithuania in the east and Baltic sea on the north), it has a predominantly Russian population." }, { "code": null, "e": 30861, "s": 30740, "text": "C cannot be inferred from the passage as it is nowhere in the passage what the original Russian name of Koenigsberg was." }, { "code": null, "e": 30941, "s": 30861, "text": "D is also not true because no data about the route is mentioned in the passage." }, { "code": null, "e": 31033, "s": 30941, "text": "A contradicts the conclusion of the municipal authorities. So, A is not the correct choice." }, { "code": null, "e": 31214, "s": 31033, "text": "B is an incorrect choice because there is no data in the passage relating the reporting of cases and the efficiency of the administrative capabilities of the municipal authorities." }, { "code": null, "e": 31297, "s": 31214, "text": "C is also incorrect as it contradicts the conclusion of the municipal authorities." }, { "code": null, "e": 31649, "s": 31297, "text": "D is the correct choice as both malarial fever and dengue fever are caused by mosquito bite. If dengue fever had increased because of some other reason other than that concluded by the municipal authorities, then there would not have been increase in the people with malarial fever. This statement supports the conclusion of the municipal authorities." }, { "code": null, "e": 32277, "s": 31649, "text": "Here we use the modulus property, which says:\n\n|x| = x when x >= 0\n\n|x| = -x when x < 0\n\ni.e. range of a modulus function is always positive.\n\nNow, given that |x^2 – 2x + 3| = 11, we can say that\n\nx^2 – 2x + 3 = +11 ----------------(1)\n\nand\n\nx2 – 2x + 3 = -11------------------(2)\n\nSolving 1st equation, we get real roots as 4 and -2.\n\nSolving 2nd eq, we get imaginary roots, hence we ignore them.\n\nNow, for eq |- x^3 + x^2 – x|, we put 4 and -2 in place of x.\n\nputting x = 4, we get |-4^3 + 4^2-4| = |-64+16-4| = 52\n\nputting x = -2 we get |-(-2)^3 + (-2)^2 - (-2)| = 14\n\nso |- x^3 + x^2 – x| has possible values as 52 and 14 " }, { "code": null, "e": 32778, "s": 32277, "text": "Let x represent the males and y represent the females.\n\nIn 2008.\nx / y = 2.5 -----------(1)\n\nIn 2009.\nM / 2y = 3-------------(2)\n\nwhere M is the total number of males in 2009.\n\nNow x = 2.5y (from (1))\nand M = 6y ( from (2))\n\nhence increased number of males in 2009 are \nM - x = 6y - 2.5y = 3.5y\n\nNow the increase in % of males =\n\n(change in no of males / initial number)*100\n\n= (3.5y / x )*100 = (3.5 / 2.5)*100 = 140 \n (given x/y = 2.5)\n\nHence, B is the right option." }, { "code": null, "e": 32993, "s": 32778, "text": "Speed of the Hour hand = ( 360 degree ) / ( 12 * 60 minutes ) \n = 0.5 degree / minute.\nSpeed of the minute hand = ( 360 degree ) / ( 60 minutes ) \n = 6 degree / minute." }, { "code": null, "e": 33328, "s": 32993, "text": "\n(180 - 6t) + 0.5t, when the minute hand is \n behind the hour hand or,\n\n6t - (180 + 0.5t), when the minute hand is \n ahead of hour hand,\n\nNow the the question asks for angle of 60 degree.\n\nHence, \n(180 - 6t) + 0.5t = 60 , we get t = 21.8 minute\nand\n6t - ( 180 + 0.5t ) = 60, we get t = 48 minutess" }, { "code": null, "e": 33426, "s": 33328, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 33500, "s": 33426, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 33537, "s": 33500, "text": "Software Testing - Web Based Testing" }, { "code": null, "e": 33589, "s": 33537, "text": "What are the different ways of Data Representation?" }, { "code": null, "e": 33624, "s": 33589, "text": "Bash Script - Command Substitution" }, { "code": null, "e": 33673, "s": 33624, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 33736, "s": 33673, "text": "7 Highest Paying Programming Languages For Freelancers in 2022" }, { "code": null, "e": 33761, "s": 33736, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33799, "s": 33761, "text": "How to Create a Shell Script in linux" }, { "code": null, "e": 33837, "s": 33799, "text": "How To Convert Numpy Array To Tensor?" } ]
How to Install Docker-CE in Redhat 8?
28 May, 2021 Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all the parts it needs, such as libraries and other dependencies, and deploy it as one package. Step 1: Open your Redhat 8 terminal. Your terminal would look like this. Also, make sure you are login as root. Step 2: Run the following commands. cd /etc/yum.repos.d/ ls Now you will see some files with .repo extension, as shown below. Step 3: Now we are going to create our own file docker.repo follow the below commands. cat > docker.repo [docker] baseurl=https://download.docker.com/linux/centos/7/x86_64/stable/ gpgcheck=0 In the next line press CTRL+D to stop appending data. If you want to check whether the file is created or not, run “ls” command and check for docker.repo, and if u want to see the content of the file run, “cat docker.repo“. Step 4: Now we are going to install docker so make sure you are connected to internet (try pinging in google). And run the following command. When asked for confirmation press ‘y‘. yum install docker-ce --nobest Wait for the process to complete. When the process completes docker is installed in your system. Step 5: To check you can run the following command- rpm -q docker-ce or systemctl start docker docker version At this stage, you have successfully installed Docker-CE in your Redhat 8 system. m27sanjay linux Shell How To Linux-Unix TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 May, 2021" }, { "code": null, "e": 292, "s": 28, "text": "Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all the parts it needs, such as libraries and other dependencies, and deploy it as one package." }, { "code": null, "e": 404, "s": 292, "text": "Step 1: Open your Redhat 8 terminal. Your terminal would look like this. Also, make sure you are login as root." }, { "code": null, "e": 440, "s": 404, "text": "Step 2: Run the following commands." }, { "code": null, "e": 464, "s": 440, "text": "cd /etc/yum.repos.d/\nls" }, { "code": null, "e": 530, "s": 464, "text": "Now you will see some files with .repo extension, as shown below." }, { "code": null, "e": 617, "s": 530, "text": "Step 3: Now we are going to create our own file docker.repo follow the below commands." }, { "code": null, "e": 721, "s": 617, "text": "cat > docker.repo\n[docker]\nbaseurl=https://download.docker.com/linux/centos/7/x86_64/stable/\ngpgcheck=0" }, { "code": null, "e": 778, "s": 721, "text": " In the next line press CTRL+D to stop appending data. " }, { "code": null, "e": 949, "s": 778, "text": " If you want to check whether the file is created or not, run “ls” command and check for docker.repo, and if u want to see the content of the file run, “cat docker.repo“." }, { "code": null, "e": 1061, "s": 949, "text": "Step 4: Now we are going to install docker so make sure you are connected to internet (try pinging in google). " }, { "code": null, "e": 1131, "s": 1061, "text": "And run the following command. When asked for confirmation press ‘y‘." }, { "code": null, "e": 1162, "s": 1131, "text": "yum install docker-ce --nobest" }, { "code": null, "e": 1261, "s": 1162, "text": " Wait for the process to complete. When the process completes docker is installed in your system. " }, { "code": null, "e": 1313, "s": 1261, "text": "Step 5: To check you can run the following command-" }, { "code": null, "e": 1330, "s": 1313, "text": "rpm -q docker-ce" }, { "code": null, "e": 1334, "s": 1330, "text": "or " }, { "code": null, "e": 1372, "s": 1334, "text": "systemctl start docker\ndocker version" }, { "code": null, "e": 1454, "s": 1372, "text": "At this stage, you have successfully installed Docker-CE in your Redhat 8 system." }, { "code": null, "e": 1464, "s": 1454, "text": "m27sanjay" }, { "code": null, "e": 1470, "s": 1464, "text": "linux" }, { "code": null, "e": 1476, "s": 1470, "text": "Shell" }, { "code": null, "e": 1483, "s": 1476, "text": "How To" }, { "code": null, "e": 1494, "s": 1483, "text": "Linux-Unix" }, { "code": null, "e": 1503, "s": 1494, "text": "TechTips" } ]
Supernetting in Network Layer
26 Oct, 2021 Supernetting is the opposite of Subnetting. In subnetting, a single big network is divided into multiple smaller subnetworks. In Supernetting, multiple networks are combined into a bigger network termed as a Supernetwork or Supernet. Supernetting is mainly used in Route Summarization, where routes to multiple networks with similar network prefixes are combined into a single routing entry, with the routing entry pointing to a Super network, encompassing all the networks. This in turn significantly reduces the size of routing tables and also the size of routing updates exchanged by routing protocols. More specifically, When multiple networks are combined to form a bigger network, it is termed super-netting Super netting is used in route aggregation to reduce the size of routing tables and routing table updates There are some points which should be kept in mind while supernetting: All the Networks should be contiguous. The block size of every network should be equal and must be in form of 2n. First Network id should be exactly divisible by whole size of supernet. All the Networks should be contiguous. The block size of every network should be equal and must be in form of 2n. First Network id should be exactly divisible by whole size of supernet. Example – Suppose 4 small networks of class C: 200.1.0.0, 200.1.1.0, 200.1.2.0, 200.1.3.0 Build a bigger network that has a single Network Id. Explanation – Before Supernetting routing table will look like as: First, let’s check whether three conditions are satisfied or not: Contiguous: You can easily see that all networks are contiguous all having size 256 hosts. Range of first Network from 200.1.0.0 to 200.1.0.255. If you add 1 in last IP address of first network that is 200.1.0.255 + 0.0.0.1, you will get the next network id which is 200.1.1.0. Similarly, check that all network are contiguous. Equal size of all network: As all networks are of class C, so all of them have a size of 256 which is in turn equal to 28. First IP address exactly divisible by total size: When a binary number is divided by 2n then last n bits are the remainder. Hence in order to prove that first IP address is exactly divisible by while size of Supernet Network. You can check that if last n v=bits are 0 or not. In the given example first IP is 200.1.0.0 and whole size of supernet is 4*28 = 210. If last 10 bits of first IP address are zero then IP will be divisible. Contiguous: You can easily see that all networks are contiguous all having size 256 hosts. Range of first Network from 200.1.0.0 to 200.1.0.255. If you add 1 in last IP address of first network that is 200.1.0.255 + 0.0.0.1, you will get the next network id which is 200.1.1.0. Similarly, check that all network are contiguous. Equal size of all network: As all networks are of class C, so all of them have a size of 256 which is in turn equal to 28. First IP address exactly divisible by total size: When a binary number is divided by 2n then last n bits are the remainder. Hence in order to prove that first IP address is exactly divisible by while size of Supernet Network. You can check that if last n v=bits are 0 or not. In the given example first IP is 200.1.0.0 and whole size of supernet is 4*28 = 210. If last 10 bits of first IP address are zero then IP will be divisible. In the given example first IP is 200.1.0.0 and whole size of supernet is 4*28 = 210. If last 10 bits of first IP address are zero then IP will be divisible. Last 10 bits of first IP address are zero (highlighted by green color). So 3rd condition is also satisfied. Control and reduce network traffic Helpful to solve the problem of lacking IP addresses Minimizes the routing table It cannot cover a different area of the network when combined All the networks should be in the same class and all IP should be contiguous Last 10 bits of first IP address are zero (highlighted by green color). So 3rd condition is also satisfied. Control and reduce network traffic Helpful to solve the problem of lacking IP addresses Minimizes the routing table It cannot cover a different area of the network when combined All the networks should be in the same class and all IP should be contiguous Last 10 bits of first IP address are zero (highlighted by green color). So 3rd condition is also satisfied. Control and reduce network traffic Helpful to solve the problem of lacking IP addresses Minimizes the routing table It cannot cover a different area of the network when combined All the networks should be in the same class and all IP should be contiguous Control and reduce network traffic Helpful to solve the problem of lacking IP addresses Minimizes the routing table It cannot cover a different area of the network when combined All the networks should be in the same class and all IP should be contiguous It cannot cover a different area of the network when combined All the networks should be in the same class and all IP should be contiguous shaztri soumalyachatterjee Pushpender007 Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Socket Programming in Python Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Introduction of Operating System - Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Oct, 2021" }, { "code": null, "e": 287, "s": 52, "text": "Supernetting is the opposite of Subnetting. In subnetting, a single big network is divided into multiple smaller subnetworks. In Supernetting, multiple networks are combined into a bigger network termed as a Supernetwork or Supernet. " }, { "code": null, "e": 660, "s": 287, "text": "Supernetting is mainly used in Route Summarization, where routes to multiple networks with similar network prefixes are combined into a single routing entry, with the routing entry pointing to a Super network, encompassing all the networks. This in turn significantly reduces the size of routing tables and also the size of routing updates exchanged by routing protocols. " }, { "code": null, "e": 680, "s": 660, "text": "More specifically, " }, { "code": null, "e": 773, "s": 682, "text": "When multiple networks are combined to form a bigger network, it is termed super-netting " }, { "code": null, "e": 881, "s": 773, "text": "Super netting is used in route aggregation to reduce the size of routing tables and routing table updates " }, { "code": null, "e": 954, "s": 881, "text": "There are some points which should be kept in mind while supernetting: " }, { "code": null, "e": 1144, "s": 954, "text": "All the Networks should be contiguous. The block size of every network should be equal and must be in form of 2n. First Network id should be exactly divisible by whole size of supernet. " }, { "code": null, "e": 1185, "s": 1144, "text": "All the Networks should be contiguous. " }, { "code": null, "e": 1262, "s": 1185, "text": "The block size of every network should be equal and must be in form of 2n. " }, { "code": null, "e": 1336, "s": 1262, "text": "First Network id should be exactly divisible by whole size of supernet. " }, { "code": null, "e": 1385, "s": 1336, "text": "Example – Suppose 4 small networks of class C: " }, { "code": null, "e": 1429, "s": 1385, "text": "200.1.0.0, \n200.1.1.0,\n200.1.2.0,\n200.1.3.0" }, { "code": null, "e": 1483, "s": 1429, "text": "Build a bigger network that has a single Network Id. " }, { "code": null, "e": 1551, "s": 1483, "text": "Explanation – Before Supernetting routing table will look like as: " }, { "code": null, "e": 1620, "s": 1553, "text": "First, let’s check whether three conditions are satisfied or not: " }, { "code": null, "e": 2510, "s": 1622, "text": "Contiguous: You can easily see that all networks are contiguous all having size 256 hosts. Range of first Network from 200.1.0.0 to 200.1.0.255. If you add 1 in last IP address of first network that is 200.1.0.255 + 0.0.0.1, you will get the next network id which is 200.1.1.0. Similarly, check that all network are contiguous. Equal size of all network: As all networks are of class C, so all of them have a size of 256 which is in turn equal to 28. First IP address exactly divisible by total size: When a binary number is divided by 2n then last n bits are the remainder. Hence in order to prove that first IP address is exactly divisible by while size of Supernet Network. You can check that if last n v=bits are 0 or not. In the given example first IP is 200.1.0.0 and whole size of supernet is 4*28 = 210. If last 10 bits of first IP address are zero then IP will be divisible. " }, { "code": null, "e": 2840, "s": 2510, "text": "Contiguous: You can easily see that all networks are contiguous all having size 256 hosts. Range of first Network from 200.1.0.0 to 200.1.0.255. If you add 1 in last IP address of first network that is 200.1.0.255 + 0.0.0.1, you will get the next network id which is 200.1.1.0. Similarly, check that all network are contiguous. " }, { "code": null, "e": 2967, "s": 2842, "text": "Equal size of all network: As all networks are of class C, so all of them have a size of 256 which is in turn equal to 28. " }, { "code": null, "e": 3404, "s": 2969, "text": "First IP address exactly divisible by total size: When a binary number is divided by 2n then last n bits are the remainder. Hence in order to prove that first IP address is exactly divisible by while size of Supernet Network. You can check that if last n v=bits are 0 or not. In the given example first IP is 200.1.0.0 and whole size of supernet is 4*28 = 210. If last 10 bits of first IP address are zero then IP will be divisible. " }, { "code": null, "e": 3562, "s": 3404, "text": "In the given example first IP is 200.1.0.0 and whole size of supernet is 4*28 = 210. If last 10 bits of first IP address are zero then IP will be divisible. " }, { "code": null, "e": 3932, "s": 3564, "text": "Last 10 bits of first IP address are zero (highlighted by green color). So 3rd condition is also satisfied. Control and reduce network traffic Helpful to solve the problem of lacking IP addresses Minimizes the routing table It cannot cover a different area of the network when combined All the networks should be in the same class and all IP should be contiguous " }, { "code": null, "e": 4300, "s": 3932, "text": "Last 10 bits of first IP address are zero (highlighted by green color). So 3rd condition is also satisfied. Control and reduce network traffic Helpful to solve the problem of lacking IP addresses Minimizes the routing table It cannot cover a different area of the network when combined All the networks should be in the same class and all IP should be contiguous " }, { "code": null, "e": 4409, "s": 4300, "text": "Last 10 bits of first IP address are zero (highlighted by green color). So 3rd condition is also satisfied. " }, { "code": null, "e": 4669, "s": 4409, "text": "Control and reduce network traffic Helpful to solve the problem of lacking IP addresses Minimizes the routing table It cannot cover a different area of the network when combined All the networks should be in the same class and all IP should be contiguous " }, { "code": null, "e": 4706, "s": 4669, "text": "Control and reduce network traffic " }, { "code": null, "e": 4761, "s": 4706, "text": "Helpful to solve the problem of lacking IP addresses " }, { "code": null, "e": 4931, "s": 4761, "text": "Minimizes the routing table It cannot cover a different area of the network when combined All the networks should be in the same class and all IP should be contiguous " }, { "code": null, "e": 4995, "s": 4931, "text": "It cannot cover a different area of the network when combined " }, { "code": null, "e": 5074, "s": 4995, "text": "All the networks should be in the same class and all IP should be contiguous " }, { "code": null, "e": 5082, "s": 5074, "text": "shaztri" }, { "code": null, "e": 5101, "s": 5082, "text": "soumalyachatterjee" }, { "code": null, "e": 5115, "s": 5101, "text": "Pushpender007" }, { "code": null, "e": 5133, "s": 5115, "text": "Computer Networks" }, { "code": null, "e": 5141, "s": 5133, "text": "GATE CS" }, { "code": null, "e": 5159, "s": 5141, "text": "Computer Networks" }, { "code": null, "e": 5257, "s": 5159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5287, "s": 5257, "text": "GSM in Wireless Communication" }, { "code": null, "e": 5316, "s": 5287, "text": "Socket Programming in Python" }, { "code": null, "e": 5350, "s": 5316, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 5376, "s": 5350, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 5406, "s": 5376, "text": "Wireless Application Protocol" }, { "code": null, "e": 5430, "s": 5406, "text": "ACID Properties in DBMS" }, { "code": null, "e": 5457, "s": 5430, "text": "Types of Operating Systems" }, { "code": null, "e": 5478, "s": 5457, "text": "Normal Forms in DBMS" }, { "code": null, "e": 5527, "s": 5478, "text": "Page Replacement Algorithms in Operating Systems" } ]
java.net.InetAddress Class in Java
29 Mar, 2021 public class InetAddress extends Object implements Serializable: The java.net.InetAddress class provides methods to get the IP address of any hostname. An IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. There are 2 types of addresses : Unicast — An identifier for a single interface.Multicast — An identifier for a set of interfaces. Unicast — An identifier for a single interface. Multicast — An identifier for a set of interfaces. InetAddress – Factory Methods : The InetAddress class is used to encapsulate both, the numerical IP address and the domain name for that address. The InetAddress class has no visible constructors. The InetAddress class has the inability to create objects directly, hence factory methods are used for the purpose. Factory Methods are static methods in a class that return an object of that class. There are 5 factory methods available in InetAddress class – Below is the Java implementation of InetAddress class to demonstrate the use of factory methods – Java import java.io.*;import java.net.*;import java.util.*; class GFG { public static void main(String[] args) throws UnknownHostException { // To get and print InetAddress of Local Host InetAddress address1 = InetAddress.getLocalHost(); System.out.println("InetAddress of Local Host : " + address1); // To get and print InetAddress of Named Host InetAddress address2 = InetAddress.getByName("45.22.30.39"); System.out.println("InetAddress of Named Host : " + address2); // To get and print ALL InetAddresses of Named Host InetAddress address3[] = InetAddress.getAllByName("172.19.25.29"); for (int i = 0; i < address3.length; i++) { System.out.println( "ALL InetAddresses of Named Host : " + address3[i]); } // To get and print InetAddresses of // Host with specified IP Address byte IPAddress[] = { 125, 0, 0, 1 }; InetAddress address4 = InetAddress.getByAddress(IPAddress); System.out.println( "InetAddresses of Host with specified IP Address : " + address4); // To get and print InetAddresses of Host // with specified IP Address and hostname byte[] IPAddress2 = { 105, 22, (byte)223, (byte)186 }; InetAddress address5 = InetAddress.getByAddress( "gfg.com", IPAddress2); System.out.println( "InetAddresses of Host with specified IP Address and hostname : " + address5); }} InetAddress of Local Host : localhost/127.0.0.1 InetAddress of Named Host : /45.22.30.39 ALL InetAddresses of Named Host : /172.19.25.29 InetAddresses of Host with specified IP Address : /125.0.0.1 InetAddresses of Host with specified IP Address and hostname : gfg.com/105.22.223.186 InetAddress — Instance Methods : InetAddress class has plenty of instance methods that can be called using the object. The instance methods are – Below is the Java implementation of InetAddress class to demonstrate the use of instance methods – Java import java.io.*;import java.net.*;import java.util.*; class GFG { public static void main(String[] args) throws UnknownHostException { InetAddress address1 = InetAddress.getByName("45.22.30.39"); InetAddress address2 = InetAddress.getByName("45.22.30.39"); InetAddress address3 = InetAddress.getByName("172.19.25.29"); // true, as clearly seen above System.out.println( "Is Address-1 equals to Address-2? : " + address1.equals(address2)); // false System.out.println( "Is Address-1 equals to Address-3? : " + address1.equals(address3)); // returns IP address System.out.println("IP Address : " + address1.getHostAddress()); // returns host name, // which is same as IP // address in this case System.out.println( "Host Name for this IP Address : " + address1.getHostName()); // returns address in bytes System.out.println("IP Address in bytes : " + address1.getAddress()); // false, as the given site // has only one server System.out.println("Is this Address Multicast? : " + address1.isMulticastAddress()); System.out.println("Address in string form : " + address1.toString()); // returns fully qualified // domain name for this IP address. System.out.println( "Fully qualified domain name for this IP address : " + address1.getCanonicalHostName()); // hashcode for this IP address. System.out.println("Hashcode for this IP address : " + address1.hashCode()); // to check if the InetAddress is // an unpredictable address.. System.out.println( "Is the InetAddress an unpredictable address? : " + address1.isAnyLocalAddress()); }} Is Address-1 equals to Address-2? : true Is Address-1 equals to Address-3? : false IP Address : 45.22.30.39 Host Name for this IP Address : 45.22.30.39 IP Address in bytes : [B@579bb367 Is this Address Multicast? : false Address in string form : 45.22.30.39/45.22.30.39 Fully qualified domain name for this IP address : 45.22.30.39 Hashcode for this IP address : 756424231 Is the InetAddress an unpredictable address? : false Java-net-package Picked 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 HashMap in Java with Examples ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Mar, 2021" }, { "code": null, "e": 117, "s": 52, "text": "public class InetAddress extends Object implements Serializable:" }, { "code": null, "e": 325, "s": 117, "text": "The java.net.InetAddress class provides methods to get the IP address of any hostname. An IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. " }, { "code": null, "e": 358, "s": 325, "text": "There are 2 types of addresses :" }, { "code": null, "e": 456, "s": 358, "text": "Unicast — An identifier for a single interface.Multicast — An identifier for a set of interfaces." }, { "code": null, "e": 504, "s": 456, "text": "Unicast — An identifier for a single interface." }, { "code": null, "e": 555, "s": 504, "text": "Multicast — An identifier for a set of interfaces." }, { "code": null, "e": 587, "s": 555, "text": "InetAddress – Factory Methods :" }, { "code": null, "e": 951, "s": 587, "text": "The InetAddress class is used to encapsulate both, the numerical IP address and the domain name for that address. The InetAddress class has no visible constructors. The InetAddress class has the inability to create objects directly, hence factory methods are used for the purpose. Factory Methods are static methods in a class that return an object of that class." }, { "code": null, "e": 1013, "s": 951, "text": "There are 5 factory methods available in InetAddress class – " }, { "code": null, "e": 1112, "s": 1013, "text": "Below is the Java implementation of InetAddress class to demonstrate the use of factory methods – " }, { "code": null, "e": 1117, "s": 1112, "text": "Java" }, { "code": "import java.io.*;import java.net.*;import java.util.*; class GFG { public static void main(String[] args) throws UnknownHostException { // To get and print InetAddress of Local Host InetAddress address1 = InetAddress.getLocalHost(); System.out.println(\"InetAddress of Local Host : \" + address1); // To get and print InetAddress of Named Host InetAddress address2 = InetAddress.getByName(\"45.22.30.39\"); System.out.println(\"InetAddress of Named Host : \" + address2); // To get and print ALL InetAddresses of Named Host InetAddress address3[] = InetAddress.getAllByName(\"172.19.25.29\"); for (int i = 0; i < address3.length; i++) { System.out.println( \"ALL InetAddresses of Named Host : \" + address3[i]); } // To get and print InetAddresses of // Host with specified IP Address byte IPAddress[] = { 125, 0, 0, 1 }; InetAddress address4 = InetAddress.getByAddress(IPAddress); System.out.println( \"InetAddresses of Host with specified IP Address : \" + address4); // To get and print InetAddresses of Host // with specified IP Address and hostname byte[] IPAddress2 = { 105, 22, (byte)223, (byte)186 }; InetAddress address5 = InetAddress.getByAddress( \"gfg.com\", IPAddress2); System.out.println( \"InetAddresses of Host with specified IP Address and hostname : \" + address5); }}", "e": 2746, "s": 1117, "text": null }, { "code": null, "e": 3030, "s": 2746, "text": "InetAddress of Local Host : localhost/127.0.0.1\nInetAddress of Named Host : /45.22.30.39\nALL InetAddresses of Named Host : /172.19.25.29\nInetAddresses of Host with specified IP Address : /125.0.0.1\nInetAddresses of Host with specified IP Address and hostname : gfg.com/105.22.223.186" }, { "code": null, "e": 3063, "s": 3030, "text": "InetAddress — Instance Methods :" }, { "code": null, "e": 3177, "s": 3063, "text": "InetAddress class has plenty of instance methods that can be called using the object. The instance methods are – " }, { "code": null, "e": 3277, "s": 3177, "text": "Below is the Java implementation of InetAddress class to demonstrate the use of instance methods – " }, { "code": null, "e": 3282, "s": 3277, "text": "Java" }, { "code": "import java.io.*;import java.net.*;import java.util.*; class GFG { public static void main(String[] args) throws UnknownHostException { InetAddress address1 = InetAddress.getByName(\"45.22.30.39\"); InetAddress address2 = InetAddress.getByName(\"45.22.30.39\"); InetAddress address3 = InetAddress.getByName(\"172.19.25.29\"); // true, as clearly seen above System.out.println( \"Is Address-1 equals to Address-2? : \" + address1.equals(address2)); // false System.out.println( \"Is Address-1 equals to Address-3? : \" + address1.equals(address3)); // returns IP address System.out.println(\"IP Address : \" + address1.getHostAddress()); // returns host name, // which is same as IP // address in this case System.out.println( \"Host Name for this IP Address : \" + address1.getHostName()); // returns address in bytes System.out.println(\"IP Address in bytes : \" + address1.getAddress()); // false, as the given site // has only one server System.out.println(\"Is this Address Multicast? : \" + address1.isMulticastAddress()); System.out.println(\"Address in string form : \" + address1.toString()); // returns fully qualified // domain name for this IP address. System.out.println( \"Fully qualified domain name for this IP address : \" + address1.getCanonicalHostName()); // hashcode for this IP address. System.out.println(\"Hashcode for this IP address : \" + address1.hashCode()); // to check if the InetAddress is // an unpredictable address.. System.out.println( \"Is the InetAddress an unpredictable address? : \" + address1.isAnyLocalAddress()); }}", "e": 5313, "s": 3282, "text": null }, { "code": null, "e": 5739, "s": 5313, "text": "Is Address-1 equals to Address-2? : true\nIs Address-1 equals to Address-3? : false\nIP Address : 45.22.30.39\nHost Name for this IP Address : 45.22.30.39\nIP Address in bytes : [B@579bb367\nIs this Address Multicast? : false\nAddress in string form : 45.22.30.39/45.22.30.39\nFully qualified domain name for this IP address : 45.22.30.39\nHashcode for this IP address : 756424231\nIs the InetAddress an unpredictable address? : false" }, { "code": null, "e": 5756, "s": 5739, "text": "Java-net-package" }, { "code": null, "e": 5763, "s": 5756, "text": "Picked" }, { "code": null, "e": 5768, "s": 5763, "text": "Java" }, { "code": null, "e": 5773, "s": 5768, "text": "Java" }, { "code": null, "e": 5871, "s": 5773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5922, "s": 5871, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 5953, "s": 5922, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5983, "s": 5953, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6001, "s": 5983, "text": "ArrayList in Java" }, { "code": null, "e": 6021, "s": 6001, "text": "Collections in Java" }, { "code": null, "e": 6036, "s": 6021, "text": "Stream In Java" }, { "code": null, "e": 6068, "s": 6036, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 6092, "s": 6068, "text": "Singleton Class in Java" }, { "code": null, "e": 6104, "s": 6092, "text": "Set in Java" } ]
Python Packages
27 Dec, 2021 We usually organize our files in different folders and subfolders based on some criteria, so that they can be managed easily and efficiently. For example, we keep all our games in a Games folder and we can even subcategorize according to the genre of the game or something like this. The same analogy is followed by the Python package. A Python module may contain several classes, functions, variables, etc. whereas a Python package can contains several module. In simpler terms a package is folder that contains various modules as files. Let’s create a package named mypckg that will contain two modules mod1 and mod2. To create this module follow the below steps – Create a folder named mypckg. Inside this folder create an empty Python file i.e. __init__.py Then create two modules mod1 and mod2 in this folder. Python3 def gfg(): print("Welcome to GFG") Python3 def sum(a, b): return a+b The hierarchy of the our package looks like this – mypckg | | ---__init__.py | | ---mod1.py | | ---mod2.py __init__.py helps the Python interpreter to recognise the folder as package. It also specifies the resources to be imported from the modules. If the __init__.py is empty this means that all the functions of the modules will be imported. We can also specify the functions from each module to be made available. For example, we can also create the __init__.py file for the above module as – Python3 from .mod1 import gfgfrom .mod2 import sum This __init__.py will only allow the gfg and sum functions from the mod1 and mod2 modules to be imported. We can import these modules using the from...import statement and the dot(.) operator. Syntax: import package_name.module_name We will import the modules from the above created package and will use the functions inside those modules. Python3 from mypckg import mod1from mypckg import mod2 mod1.gfg()res = mod2.sum(1, 2)print(res) Output: Welcome to GFG 3 We can also import the specific function also using the same syntax. Python3 from mypckg.mod1 import gfgfrom mypckg.mod2 import sum gfg()res = sum(1, 2)print(res) Output: Welcome to GFG 3 surinderdawra388 sweetyty rajeev0719singh kk773572498 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Dec, 2021" }, { "code": null, "e": 391, "s": 54, "text": "We usually organize our files in different folders and subfolders based on some criteria, so that they can be managed easily and efficiently. For example, we keep all our games in a Games folder and we can even subcategorize according to the genre of the game or something like this. The same analogy is followed by the Python package. " }, { "code": null, "e": 594, "s": 391, "text": "A Python module may contain several classes, functions, variables, etc. whereas a Python package can contains several module. In simpler terms a package is folder that contains various modules as files." }, { "code": null, "e": 723, "s": 594, "text": "Let’s create a package named mypckg that will contain two modules mod1 and mod2. To create this module follow the below steps – " }, { "code": null, "e": 753, "s": 723, "text": "Create a folder named mypckg." }, { "code": null, "e": 817, "s": 753, "text": "Inside this folder create an empty Python file i.e. __init__.py" }, { "code": null, "e": 871, "s": 817, "text": "Then create two modules mod1 and mod2 in this folder." }, { "code": null, "e": 879, "s": 871, "text": "Python3" }, { "code": "def gfg(): print(\"Welcome to GFG\")", "e": 917, "s": 879, "text": null }, { "code": null, "e": 925, "s": 917, "text": "Python3" }, { "code": "def sum(a, b): return a+b", "e": 954, "s": 925, "text": null }, { "code": null, "e": 1006, "s": 954, "text": "The hierarchy of the our package looks like this – " }, { "code": null, "e": 1062, "s": 1006, "text": "mypckg\n|\n|\n---__init__.py\n|\n|\n---mod1.py\n|\n|\n---mod2.py" }, { "code": null, "e": 1372, "s": 1062, "text": "__init__.py helps the Python interpreter to recognise the folder as package. It also specifies the resources to be imported from the modules. If the __init__.py is empty this means that all the functions of the modules will be imported. We can also specify the functions from each module to be made available." }, { "code": null, "e": 1452, "s": 1372, "text": "For example, we can also create the __init__.py file for the above module as – " }, { "code": null, "e": 1460, "s": 1452, "text": "Python3" }, { "code": "from .mod1 import gfgfrom .mod2 import sum", "e": 1503, "s": 1460, "text": null }, { "code": null, "e": 1609, "s": 1503, "text": "This __init__.py will only allow the gfg and sum functions from the mod1 and mod2 modules to be imported." }, { "code": null, "e": 1697, "s": 1609, "text": "We can import these modules using the from...import statement and the dot(.) operator. " }, { "code": null, "e": 1705, "s": 1697, "text": "Syntax:" }, { "code": null, "e": 1737, "s": 1705, "text": "import package_name.module_name" }, { "code": null, "e": 1844, "s": 1737, "text": "We will import the modules from the above created package and will use the functions inside those modules." }, { "code": null, "e": 1852, "s": 1844, "text": "Python3" }, { "code": "from mypckg import mod1from mypckg import mod2 mod1.gfg()res = mod2.sum(1, 2)print(res)", "e": 1940, "s": 1852, "text": null }, { "code": null, "e": 1948, "s": 1940, "text": "Output:" }, { "code": null, "e": 1965, "s": 1948, "text": "Welcome to GFG\n3" }, { "code": null, "e": 2034, "s": 1965, "text": "We can also import the specific function also using the same syntax." }, { "code": null, "e": 2042, "s": 2034, "text": "Python3" }, { "code": "from mypckg.mod1 import gfgfrom mypckg.mod2 import sum gfg()res = sum(1, 2)print(res)", "e": 2128, "s": 2042, "text": null }, { "code": null, "e": 2136, "s": 2128, "text": "Output:" }, { "code": null, "e": 2153, "s": 2136, "text": "Welcome to GFG\n3" }, { "code": null, "e": 2170, "s": 2153, "text": "surinderdawra388" }, { "code": null, "e": 2179, "s": 2170, "text": "sweetyty" }, { "code": null, "e": 2195, "s": 2179, "text": "rajeev0719singh" }, { "code": null, "e": 2207, "s": 2195, "text": "kk773572498" }, { "code": null, "e": 2214, "s": 2207, "text": "Python" }, { "code": null, "e": 2312, "s": 2214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2344, "s": 2312, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2371, "s": 2344, "text": "Python Classes and Objects" }, { "code": null, "e": 2392, "s": 2371, "text": "Python OOPs Concepts" }, { "code": null, "e": 2415, "s": 2392, "text": "Introduction To PYTHON" }, { "code": null, "e": 2471, "s": 2415, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2502, "s": 2471, "text": "Python | os.path.join() method" }, { "code": null, "e": 2544, "s": 2502, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2586, "s": 2544, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2625, "s": 2586, "text": "Python | Get unique values from a list" } ]
Is it possible to use this keyword in static context in java?
A static method or, block belongs to the class and these will be loaded into the memory along with the class. You can invoke static methods without creating an object. (using the class name as reference). Whereas "this" in Java acts as a reference to the current object. But static contexts(methods and blocks) doesn't have any instance they belong to the class. In a simple sense, to use “this” the method should be invoked by an object, which is not always necessary with static methods. Therefore, you cannot use this keyword from a static method. In the following Java program, the class ThisExample contains a private variable name with setter and getter methods and an instance method display(). From the main method (which is static) we are trying to invoke the display() method using "this". Live Demo public class ThisExample { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void display() { System.out.println("name: "+this.getName()); } public static void main(String args[]) { this.display(); } } On compiling, this program gives you an error as shown below − ThisExample.java:17: error: non-static variable this cannot be referenced from a static context this.display(); ^ 1 error
[ { "code": null, "e": 1392, "s": 1187, "text": "A static method or, block belongs to the class and these will be loaded into the memory along with the class. You can invoke static methods without creating an object. (using the class name as reference)." }, { "code": null, "e": 1550, "s": 1392, "text": "Whereas \"this\" in Java acts as a reference to the current object. But static contexts(methods and blocks) doesn't have any instance they belong to the class." }, { "code": null, "e": 1677, "s": 1550, "text": "In a simple sense, to use “this” the method should be invoked by an object, which is not always necessary with static methods." }, { "code": null, "e": 1738, "s": 1677, "text": "Therefore, you cannot use this keyword from a static method." }, { "code": null, "e": 1987, "s": 1738, "text": "In the following Java program, the class ThisExample contains a private variable name with setter and getter methods and an instance method display(). From the main method (which is static) we are trying to invoke the display() method using \"this\"." }, { "code": null, "e": 1998, "s": 1987, "text": " Live Demo" }, { "code": null, "e": 2325, "s": 1998, "text": "public class ThisExample {\n private String name;\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public void display() {\n System.out.println(\"name: \"+this.getName());\n }\n public static void main(String args[]) {\n this.display();\n }\n}" }, { "code": null, "e": 2388, "s": 2325, "text": "On compiling, this program gives you an error as shown below −" }, { "code": null, "e": 2522, "s": 2388, "text": "ThisExample.java:17: error: non-static variable this cannot be referenced from a static context\n this.display();\n ^\n1 error" } ]
Debouncing in JavaScript
26 Jul, 2021 Debouncing in JavaScript is a practice used to improve browser performance. There might be some functionality in a web page which requires time-consuming computations. If such a method is invoked frequently, it might greatly affect the performance of the browser, as JavaScript is a single threaded language. Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, that it stalls the performance of the web page. In other words, it limits the rate at which a function gets invoked. <html> <body><button id="debounce"> Debounce</button><script>var button = document.getElementById("debounce");const debounce = (func, delay) => { let debounceTimer return function() { const context = this const args = arguments clearTimeout(debounceTimer) debounceTimer = setTimeout(() => func.apply(context, args), delay) }} button.addEventListener('click', debounce(function() { alert("Hello\nNo matter how many times you" + "click the debounce button, I get " + "executed once every 3 seconds!!") }, 3000));</script></body></html> Output: Alertbox after 3 seconds Hello No matter how many times you click the debounce button, I get executed once every 3 seconds!! Explanation: The button is attached to an event listener that calls the debounce function. The debounce function is provided 2 parameters – a function and a Number.Declared a variable debounceTimer, which as the name suggests, is used to actually call the function, received as a parameter after an interval of ‘delay’ milliseconds.If the debounce button is clicked only once, the debounce function gets called after the delay. However, if the debounce button is clicked once, and again clicked prior to the end of the delay, the initial delay is cleared and a fresh delay timer is started. The clearTimeout function is being used to achieve it. The general idea for debouncing is:1. Start with 0 timeout2. If the debounced function is called again, reset the timer to the specified delay3. In case of timeout, call the debounced functionThus every call to a debounce function, resets the timer and delays the call. Application:Debouncing can be applied in implementing suggestive text, where we wait for the user to stop typing for a few seconds before suggesting the text. thus, on every keystroke, we wait for some seconds before giving out suggestions.Another application of debouncing is in content-loading webpages like Facebook and Twitter where the user keeps on scrolling. In these scenarios, if the scroll event is fired too frequently, there might be a performance impact, as it contains lots of videos and images. Thus the scroll event must make use of debouncing. JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. JayantaTalukdar javascript-functions JavaScript-Misc 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 Hide or show elements in HTML using display property Difference Between PUT and PATCH Request 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": 52, "s": 24, "text": "\n26 Jul, 2021" }, { "code": null, "e": 578, "s": 52, "text": "Debouncing in JavaScript is a practice used to improve browser performance. There might be some functionality in a web page which requires time-consuming computations. If such a method is invoked frequently, it might greatly affect the performance of the browser, as JavaScript is a single threaded language. Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, that it stalls the performance of the web page. In other words, it limits the rate at which a function gets invoked." }, { "code": "<html> <body><button id=\"debounce\"> Debounce</button><script>var button = document.getElementById(\"debounce\");const debounce = (func, delay) => { let debounceTimer return function() { const context = this const args = arguments clearTimeout(debounceTimer) debounceTimer = setTimeout(() => func.apply(context, args), delay) }} button.addEventListener('click', debounce(function() { alert(\"Hello\\nNo matter how many times you\" + \"click the debounce button, I get \" + \"executed once every 3 seconds!!\") }, 3000));</script></body></html>", "e": 1227, "s": 578, "text": null }, { "code": null, "e": 1260, "s": 1227, "text": "Output: Alertbox after 3 seconds" }, { "code": null, "e": 1361, "s": 1260, "text": "Hello\nNo matter how many times you click the debounce button,\nI get executed once every 3 seconds!!\n" }, { "code": null, "e": 1374, "s": 1361, "text": "Explanation:" }, { "code": null, "e": 2007, "s": 1374, "text": "The button is attached to an event listener that calls the debounce function. The debounce function is provided 2 parameters – a function and a Number.Declared a variable debounceTimer, which as the name suggests, is used to actually call the function, received as a parameter after an interval of ‘delay’ milliseconds.If the debounce button is clicked only once, the debounce function gets called after the delay. However, if the debounce button is clicked once, and again clicked prior to the end of the delay, the initial delay is cleared and a fresh delay timer is started. The clearTimeout function is being used to achieve it." }, { "code": null, "e": 2277, "s": 2007, "text": "The general idea for debouncing is:1. Start with 0 timeout2. If the debounced function is called again, reset the timer to the specified delay3. In case of timeout, call the debounced functionThus every call to a debounce function, resets the timer and delays the call." }, { "code": null, "e": 2838, "s": 2277, "text": "Application:Debouncing can be applied in implementing suggestive text, where we wait for the user to stop typing for a few seconds before suggesting the text. thus, on every keystroke, we wait for some seconds before giving out suggestions.Another application of debouncing is in content-loading webpages like Facebook and Twitter where the user keeps on scrolling. In these scenarios, if the scroll event is fired too frequently, there might be a performance impact, as it contains lots of videos and images. Thus the scroll event must make use of debouncing." }, { "code": null, "e": 3057, "s": 2838, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 3073, "s": 3057, "text": "JayantaTalukdar" }, { "code": null, "e": 3094, "s": 3073, "text": "javascript-functions" }, { "code": null, "e": 3110, "s": 3094, "text": "JavaScript-Misc" }, { "code": null, "e": 3121, "s": 3110, "text": "JavaScript" }, { "code": null, "e": 3138, "s": 3121, "text": "Web Technologies" }, { "code": null, "e": 3236, "s": 3138, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3297, "s": 3236, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3369, "s": 3297, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3409, "s": 3369, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3462, "s": 3409, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3503, "s": 3462, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3536, "s": 3503, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3598, "s": 3536, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3659, "s": 3598, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3709, "s": 3659, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Difference between 3NF and BCNF in DBMS
15 Jan, 2021 1. Third Normal Form (3NF) :A relation is said to be in Third Normal Form (3NF), if it is in 2NF and when no non key attribute is transitively dependent on the primary key i.e., there is no transitive dependency. Also it should satisfy one of the below given conditions. For the function dependency C->D: C should be a super key and, D should be a prime attribute i.e, D should be a part of the candidate key. 3NF is used to reduce data duplication and to attain data integrity. Example:For the relation R(L, M, N, O, P) with functional dependencies as {L->M, MN->P, PO->L}: The candidate keys will be : {LNO, MNO, NOP} as the closure of LNO = {L, M, N, O, P} closure of MNO = {L, M, N, O, P} closure of NOP = {L, M, N, O, P} This relation is in 3NF as it is already in 2NF and has no transitive dependency. Also there is no non prime attribute that is deriving a non prime attribute. 2. Boyce-Codd Normal Form (BCNF) :BCNF stands for Boyce-Codd normal form and was made by R.F Boyce and E.F Codd in 1974.A functional dependency is said to be in BCNF if these properties hold: It should already be in 3NF. For a functional dependency say P->Q, P should be a super key. BCNF is an extension of 3NF and it is has more strict rules than 3NF. Also, it is considered to be more stronger than 3NF. Example:for the relation R(A, B, C, D) with functional dependencies as {A->B, A->C, C->D, C->A}: The candidate keys will be : {A, C} as the closure of A = {A, B, C, D} closure of C = {A, B, C, D} This relation is in BCNF as it is already in 3Nf (there is no prime attribute deriving no prime attribute) and on the left hand side of the functional dependency there is a candidate key. Difference between 3NF and BCNF : DBMS Difference Between GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Introduction of DBMS (Database Management System) | Set 1 Difference between Clustered and Non-clustered index Introduction of B-Tree SQL Trigger | Student Database Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jan, 2021" }, { "code": null, "e": 359, "s": 54, "text": "1. Third Normal Form (3NF) :A relation is said to be in Third Normal Form (3NF), if it is in 2NF and when no non key attribute is transitively dependent on the primary key i.e., there is no transitive dependency. Also it should satisfy one of the below given conditions. For the function dependency C->D:" }, { "code": null, "e": 388, "s": 359, "text": "C should be a super key and," }, { "code": null, "e": 464, "s": 388, "text": "D should be a prime attribute i.e, D should be a part of the candidate key." }, { "code": null, "e": 533, "s": 464, "text": "3NF is used to reduce data duplication and to attain data integrity." }, { "code": null, "e": 629, "s": 533, "text": "Example:For the relation R(L, M, N, O, P) with functional dependencies as {L->M, MN->P, PO->L}:" }, { "code": null, "e": 813, "s": 629, "text": "The candidate keys will be : {LNO, MNO, NOP}\n as the closure of LNO = {L, M, N, O, P} \n closure of MNO = {L, M, N, O, P}\n closure of NOP = {L, M, N, O, P}" }, { "code": null, "e": 972, "s": 813, "text": "This relation is in 3NF as it is already in 2NF and has no transitive dependency. Also there is no non prime attribute that is deriving a non prime attribute." }, { "code": null, "e": 1164, "s": 972, "text": "2. Boyce-Codd Normal Form (BCNF) :BCNF stands for Boyce-Codd normal form and was made by R.F Boyce and E.F Codd in 1974.A functional dependency is said to be in BCNF if these properties hold:" }, { "code": null, "e": 1193, "s": 1164, "text": "It should already be in 3NF." }, { "code": null, "e": 1256, "s": 1193, "text": "For a functional dependency say P->Q, P should be a super key." }, { "code": null, "e": 1379, "s": 1256, "text": "BCNF is an extension of 3NF and it is has more strict rules than 3NF. Also, it is considered to be more stronger than 3NF." }, { "code": null, "e": 1476, "s": 1379, "text": "Example:for the relation R(A, B, C, D) with functional dependencies as {A->B, A->C, C->D, C->A}:" }, { "code": null, "e": 1596, "s": 1476, "text": "The candidate keys will be : {A, C}\n as the closure of A = {A, B, C, D} \n closure of C = {A, B, C, D} " }, { "code": null, "e": 1784, "s": 1596, "text": "This relation is in BCNF as it is already in 3Nf (there is no prime attribute deriving no prime attribute) and on the left hand side of the functional dependency there is a candidate key." }, { "code": null, "e": 1818, "s": 1784, "text": "Difference between 3NF and BCNF :" }, { "code": null, "e": 1823, "s": 1818, "text": "DBMS" }, { "code": null, "e": 1842, "s": 1823, "text": "Difference Between" }, { "code": null, "e": 1850, "s": 1842, "text": "GATE CS" }, { "code": null, "e": 1855, "s": 1850, "text": "DBMS" }, { "code": null, "e": 1953, "s": 1855, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1964, "s": 1953, "text": "CTE in SQL" }, { "code": null, "e": 2022, "s": 1964, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 2075, "s": 2022, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 2098, "s": 2075, "text": "Introduction of B-Tree" }, { "code": null, "e": 2129, "s": 2098, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 2169, "s": 2129, "text": "Class method vs Static method in Python" }, { "code": null, "e": 2200, "s": 2169, "text": "Difference between BFS and DFS" }, { "code": null, "e": 2261, "s": 2200, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2329, "s": 2261, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
How to Create Your First Linear Programming Solver in Python | by Gustavo Santos | Towards Data Science
Linear Programming (LP) is a method to get to an optimal solution of a problem by solving a linear equation. Ok, still a puzzle to you? Then let me try to simplify even more. Linear Programming will look to a problem and transform it in a mathematical equation using variables like x and y. After that, it is a matter of trying numbers for those variables until you reach the best solution, what can be the maximum or minimum possible value. If I give you the equation x + y = 10 and ask for the maximum value of x, that is a good example of LP. It is called Linear because those xy-like mathematical expressions can be represented as a line in space, meaning that if I solve the equation by finding the values of x and y and plot the resulting combination on a 2-dimensional graphic, the result will be a line. In this section, my intention is to apply the Linear Programming to a very simple problem, what will give us a full understanding of how to translate our problem into an equation, how the linear solvers work and how to program them. First things first. Before the coding, let’s go over a few concepts. Objective Function: that is the goal, the problem you are actually trying to solve (e.g. maximize profit, minimize loss, optimize space allocation). Constraints: the can’s and cant’s. What can or cannot not happen while you’re solving the problem (e.g. value can’t be negative, max space available in a container). Variables: the variable parts of your problem (e.g. products, prices, profit, size). There are a couple of LP solvers packages available in Python. Among them are SciPy, PuLP, CVXOPT. In this tutorial, we’re working with PuLP. Install it using pip: pip install pulp # for Jupyter Notebooks!pip install pulp Imagine we have a square field of 100 meters by 100 meters where we must draw the longest 45 degrees diagonal line starting at point 0 up to the upper right corner. However, let’s imagine that there is a fence 5 meters away from the upper margin and another fence 5 meters away from the right margin. I want to know what is my maximum value of X and Y (my coordinates to draw the longest line) if I have to stop at the fence. Like I said, this is a very simple problem. You probably figured it out by yourself that the answer is x=95 and y=95, right? And that is also part of my method here. Now that you already know the answer, let’s work on the logic we can build to make the computer get to the result. Like previously mentioned, the objective function is our goal, what we want to accomplish, what we’re trying to solve. The objective function is what we are trying to solve. In our example here, we want to draw a diagonal line. Do you agree with me that, in order to draw a diagonal on a 2D graphic, all we have to do is to assign the same value to X and Y? Also, we want to add values up to a maximum. Thus, our objective function becomes x + y. We have only two simple constraints in this problem: the line can’t go after the fence and the values can’t be negative. Constraints are the rules that the objective function must follow. Now to put that constraint in a mathematical form, we must use x and y again. Let’s think logically. If the field is 100 x 100 and we have a fence 5 meters from top and 5 meters from right, we should say that x can’t be higher than 100–5 (a.k.a 95). The same applies to y, as this would mean that the line went over the fence. 0 ≤ x ≤ 950≤ y ≤ 95 0 ≤ x ≤ 95 0≤ y ≤ 95 The next step is using PuLP to create our solver and find the maximum coordinates values for the end of the diagonal line. Import the modules to your Python session: from pulp import LpMaximize, LpProblem, LpStatus, LpVariable Create an instance of the solver and the variables. Notice that the lowBoundparameter here will act as a constraint to prevent negative values. The upBound parameter is not that important, given that it will be overwritten by the fence constraint, but still nice to know it’s there. # Create the maximization problemmodel = LpProblem(name='Field Problem', sense=LpMaximize)# Initialize the variablesx = LpVariable(name="x", lowBound=0, upBound=100)y = LpVariable(name="y", lowBound=0, upBound=100) Next step is to add the constraints to the model. The first element is a LpConstraint instance. The second element is a name you want to give for that constraint. We could create the x≥0 and y≥0, but that is already taken care, as explained before. # Add the constraints to the model. Use += to append expressions to the modelmodel += (x <= 95, "margin_X") #it cannot go past the fencemodel += (y <= 95, "margin_Y") Now we add the objective function to the model. # Objective Functionobj_func = x + y# Add Objective function to the modelmodel += obj_func If you’d like to see the model just created prior to solve it, just call your model name. There you will see how it reads the problem logically as a math problem. Maximize function x+y subject to x and Y being less than 95. modelField_Problem: MAXIMIZE 1*x + 1*y + 0 SUBJECT TO margin_X: x <= 95 margin_Y: y <= 95 VARIABLES x <= 100 Continuous y <= 100 Continuous Solve. status = model.solve() Print a report. print(f"status: {model.status}, {LpStatus[model.status]}")print(f"objective: {model.objective.value()}")for var in model.variables(): print(f"{var.name}: {var.value()}")for name, constraint in model.constraints.items(): print(f"{name}: {constraint.value()}")[OUT]:status: 1, Optimal objective: 190.0 x: 95.0 y: 95.0 margin_X: 0.0 margin_Y: 0.0 As expected, the maximum value for x and y is 95. # The field solution plot# Create a plot spaceplt.figure(figsize=(8,8))# Dimensions of the field.xlimits=[0,100,0,100]ylimits=[0,0,100,100]# Plot fieldplt.scatter(xlimits,ylimits)# Plot line SOLUTIONplt.plot([0,x.value()], [0,y.value()], c='red')# Plot MAX POINTplt.scatter(x.value(),y.value(), c='red')# Plot Fence 1plt.vlines(95, 0,100, linestyles='--', colors='red')# Plot Fence 2plt.hlines(95, 0,100, linestyles='--', colors='red')# Annotationsplt.annotate(f'Optimal Value: {x.value(), y.value()} --->', xy=(47, 96)); The intention of this post was to give you a gentle and user-friendly introduction to Linear Programming in Python. The example is extremely simple, but the idea is to build from here, understanding the basic concept to be able to apply that on more complex problems. Here is a good tutorial from Real Python, if you’d like to go deeper. realpython.com If this content is useful to you, follow my blog.
[ { "code": null, "e": 281, "s": 172, "text": "Linear Programming (LP) is a method to get to an optimal solution of a problem by solving a linear equation." }, { "code": null, "e": 347, "s": 281, "text": "Ok, still a puzzle to you? Then let me try to simplify even more." }, { "code": null, "e": 614, "s": 347, "text": "Linear Programming will look to a problem and transform it in a mathematical equation using variables like x and y. After that, it is a matter of trying numbers for those variables until you reach the best solution, what can be the maximum or minimum possible value." }, { "code": null, "e": 718, "s": 614, "text": "If I give you the equation x + y = 10 and ask for the maximum value of x, that is a good example of LP." }, { "code": null, "e": 984, "s": 718, "text": "It is called Linear because those xy-like mathematical expressions can be represented as a line in space, meaning that if I solve the equation by finding the values of x and y and plot the resulting combination on a 2-dimensional graphic, the result will be a line." }, { "code": null, "e": 1217, "s": 984, "text": "In this section, my intention is to apply the Linear Programming to a very simple problem, what will give us a full understanding of how to translate our problem into an equation, how the linear solvers work and how to program them." }, { "code": null, "e": 1286, "s": 1217, "text": "First things first. Before the coding, let’s go over a few concepts." }, { "code": null, "e": 1435, "s": 1286, "text": "Objective Function: that is the goal, the problem you are actually trying to solve (e.g. maximize profit, minimize loss, optimize space allocation)." }, { "code": null, "e": 1601, "s": 1435, "text": "Constraints: the can’s and cant’s. What can or cannot not happen while you’re solving the problem (e.g. value can’t be negative, max space available in a container)." }, { "code": null, "e": 1686, "s": 1601, "text": "Variables: the variable parts of your problem (e.g. products, prices, profit, size)." }, { "code": null, "e": 1828, "s": 1686, "text": "There are a couple of LP solvers packages available in Python. Among them are SciPy, PuLP, CVXOPT. In this tutorial, we’re working with PuLP." }, { "code": null, "e": 1850, "s": 1828, "text": "Install it using pip:" }, { "code": null, "e": 1908, "s": 1850, "text": "pip install pulp # for Jupyter Notebooks!pip install pulp" }, { "code": null, "e": 2334, "s": 1908, "text": "Imagine we have a square field of 100 meters by 100 meters where we must draw the longest 45 degrees diagonal line starting at point 0 up to the upper right corner. However, let’s imagine that there is a fence 5 meters away from the upper margin and another fence 5 meters away from the right margin. I want to know what is my maximum value of X and Y (my coordinates to draw the longest line) if I have to stop at the fence." }, { "code": null, "e": 2615, "s": 2334, "text": "Like I said, this is a very simple problem. You probably figured it out by yourself that the answer is x=95 and y=95, right? And that is also part of my method here. Now that you already know the answer, let’s work on the logic we can build to make the computer get to the result." }, { "code": null, "e": 2734, "s": 2615, "text": "Like previously mentioned, the objective function is our goal, what we want to accomplish, what we’re trying to solve." }, { "code": null, "e": 2789, "s": 2734, "text": "The objective function is what we are trying to solve." }, { "code": null, "e": 2973, "s": 2789, "text": "In our example here, we want to draw a diagonal line. Do you agree with me that, in order to draw a diagonal on a 2D graphic, all we have to do is to assign the same value to X and Y?" }, { "code": null, "e": 3062, "s": 2973, "text": "Also, we want to add values up to a maximum. Thus, our objective function becomes x + y." }, { "code": null, "e": 3183, "s": 3062, "text": "We have only two simple constraints in this problem: the line can’t go after the fence and the values can’t be negative." }, { "code": null, "e": 3250, "s": 3183, "text": "Constraints are the rules that the objective function must follow." }, { "code": null, "e": 3577, "s": 3250, "text": "Now to put that constraint in a mathematical form, we must use x and y again. Let’s think logically. If the field is 100 x 100 and we have a fence 5 meters from top and 5 meters from right, we should say that x can’t be higher than 100–5 (a.k.a 95). The same applies to y, as this would mean that the line went over the fence." }, { "code": null, "e": 3597, "s": 3577, "text": "0 ≤ x ≤ 950≤ y ≤ 95" }, { "code": null, "e": 3608, "s": 3597, "text": "0 ≤ x ≤ 95" }, { "code": null, "e": 3618, "s": 3608, "text": "0≤ y ≤ 95" }, { "code": null, "e": 3741, "s": 3618, "text": "The next step is using PuLP to create our solver and find the maximum coordinates values for the end of the diagonal line." }, { "code": null, "e": 3784, "s": 3741, "text": "Import the modules to your Python session:" }, { "code": null, "e": 3845, "s": 3784, "text": "from pulp import LpMaximize, LpProblem, LpStatus, LpVariable" }, { "code": null, "e": 4128, "s": 3845, "text": "Create an instance of the solver and the variables. Notice that the lowBoundparameter here will act as a constraint to prevent negative values. The upBound parameter is not that important, given that it will be overwritten by the fence constraint, but still nice to know it’s there." }, { "code": null, "e": 4343, "s": 4128, "text": "# Create the maximization problemmodel = LpProblem(name='Field Problem', sense=LpMaximize)# Initialize the variablesx = LpVariable(name=\"x\", lowBound=0, upBound=100)y = LpVariable(name=\"y\", lowBound=0, upBound=100)" }, { "code": null, "e": 4592, "s": 4343, "text": "Next step is to add the constraints to the model. The first element is a LpConstraint instance. The second element is a name you want to give for that constraint. We could create the x≥0 and y≥0, but that is already taken care, as explained before." }, { "code": null, "e": 4759, "s": 4592, "text": "# Add the constraints to the model. Use += to append expressions to the modelmodel += (x <= 95, \"margin_X\") #it cannot go past the fencemodel += (y <= 95, \"margin_Y\")" }, { "code": null, "e": 4807, "s": 4759, "text": "Now we add the objective function to the model." }, { "code": null, "e": 4898, "s": 4807, "text": "# Objective Functionobj_func = x + y# Add Objective function to the modelmodel += obj_func" }, { "code": null, "e": 5122, "s": 4898, "text": "If you’d like to see the model just created prior to solve it, just call your model name. There you will see how it reads the problem logically as a math problem. Maximize function x+y subject to x and Y being less than 95." }, { "code": null, "e": 5264, "s": 5122, "text": "modelField_Problem: MAXIMIZE 1*x + 1*y + 0 SUBJECT TO margin_X: x <= 95 margin_Y: y <= 95 VARIABLES x <= 100 Continuous y <= 100 Continuous" }, { "code": null, "e": 5271, "s": 5264, "text": "Solve." }, { "code": null, "e": 5294, "s": 5271, "text": "status = model.solve()" }, { "code": null, "e": 5310, "s": 5294, "text": "Print a report." }, { "code": null, "e": 5660, "s": 5310, "text": "print(f\"status: {model.status}, {LpStatus[model.status]}\")print(f\"objective: {model.objective.value()}\")for var in model.variables(): print(f\"{var.name}: {var.value()}\")for name, constraint in model.constraints.items(): print(f\"{name}: {constraint.value()}\")[OUT]:status: 1, Optimal objective: 190.0 x: 95.0 y: 95.0 margin_X: 0.0 margin_Y: 0.0" }, { "code": null, "e": 5710, "s": 5660, "text": "As expected, the maximum value for x and y is 95." }, { "code": null, "e": 6232, "s": 5710, "text": "# The field solution plot# Create a plot spaceplt.figure(figsize=(8,8))# Dimensions of the field.xlimits=[0,100,0,100]ylimits=[0,0,100,100]# Plot fieldplt.scatter(xlimits,ylimits)# Plot line SOLUTIONplt.plot([0,x.value()], [0,y.value()], c='red')# Plot MAX POINTplt.scatter(x.value(),y.value(), c='red')# Plot Fence 1plt.vlines(95, 0,100, linestyles='--', colors='red')# Plot Fence 2plt.hlines(95, 0,100, linestyles='--', colors='red')# Annotationsplt.annotate(f'Optimal Value: {x.value(), y.value()} --->', xy=(47, 96));" }, { "code": null, "e": 6500, "s": 6232, "text": "The intention of this post was to give you a gentle and user-friendly introduction to Linear Programming in Python. The example is extremely simple, but the idea is to build from here, understanding the basic concept to be able to apply that on more complex problems." }, { "code": null, "e": 6570, "s": 6500, "text": "Here is a good tutorial from Real Python, if you’d like to go deeper." }, { "code": null, "e": 6585, "s": 6570, "text": "realpython.com" } ]
Sending data from a Raspberry Pi Sensor unit over Serial-Bluetooth | by Daniel Ellis | Towards Data Science
When building portable sensors we often want to calibrate and double-check their readings before allowing them to log data remotely. Whilst developing these we can easily SSH into them and write any results to screen. However what happens when we are in a very remote part of the world, with no laptop, wifi or signal? Within this tutorial, we look at exploiting the Bluetooth capabilities of a Raspberry Pi Zero (without WiFi) to transmit the initial set of results to a handheld device of our choosing. In our case, it will be through the use of a mobile phone or android tablet, such that we can compare the sensor and GPS readings. Before we start there are a couple of changes required for the Bluetooth to work. These are outlined below. We begin by changing the configuration of the installed Bluetooth library: sudo nano /etc/systemd/system/dbus-org.bluez.service Here we locate the line starting ExecStart , and replace it with the following: ExecStart=/usr/lib/bluetooth/bluetoothd --compat --noplugin=sapExecStartPost=/usr/bin/sdptool add SP Having added the ‘compatibility’ flag, we now have to restart the Bluetooth service on the Pi: sudo systemctl daemon-reload;sudo systemctl restart bluetooth.service; To prevent issues with pairing Bluetooth devices whilst out in the field, it is always a good idea to pre-pair devices — saving their configuration. To do this we use bluetoothctl following the process described in the link below: medium.com Locate our host MAC address Locate our host MAC address hcitool scan This gives results in the format: Scanning ...XX:XX:XX:XX:XX:XX device1XX:XX:XX:XX:XX:XX device2 2. select the device we want and copy its address. 3. execute the following: sudo bluetoothctl 4. In the Bluetooth console run the following 3 commands (substituting your copied address): discoverable on# thenpair XX:XX:XX:XX:XX:XX# and trust XX:XX:XX:XX:XX:XX# where XX corresponds to the address copied from above When pairing you may be asked to confirm a pin on both devices. trust saves the device address to the trusted list. To make a PI discoverable on boot, you can have a look at the code here: medium.com Finally, we wish to tell the device to watch for incoming Bluetooth connections when it boots. To do this we can add the following file to /etc/rc.local (before the exit command). sudo rfcomm watch hci0 & Take care to include the ampersand at the end, as otherwise, it will stall the device bootup process. Also if you are reading another device over serial, e.g. a GPS receiver, you may want to use rfcomm1 instead of hci0 (rfcomm0). Depending on what device you are using, the method to read from a serial monitor varies. On an android device, you may take the node/javascript approach (this should work on all operating systems!). For the purpose of this demo, I will describe a method using python to check things are working on a MacBook Pro. If you have a terminal, the simplest way to do this is to type ls /dev/tty. and hit the tab (autocomplete) button. Presuming you have not changed this, this should be your device hostname followed by SerialPort. The default serial port path for a freshly installed raspberry pi should be /dev/tty.raspberrypi-SerialPort To read any data received, we can use the python serial library coupled with the following code snippet. import serialser = serial.Serial('/dev/tty.raspberrypi-SerialPort', timeout=1, baudrate=115000)serial.flushInput();serial.flushOutput() while True: out = serial.readline().decode() if out!='' : print (out) Note that this is an infinite loop that keeps printing anything it receives. To cancel it when the message ‘exit’ is received we can use: if out == 'exit': break When testing the simplest way to send data is to echo it to /dev/rgcomm0 from the raspberry pi shell. This allows us to manually test communication over the port before writing anything more complicated. echo "hello!" > /dev/rfcomm0 If reading data from the raspberry pi and pre-processing it, chances are we will be using python to do the heavy lifting. From here we can treat the rfcomm0 channel as a file and write to it as follows: with open(‘/dev/rfcomm0’,’w’,1) as f: f.write(‘hello from python!’) If we want to quickly check that our sensors are behaving whilst out in the field, we can make use of the Bluetooth capabilities of the Raspberry Pi. This is done by creating a Bluetooth serial port and sending data over it. Such methods are particularly useful if we do not wish to carry bulky laptops, or where a WiFi network is occupied or unavailable. More complex tasks such as sending commands to the Raspberry Pi, or even SSHing into it over Bluetooth are also possible but are beyond the scope of this tutorial.
[ { "code": null, "e": 490, "s": 171, "text": "When building portable sensors we often want to calibrate and double-check their readings before allowing them to log data remotely. Whilst developing these we can easily SSH into them and write any results to screen. However what happens when we are in a very remote part of the world, with no laptop, wifi or signal?" }, { "code": null, "e": 807, "s": 490, "text": "Within this tutorial, we look at exploiting the Bluetooth capabilities of a Raspberry Pi Zero (without WiFi) to transmit the initial set of results to a handheld device of our choosing. In our case, it will be through the use of a mobile phone or android tablet, such that we can compare the sensor and GPS readings." }, { "code": null, "e": 915, "s": 807, "text": "Before we start there are a couple of changes required for the Bluetooth to work. These are outlined below." }, { "code": null, "e": 990, "s": 915, "text": "We begin by changing the configuration of the installed Bluetooth library:" }, { "code": null, "e": 1043, "s": 990, "text": "sudo nano /etc/systemd/system/dbus-org.bluez.service" }, { "code": null, "e": 1123, "s": 1043, "text": "Here we locate the line starting ExecStart , and replace it with the following:" }, { "code": null, "e": 1224, "s": 1123, "text": "ExecStart=/usr/lib/bluetooth/bluetoothd --compat --noplugin=sapExecStartPost=/usr/bin/sdptool add SP" }, { "code": null, "e": 1319, "s": 1224, "text": "Having added the ‘compatibility’ flag, we now have to restart the Bluetooth service on the Pi:" }, { "code": null, "e": 1390, "s": 1319, "text": "sudo systemctl daemon-reload;sudo systemctl restart bluetooth.service;" }, { "code": null, "e": 1539, "s": 1390, "text": "To prevent issues with pairing Bluetooth devices whilst out in the field, it is always a good idea to pre-pair devices — saving their configuration." }, { "code": null, "e": 1621, "s": 1539, "text": "To do this we use bluetoothctl following the process described in the link below:" }, { "code": null, "e": 1632, "s": 1621, "text": "medium.com" }, { "code": null, "e": 1660, "s": 1632, "text": "Locate our host MAC address" }, { "code": null, "e": 1688, "s": 1660, "text": "Locate our host MAC address" }, { "code": null, "e": 1701, "s": 1688, "text": "hcitool scan" }, { "code": null, "e": 1735, "s": 1701, "text": "This gives results in the format:" }, { "code": null, "e": 1798, "s": 1735, "text": "Scanning ...XX:XX:XX:XX:XX:XX device1XX:XX:XX:XX:XX:XX device2" }, { "code": null, "e": 1849, "s": 1798, "text": "2. select the device we want and copy its address." }, { "code": null, "e": 1875, "s": 1849, "text": "3. execute the following:" }, { "code": null, "e": 1893, "s": 1875, "text": "sudo bluetoothctl" }, { "code": null, "e": 1986, "s": 1893, "text": "4. In the Bluetooth console run the following 3 commands (substituting your copied address):" }, { "code": null, "e": 2114, "s": 1986, "text": "discoverable on# thenpair XX:XX:XX:XX:XX:XX# and trust XX:XX:XX:XX:XX:XX# where XX corresponds to the address copied from above" }, { "code": null, "e": 2230, "s": 2114, "text": "When pairing you may be asked to confirm a pin on both devices. trust saves the device address to the trusted list." }, { "code": null, "e": 2303, "s": 2230, "text": "To make a PI discoverable on boot, you can have a look at the code here:" }, { "code": null, "e": 2314, "s": 2303, "text": "medium.com" }, { "code": null, "e": 2494, "s": 2314, "text": "Finally, we wish to tell the device to watch for incoming Bluetooth connections when it boots. To do this we can add the following file to /etc/rc.local (before the exit command)." }, { "code": null, "e": 2519, "s": 2494, "text": "sudo rfcomm watch hci0 &" }, { "code": null, "e": 2749, "s": 2519, "text": "Take care to include the ampersand at the end, as otherwise, it will stall the device bootup process. Also if you are reading another device over serial, e.g. a GPS receiver, you may want to use rfcomm1 instead of hci0 (rfcomm0)." }, { "code": null, "e": 3062, "s": 2749, "text": "Depending on what device you are using, the method to read from a serial monitor varies. On an android device, you may take the node/javascript approach (this should work on all operating systems!). For the purpose of this demo, I will describe a method using python to check things are working on a MacBook Pro." }, { "code": null, "e": 3125, "s": 3062, "text": "If you have a terminal, the simplest way to do this is to type" }, { "code": null, "e": 3138, "s": 3125, "text": "ls /dev/tty." }, { "code": null, "e": 3177, "s": 3138, "text": "and hit the tab (autocomplete) button." }, { "code": null, "e": 3350, "s": 3177, "text": "Presuming you have not changed this, this should be your device hostname followed by SerialPort. The default serial port path for a freshly installed raspberry pi should be" }, { "code": null, "e": 3382, "s": 3350, "text": "/dev/tty.raspberrypi-SerialPort" }, { "code": null, "e": 3487, "s": 3382, "text": "To read any data received, we can use the python serial library coupled with the following code snippet." }, { "code": null, "e": 3701, "s": 3487, "text": "import serialser = serial.Serial('/dev/tty.raspberrypi-SerialPort', timeout=1, baudrate=115000)serial.flushInput();serial.flushOutput() while True: out = serial.readline().decode() if out!='' : print (out)" }, { "code": null, "e": 3839, "s": 3701, "text": "Note that this is an infinite loop that keeps printing anything it receives. To cancel it when the message ‘exit’ is received we can use:" }, { "code": null, "e": 3863, "s": 3839, "text": "if out == 'exit': break" }, { "code": null, "e": 4067, "s": 3863, "text": "When testing the simplest way to send data is to echo it to /dev/rgcomm0 from the raspberry pi shell. This allows us to manually test communication over the port before writing anything more complicated." }, { "code": null, "e": 4096, "s": 4067, "text": "echo \"hello!\" > /dev/rfcomm0" }, { "code": null, "e": 4299, "s": 4096, "text": "If reading data from the raspberry pi and pre-processing it, chances are we will be using python to do the heavy lifting. From here we can treat the rfcomm0 channel as a file and write to it as follows:" }, { "code": null, "e": 4371, "s": 4299, "text": "with open(‘/dev/rfcomm0’,’w’,1) as f: f.write(‘hello from python!’)" }, { "code": null, "e": 4727, "s": 4371, "text": "If we want to quickly check that our sensors are behaving whilst out in the field, we can make use of the Bluetooth capabilities of the Raspberry Pi. This is done by creating a Bluetooth serial port and sending data over it. Such methods are particularly useful if we do not wish to carry bulky laptops, or where a WiFi network is occupied or unavailable." } ]
Capgemini Tech Challenge 2019 | Round2 & Round 3 Question - GeeksforGeeks
11 Jan, 2021 Round 2: MISSION WITH MI6: Last year a hacking took place in the safest and crucial defense network of the US. Hackers downloaded crucial defense-related confidential files and documents from their network and after that, they flew to Dubai for delivery of the documents to some terror-related outfits. Investigation Agent MI6 found that there is a meeting scheduled between parties in the hotel room of Burj Khalifa. MI6 agency formed a team and send their best agents for recovering documents and catching hackers. After reaching Dubai, agents check-in to a hotel and found a way to go to the room by hacking surveillance cameras but there is very high security on the floor where the meeting is supposed to be held. So they decided to take another route by walking on the wall of the hotel building with the help of electromagnetic repulsive force. They have a gadget having this type of technology that helps them in walking on the wall of the hotel. There are various metal square-shaped sheets attached to the outside wall of the hotel. A specialist agent Bob decided to walk on the wall and his colleague guide him and instruct him that on which square sheet he had to walk. Bob’s colleague sends him a set of instructions which helps in determining which particular sheet he has to stand. A set of instructions is a string that consists of letters ‘L’, ‘R’, ‘U’, ‘D’ . For simplicity let’s assume that Bob is staying at point (0, 0) on a big wall. He consistently fulfills all the instructions sent by his colleague. Let’s assume that now he is staying at point (X, Y), then depending on what is the current instruction he moves in one direction: ‘L’: from (X,Y) moves to point (X,Y-1) ‘R’: from (X,Y) moves to point (X,Y+1) ‘U’: from (X,Y) moves to point (X-1,Y) 'D' : from (X,Y) moves to point (X+1,Y) Initially, all the points are good ones and there is no crack on any point or sheet. But if Bob already visited some point at any time then next time this point cracked. Every time Bob makes a step on the cracked points he slips on the wall. You are given a string S which tells the set of instructions for Bob. Your work is to calculate how many times Bob slips from his position. Input Format: Input 1: It will be a string that tells the string S which denotes the set of instructions for Bob. Constraints 1 ≤ S ≤ 105 Output Format: It will be an integer which tells that how many times Bob slips from his position Sample TestCase 1 Input RRULDL Output 2 Here is my solution: C++ #include<bits/stdc++.h>using namespace std;int main(){ /*input the string*/ string str; cin>>str; /* best data structure for this problem is unordered map , by using this data structure we can detect every repeating steps*/ unordered_map<string,int> mp; int res=0; int x=0,y=0; string ss; mp["0,0"]=1; /*traverse the whole string */ for(int i=0;i<str.size();i++) { if(str[i]=='L') { y--; ss=to_string(x)+","+to_string(y); if(mp[ss]) res++; else mp[ss]=1; } else if(str[i]=='R') { y++; ss=to_string(x)+","+to_string(y); if(mp[ss]) res++; else mp[ss]=1; } else if(str[i]=='D') { x++; ss=to_string(x)+","+to_string(y); if(mp[ss]) res++; else mp[ss]=1; } else if(str[i]=='U') { x--; ss = to_string(x) + "," + to_string(y); if (mp[ss]) res++; else mp[ss] = 1; } } cout<<res; return 0; } Bob route consists of the following points: 0,0 ---> 0,1 ---> 0,2 ----> -1,2 ---> -1,1 ----> 0,1(cracks) ----> 0,0 (cracks) So, there will be 2 points where Bob visited again, and so he slips 2 steps. Round 3: Craziest Prisons and Jails: Some prisons are known for being violent and treating prisoners like animals, leading to inhumane and unethical tactics for keeping the peace. There is a prison located in Norway, Halden is often described as peaceful and relaxing. The prisoners are treated to good food, hot coffee, and cells that boast televisions, mini-fridges, private bathrooms, and scenic views of the surrounding forest. Norway’s government build 3 new prisons each one is having its own unique design different from the other. Each prison consists of cells arranged into a one, two, or three-dimensional grid. Jailer can fill N prisoners into the cells. The Distance between two cells is the smallest number of moves that a prisoner would need in order to reach one cell from the other. In one move, the prisoner may step into one of the adjacent cells. Two prisoners can hear each other if the distance between their cells is at most D. Your task is to calculate how many pairs of prisoners there are such that one prisoner can hear the other prisoner. Example: Suppose the prison will of 3-dimensional type then it will look like below Input Format: Input 1: It will be the integer which tells the type of prison P Input 1: It will be the integer which tells the type of prison P Input 2: It will be the integer which tells the number of prisoners N Input 2: It will be the integer which tells the number of prisoners N Input 3: It will be the integer which tells the largest distance D at which two prisoners can hear each other Input 3: It will be the integer which tells the largest distance D at which two prisoners can hear each other Input 4: It will be the integer which tells the size of the prison S; (the largest coordinate allowed to appear in the input):When P=1, S will be at most 75000000.When P=2, S will be at most 75000.When P=3, S will be at most 75. Input 4: It will be the integer which tells the size of the prison S; (the largest coordinate allowed to appear in the input): When P=1, S will be at most 75000000. When P=2, S will be at most 75000. When P=3, S will be at most 75. Input 5: It will be a string array which tells the coordinates of each prisoner. Array format will be like:First-line will tell the total number of rows i.e. total number of prisoners N Input 5: It will be a string array which tells the coordinates of each prisoner. Array format will be like: First-line will tell the total number of rows i.e. total number of prisoners N Each of the following N lines contains P integers separated by single commas – the coordinates of one prisoner. Each coordinate will be between 1 and S (inclusive). More than one prisoner may occupy the same cell. If the P is one, then there will be no comma – only single value will be there in each line. Constraints 1 ≤ P ≤ 3 1 ≤ N ≤ 100000 1 ≤ D ≤ 100000000 Output Format: It will be the single integer, the number of pairs of prisoners that can hear each other. Sample TestCase 1: Input 3 8 10 20 8 10,10,10 10,10,20 10,20,10 10,20,20 20,10,10 20,10,20 20,20,10 20,20,20 Output 12 Solution in C++: C++ #include<bits/stdc++.h>#define ll long intusing namespace std; //calculate distance in 2D for two grid/* For 2D jail */int TwoD(ll x1,ll y1, ll x2, ll y2,ll distance ) { ll d=0; if(x1==x2){ d=abs(y1-y2); } else if(y1==y2){ d=abs(x1-x2); } else{ return 0; } if(d<=distance){ return 1; } else{ return 0; } } //calculate distance in 3D for two grid /* For 3D jail*/int ThreeD(ll x1, ll y1,ll z1, ll x2,ll y2,ll z2,ll distance) { ll d=0; if(x1==x2&&y1==y2){ d=abs(z1-z2); } else if(y1==y2&&z1==z2){ d=abs(x1-x2); } else if(z1==z2&&x1==x2){ d=abs(y1-y2); } else{ return 0; } if(d<=distance){ return 1; } else{ return 0; } } //driver programint main(){ ll p,n,d,s; ll res=0; cin>>p; cin>>n; cin>>d; cin>>s; cin>>n; ll distance=d ; int inp[n],inp1[n],inp2[n]; ll x1,x2,y1,y2,z1,z2; if(p==1) { for(int i=0;i<n;i++) { cin>>inp[i]; } } else if(p==2) { for (int i = 0; i < n; i++) { scanf("%d,%d", &inp[i], &inp1[i]); } } else { for (int i = 0; i < n; i++) { scanf("%d,%d,%d", &inp[i], &inp1[i], &inp2[i]); } } if(p==1) { sort(inp,inp+n); for(int i=0;i<n-1;i++) { for (int j = i+1; j <n ; j++) { if(inp[i] && inp[j] && inp[i]<=s && inp[j]<=s) { if (abs(inp[i] - inp[j]) <= distance) { res++; } else { break; } } } } } else if(p==2) { for (int i = 0; i < n-1; i++) { for(int j=i+1;j<n;j++) { x1 = inp[i]; y1 = inp1[i]; x2 = inp[j]; y2 = inp1[j]; if(x1 && y1 && x2 && y2 && x1<=s && y1<=s && x2<=s && y2<=s ) if(TwoD(x1,y1,x2,y2,distance)) { res++; } } } } else { res=0; for (int i = 0; i < n-1; i++) { for(int j=i+1;j<n;j++) { x1 = inp[i]; y1 = inp1[i]; z1 = inp2[i]; x2 = inp[j]; y2 = inp1[j]; z2 = inp2[j]; if(x1 && y1 && z1 && x2 && y2 && z2 && x1<=s && y1<=s && z1<=s && x2<=s && y2<=s && z2<=s ) if(ThreeD(x1,y1,z1,x2,y2,z2,distance)){ res++; } } } } cout<<res; return 0;} Capgemini Interview Experiences Capgemini Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 (On-Campus) Infosys Interview Experience for DSE - System Engineer | On-Campus 2022 Amazon Interview Experience for SDE-1 Oracle Interview Experience | Set 69 (Application Engineer) Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1 Infosys DSE Interview Experience 2021
[ { "code": null, "e": 24637, "s": 24609, "text": "\n11 Jan, 2021" }, { "code": null, "e": 24646, "s": 24637, "text": "Round 2:" }, { "code": null, "e": 25154, "s": 24646, "text": "MISSION WITH MI6: Last year a hacking took place in the safest and crucial defense network of the US. Hackers downloaded crucial defense-related confidential files and documents from their network and after that, they flew to Dubai for delivery of the documents to some terror-related outfits. Investigation Agent MI6 found that there is a meeting scheduled between parties in the hotel room of Burj Khalifa. MI6 agency formed a team and send their best agents for recovering documents and catching hackers." }, { "code": null, "e": 25592, "s": 25154, "text": "After reaching Dubai, agents check-in to a hotel and found a way to go to the room by hacking surveillance cameras but there is very high security on the floor where the meeting is supposed to be held. So they decided to take another route by walking on the wall of the hotel building with the help of electromagnetic repulsive force. They have a gadget having this type of technology that helps them in walking on the wall of the hotel." }, { "code": null, "e": 26014, "s": 25592, "text": "There are various metal square-shaped sheets attached to the outside wall of the hotel. A specialist agent Bob decided to walk on the wall and his colleague guide him and instruct him that on which square sheet he had to walk. Bob’s colleague sends him a set of instructions which helps in determining which particular sheet he has to stand. A set of instructions is a string that consists of letters ‘L’, ‘R’, ‘U’, ‘D’ ." }, { "code": null, "e": 26292, "s": 26014, "text": "For simplicity let’s assume that Bob is staying at point (0, 0) on a big wall. He consistently fulfills all the instructions sent by his colleague. Let’s assume that now he is staying at point (X, Y), then depending on what is the current instruction he moves in one direction:" }, { "code": null, "e": 26449, "s": 26292, "text": "‘L’: from (X,Y) moves to point (X,Y-1)\n‘R’: from (X,Y) moves to point (X,Y+1)\n‘U’: from (X,Y) moves to point (X-1,Y)\n'D' : from (X,Y) moves to point (X+1,Y)" }, { "code": null, "e": 26691, "s": 26449, "text": "Initially, all the points are good ones and there is no crack on any point or sheet. But if Bob already visited some point at any time then next time this point cracked. Every time Bob makes a step on the cracked points he slips on the wall." }, { "code": null, "e": 26831, "s": 26691, "text": "You are given a string S which tells the set of instructions for Bob. Your work is to calculate how many times Bob slips from his position." }, { "code": null, "e": 26845, "s": 26831, "text": "Input Format:" }, { "code": null, "e": 26945, "s": 26845, "text": "Input 1: It will be a string that tells the string S which denotes the set of instructions for Bob." }, { "code": null, "e": 26969, "s": 26945, "text": "Constraints\n1 ≤ S ≤ 105" }, { "code": null, "e": 27066, "s": 26969, "text": "Output Format: It will be an integer which tells that how many times Bob slips from his position" }, { "code": null, "e": 27084, "s": 27066, "text": "Sample TestCase 1" }, { "code": null, "e": 27127, "s": 27084, "text": "Input\nRRULDL\nOutput\n2\nHere is my solution:" }, { "code": null, "e": 27131, "s": 27127, "text": "C++" }, { "code": "#include<bits/stdc++.h>using namespace std;int main(){ /*input the string*/ string str; cin>>str; /* best data structure for this problem is unordered map , by using this data structure we can detect every repeating steps*/ unordered_map<string,int> mp; int res=0; int x=0,y=0; string ss; mp[\"0,0\"]=1; /*traverse the whole string */ for(int i=0;i<str.size();i++) { if(str[i]=='L') { y--; ss=to_string(x)+\",\"+to_string(y); if(mp[ss]) res++; else mp[ss]=1; } else if(str[i]=='R') { y++; ss=to_string(x)+\",\"+to_string(y); if(mp[ss]) res++; else mp[ss]=1; } else if(str[i]=='D') { x++; ss=to_string(x)+\",\"+to_string(y); if(mp[ss]) res++; else mp[ss]=1; } else if(str[i]=='U') { x--; ss = to_string(x) + \",\" + to_string(y); if (mp[ss]) res++; else mp[ss] = 1; } } cout<<res; return 0; }", "e": 28286, "s": 27131, "text": null }, { "code": null, "e": 28330, "s": 28286, "text": "Bob route consists of the following points:" }, { "code": null, "e": 28410, "s": 28330, "text": "0,0 ---> 0,1 ---> 0,2 ----> -1,2 ---> -1,1 ----> 0,1(cracks) ----> 0,0 (cracks)" }, { "code": null, "e": 28487, "s": 28410, "text": "So, there will be 2 points where Bob visited again, and so he slips 2 steps." }, { "code": null, "e": 28496, "s": 28487, "text": "Round 3:" }, { "code": null, "e": 28919, "s": 28496, "text": "Craziest Prisons and Jails: Some prisons are known for being violent and treating prisoners like animals, leading to inhumane and unethical tactics for keeping the peace. There is a prison located in Norway, Halden is often described as peaceful and relaxing. The prisoners are treated to good food, hot coffee, and cells that boast televisions, mini-fridges, private bathrooms, and scenic views of the surrounding forest." }, { "code": null, "e": 29153, "s": 28919, "text": "Norway’s government build 3 new prisons each one is having its own unique design different from the other. Each prison consists of cells arranged into a one, two, or three-dimensional grid. Jailer can fill N prisoners into the cells." }, { "code": null, "e": 29353, "s": 29153, "text": "The Distance between two cells is the smallest number of moves that a prisoner would need in order to reach one cell from the other. In one move, the prisoner may step into one of the adjacent cells." }, { "code": null, "e": 29553, "s": 29353, "text": "Two prisoners can hear each other if the distance between their cells is at most D. Your task is to calculate how many pairs of prisoners there are such that one prisoner can hear the other prisoner." }, { "code": null, "e": 29637, "s": 29553, "text": "Example: Suppose the prison will of 3-dimensional type then it will look like below" }, { "code": null, "e": 29651, "s": 29637, "text": "Input Format:" }, { "code": null, "e": 29716, "s": 29651, "text": "Input 1: It will be the integer which tells the type of prison P" }, { "code": null, "e": 29781, "s": 29716, "text": "Input 1: It will be the integer which tells the type of prison P" }, { "code": null, "e": 29851, "s": 29781, "text": "Input 2: It will be the integer which tells the number of prisoners N" }, { "code": null, "e": 29921, "s": 29851, "text": "Input 2: It will be the integer which tells the number of prisoners N" }, { "code": null, "e": 30031, "s": 29921, "text": "Input 3: It will be the integer which tells the largest distance D at which two prisoners can hear each other" }, { "code": null, "e": 30141, "s": 30031, "text": "Input 3: It will be the integer which tells the largest distance D at which two prisoners can hear each other" }, { "code": null, "e": 30370, "s": 30141, "text": "Input 4: It will be the integer which tells the size of the prison S; (the largest coordinate allowed to appear in the input):When P=1, S will be at most 75000000.When P=2, S will be at most 75000.When P=3, S will be at most 75." }, { "code": null, "e": 30497, "s": 30370, "text": "Input 4: It will be the integer which tells the size of the prison S; (the largest coordinate allowed to appear in the input):" }, { "code": null, "e": 30535, "s": 30497, "text": "When P=1, S will be at most 75000000." }, { "code": null, "e": 30570, "s": 30535, "text": "When P=2, S will be at most 75000." }, { "code": null, "e": 30602, "s": 30570, "text": "When P=3, S will be at most 75." }, { "code": null, "e": 30788, "s": 30602, "text": "Input 5: It will be a string array which tells the coordinates of each prisoner. Array format will be like:First-line will tell the total number of rows i.e. total number of prisoners N" }, { "code": null, "e": 30896, "s": 30788, "text": "Input 5: It will be a string array which tells the coordinates of each prisoner. Array format will be like:" }, { "code": null, "e": 30975, "s": 30896, "text": "First-line will tell the total number of rows i.e. total number of prisoners N" }, { "code": null, "e": 31282, "s": 30975, "text": "Each of the following N lines contains P integers separated by single commas – the coordinates of one prisoner. Each coordinate will be between 1 and S (inclusive). More than one prisoner may occupy the same cell. If the P is one, then there will be no comma – only single value will be there in each line." }, { "code": null, "e": 31294, "s": 31282, "text": "Constraints" }, { "code": null, "e": 31337, "s": 31294, "text": "1 ≤ P ≤ 3\n1 ≤ N ≤ 100000\n1 ≤ D ≤ 100000000" }, { "code": null, "e": 31442, "s": 31337, "text": "Output Format: It will be the single integer, the number of pairs of prisoners that can hear each other." }, { "code": null, "e": 31461, "s": 31442, "text": "Sample TestCase 1:" }, { "code": null, "e": 31561, "s": 31461, "text": "Input\n3\n8\n10\n20\n8\n10,10,10\n10,10,20\n10,20,10\n10,20,20\n20,10,10\n20,10,20\n20,20,10\n20,20,20\nOutput\n12" }, { "code": null, "e": 31578, "s": 31561, "text": "Solution in C++:" }, { "code": null, "e": 31582, "s": 31578, "text": "C++" }, { "code": "#include<bits/stdc++.h>#define ll long intusing namespace std; //calculate distance in 2D for two grid/* For 2D jail */int TwoD(ll x1,ll y1, ll x2, ll y2,ll distance ) { ll d=0; if(x1==x2){ d=abs(y1-y2); } else if(y1==y2){ d=abs(x1-x2); } else{ return 0; } if(d<=distance){ return 1; } else{ return 0; } } //calculate distance in 3D for two grid /* For 3D jail*/int ThreeD(ll x1, ll y1,ll z1, ll x2,ll y2,ll z2,ll distance) { ll d=0; if(x1==x2&&y1==y2){ d=abs(z1-z2); } else if(y1==y2&&z1==z2){ d=abs(x1-x2); } else if(z1==z2&&x1==x2){ d=abs(y1-y2); } else{ return 0; } if(d<=distance){ return 1; } else{ return 0; } } //driver programint main(){ ll p,n,d,s; ll res=0; cin>>p; cin>>n; cin>>d; cin>>s; cin>>n; ll distance=d ; int inp[n],inp1[n],inp2[n]; ll x1,x2,y1,y2,z1,z2; if(p==1) { for(int i=0;i<n;i++) { cin>>inp[i]; } } else if(p==2) { for (int i = 0; i < n; i++) { scanf(\"%d,%d\", &inp[i], &inp1[i]); } } else { for (int i = 0; i < n; i++) { scanf(\"%d,%d,%d\", &inp[i], &inp1[i], &inp2[i]); } } if(p==1) { sort(inp,inp+n); for(int i=0;i<n-1;i++) { for (int j = i+1; j <n ; j++) { if(inp[i] && inp[j] && inp[i]<=s && inp[j]<=s) { if (abs(inp[i] - inp[j]) <= distance) { res++; } else { break; } } } } } else if(p==2) { for (int i = 0; i < n-1; i++) { for(int j=i+1;j<n;j++) { x1 = inp[i]; y1 = inp1[i]; x2 = inp[j]; y2 = inp1[j]; if(x1 && y1 && x2 && y2 && x1<=s && y1<=s && x2<=s && y2<=s ) if(TwoD(x1,y1,x2,y2,distance)) { res++; } } } } else { res=0; for (int i = 0; i < n-1; i++) { for(int j=i+1;j<n;j++) { x1 = inp[i]; y1 = inp1[i]; z1 = inp2[i]; x2 = inp[j]; y2 = inp1[j]; z2 = inp2[j]; if(x1 && y1 && z1 && x2 && y2 && z2 && x1<=s && y1<=s && z1<=s && x2<=s && y2<=s && z2<=s ) if(ThreeD(x1,y1,z1,x2,y2,z2,distance)){ res++; } } } } cout<<res; return 0;}", "e": 34297, "s": 31582, "text": null }, { "code": null, "e": 34307, "s": 34297, "text": "Capgemini" }, { "code": null, "e": 34329, "s": 34307, "text": "Interview Experiences" }, { "code": null, "e": 34339, "s": 34329, "text": "Capgemini" }, { "code": null, "e": 34437, "s": 34339, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34446, "s": 34437, "text": "Comments" }, { "code": null, "e": 34459, "s": 34446, "text": "Old Comments" }, { "code": null, "e": 34518, "s": 34459, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 34568, "s": 34518, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 34640, "s": 34568, "text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022" }, { "code": null, "e": 34678, "s": 34640, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 34738, "s": 34678, "text": "Oracle Interview Experience | Set 69 (Application Engineer)" }, { "code": null, "e": 34803, "s": 34738, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 34853, "s": 34803, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 34899, "s": 34853, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 34937, "s": 34899, "text": "Amazon Interview Experience for SDE-1" } ]
Full stack PyTorch Crowd Size Estimator | by Charlie Mackie | Towards Data Science
Please try the demo of our crowd size estimator: https://app3-qrhrzckmpq-ue.a.run.app You can choose from some of the images in the ShanghaiTech dataset, or you can upload your own image. If you choose to upload your own image it must be a JPG/JPEG and under 100KB. You can check the image size as follows: Computer: Windows: Explorer → Select Image (bottom of the window). Mac: Control + Click → ‘Get Info’ → ‘Size’ Mobile: iPhone: Ensure the image is not a screenshot, then you can “Choose Size” of the image (bottom of screen). Choose “Small” and upload. Android: Check out this blog post, https://www.quora.com/How-do-I-reduce-the-size-of-photos-in-Android In this article, I will explain how my Western AI project team developed a web application that estimates the size of a crowd in a given image. Our goal from September 2019 was to deploy a machine learning model that could predict the sizes of crowds. We accomplished our goal and we were able to showcase our project at the Canadian Undergraduate Conference on AI (CUCAI) hosted by QMIND — Queen’s AI Hub. Crowd size estimation is a popular topic in the machine learning community. It has various applications including crowd control, customer management, and urban planning. Our model could be applicable in a school setting, measuring class attendance or building occupancy. Pictured above is our deployed web application. The web host takes a local image from the user in a JPG format then estimates the size (number of people) of the crowd. The purpose of this article is to: Showcase our project: Size.AI Give insight into crowd recognition and machine learning as they stand today Provide a tutorial for the deployment of a machine learning model The article will be structured as follows: Brief introduction to machine learning, computer vision, and crowd size estimation Current crowd size estimation approaches Our approach: CSRNet Training, testing, and validation (Google Colab/Python3) Deployment (Flask/Google Cloud) Next steps, sources, and Western AI Artificial intelligence (AI) and machine learning (ML) have different meanings. Machine learning is a type of AI that involves statistical analysis and classification of problems. Popular machine learning applications include Natural Language Processing (NLP) and Computer Vision (CV). These applications are powered by machine learning algorithms which include K Nearest Neighbours (kNN), regression, and neural networks. Let’s focus on neural networks. Neural networks are loosely inspired by the structure of our brain. In the brain there is a network of neurons and each neuron stores bits of information. The neurons are attached to each other by axons which can transfer signals between neurons. In an artificial neural network, the neurons are represented by nodes which are organized into layers. The first layer of nodes can take some form of input and each layer proceeding will help classify the input. The last layer represents an easily interpretable output. Example: The computer wants to determine whether an image contains a dog or a cat. The image will be broken down to its pixels, and each pixel will be represented by an RGB Scale Value (0–255). The RGB values are inputs to the first layer of nodes. Each layer after that can represent some type of feature detection within the image; superposition of the eyes, head size compared to ear size ... etc. The final layer of nodes aggregates all of the information from previous layers and makes a decision. The ‘learning’ part of machine learning, involves iterating through many examples that are tagged with metadata which has already been classified by humans. The neural network undergoes the process of back-propagation where the error of the network is minimized. For each example provided, the network will make its prediction, then validate its prediction with the metadata provided and come up with a cost of error (predicted - actual). The goal of back-propagation is to minimize this error by adjusting the network. The math behind this is more complicated than I just explained. If you are still interested, check out Jayson’s (Project Manager), Simple classifier intro to neural networks. Crowd size estimation uses neural networks to classify people in a crowd then aggregate the amount of people detected. Currently there are three approaches to crowd size estimation: Detection, Regression, and Density. Detection: Focuses on object detection; recognizing features of a human (Ex: head, shoulders, body ... etc). This approach is typically more accurate for smaller crowds of people. Regression: Uses broader features of a person and puts more focus on edge details. This outperforms the detection models when presented with more dense crowds. Density: (See density map example below) Instead of focusing on individual people, density maps are produced that track groups of people. This is the most accurate method for dense crowds, and the method used by our model of choice: CSRNet. Congested Scene Recognition Net (CSRNet) is a crowd size estimation model that was proposed by computer scientists at the University of Illinois Urbana-Champaign in 2018. CSRNet leverages the VGG-16 image classification network as the frontend portion since it has a flexible and effective architecture. The VGG-16 uses a variety of activation functions (used to abstract node outputs inter-layer) and other hyper-parameters (layer/node configuration) including ReLU and SoftMax. ReLU is standard in machine learning, it means Rectified Linear Unit. SoftMax is less common but noteworthy. The goal of SoftMax is to turn numbers into probabilities and polarize classification. This can be useful in image classification at the last layer because it provides probabilities for any classification scenario. Since our goal is to output a density map instead of one-hot classification, CSRNet’s backend structure replaces the fully connected and SoftMax layers with more convolutional layers. Dilated Kernels: In the backend, dilated convolutional layers are used in place of max pooling in order to retain the output dimensions and increase the receptive field. The dilated kernel is a standard convolutional kernel that is dispersed by a dilation factor (seen below). Dilated kernels do not reduce image quality which is important because the larger the density map dimensions, the more accurate our estimate can be. The dilated convolutions help produce our density maps: Results: CSRNet achieved better MAE and MSE results than the other popular Crowd Size Estimation Networks. For some more context, MAE is the Mean Absolute Error. Mean absolute error is the average of the absolute error for every training image. MSE is the Mean Squared Error. MSE is different than MAE because it puts more emphasis on large errors. Now that all the Queen’s students are gone — let’s code! We used a tutorial from Analytics Vidhya: Building your own Crowd Counting Model . We stored all of our pre-processing, training, testing, and validation scripts in a Google Drive folder. In Google Drive we were able to employ Google Colab Notebooks to create and share our model. All scripts were written and compiled in Python 3 or Python 2 in some cases. We also installed a CUDA GPU in order to train our model. We used the ShanghaiTech dataset because of its breadth in camera perspective, variety of crowd sizes, and large quantity of annotated data. The dataset contains almost 1200 images with over 330,000 annotated heads. The end goal of the training and testing in Google Drive was to produce our trained Model.PT file (PyTorch file) that we could upload to our front-end interface. In order to reach that goal, we had to compile and run: Ground truth production script Training script Validation script Ground truth production script: The purpose of this script was to convert the ground-truths provided by the dataset into density maps that could be used for training. Below you can see and example of the output. Converting the ground truth into a density map. Show the raw predicted count from a density map: np.sum(groundtruth) # Output -> 166.15 Training Script: The training script iterated through all of our train data set images and improved accuracy between each Epoch (Epoch is an iteration through the data). Example code of running the training script with our first data set: root = "/content/gdrive/My Drive/Western AI - Intro to Computer Vision Project/CSRNet Crowd Counting Model/Data/"!python2 '/content/gdrive/My Drive/Western AI - Intro to Computer Vision Project/CSRNet Crowd Counting Model/train.py' '/content/gdrive/My Drive/Western AI - Intro to Computer Vision Project/CSRNet Crowd Counting Model/part_A_train.json' '/content/gdrive/My Drive/Western AI - Intro to Computer Vision Project/CSRNet Crowd Counting Model/part_A_test.json' 0 0 Here is a snapshot of one of the training Epochs (15th): We were able to train our model for 100 full epochs, time and resource permitting. While monitoring the training we noticed a slight improvement in MAE with each epoch. If you look at the output above, the MAE in the 15th epoch was 70.621. That means the average error was 70.621 people (+/-). The MAE in the first epoch was 250, so we made some progress. With the size of the dataset (1200 images) and the aggregated size of every crowd (330,000 heads), there was an average of 275 people in each crowd. Given the large crowd sizes, our errors are satisfactory. Validation Script: This script took our trained model and determined the MAE and percent error over every testing example. (Note: this is an abstracted version of the validation script) checkpoint = torch.load('/content/gdrive/My Drive/Western AI - Intro to Computer Vision Project/CSRNet Crowd Counting Model/model.pt')model.load_state_dict(checkpoint['state_dict'])import numpy as npmae = []for i in xrange(len(img_paths)): ... mae.append(abs(np.sum(groundtruth))) print i, mae[i] The results varied, but finished with a MAE average of 90.19 for testing. This correlates well with the MAE values from the training script and does not indicate any significant overfitting/underfitting of our training set. Here is an snippet of some of the results: We ran a similar variation of this validation script that gave us model error/accuracy. The MAE values above correspond to a total testing error of 15.3% (two test sets: A and B). This means that our model had 84.7% accuracy. Model.pt: Once trained and tested we exported our model to a .pt file (PyTorch) that we could deploy on Flask. The model.pt file contains all the network parameters and weights stored in a massive dictionary object. You can check out the GitHub Repository for our Flask deployment here: https://github.com/jaysondale/Size.AI-Deployment Flask is a Python web framework built with an easy-to-extend philosophy (https://www.fullstackpython.com/flask.html). Launching your own web application is as easy running an ‘app.py’ Python file with this structure: from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world(): return 'Hello, World!'if __name__ == '__main__': app.run() In our deployment framework there are 5 key components: App— launches our localhost port 5000 Inferences— initializes our model and makes the predictions Commons —references our model file Model.pt — our trained model Templates— contains index and result templates (render results page) App (‘app.py’): the hello_world function (above) returns the content and functionality to be displayed in the web app. In our case we needed to accept an image from the user and return a prediction. When dealing with user input, we need to use HTTP Methods. ‘GET’ renders the template that we desire, ‘POST’ registers a user that can perform actions (upload a file). Here you can see the ‘upload_file’ function in the ‘app.py’ file: def upload_file(): if request.method == 'POST': absolute_path = os.path.abspath("../") if 'file' not in request.files: return redirect(request.url) file = request.files['file'] if not file: return print("GETTING PREDICTION") filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename)) prediction = get_prediction(file) return render_template('result.html', Prediction=prediction, File=filename) return render_template('index.html') Inferences (‘inference.py’): initializes our model and gets a prediction from it. The App script sent a file from the user as a parameter. The get_prediction function sends the image to the model and outputs the result: model = get_model() # initialize modeldef get_prediction(file): img = transform(Image.open(file).convert('RGB')).cpu() output = model(img.unsqueeze(0)) prediction=int(output.detach().cpu().sum().numpy()) # prediction print("Predicted Count: ",int(output.detach().cpu().sum().numpy())) return prediction Commons (‘commons.py’): references our model.pt file. We import and initialize CSRNet from PyTorch, then we load our state dictionary (our weights and biases from training): def get_model(): model = CSRNet() # original CSRNet model.load_state_dict( torch.load('/Users/charliemackie/CSRNET_DEPLOYMENT/SIZE.AI/Pytorch/model (2).pt', map_location='cpu')) # local reference to model.pt model.eval() return model The ‘/Users/charliemackie/CSRNET_DEPLOYMENT/SIZE.AI/Pytorch/model (2).pt’ is the path to the Model.pt saved in our project directory. Templates: has our custom HTML and CSS templates that will display our User Interface. These files have a combination of text labels, buttons, and titles. The most important part is displaying our prediction which is embedded in a text body like this: <h2 class="h5 mb-3 font-weight-normal"><i>{{Prediction}}</i></h2> With all of these components working together, we have our functioning Flask application! Our deployment process utilized three core Google Cloud features: Cloud Storage, Build, and Run. The first step in creating a cloud-based web system was to containerize our flask application, meaning it would contain all requirements and commands to run on any given computer system. While running, the cloud platform is programmed to listen on a specific network port at the IP address 0.0.0.0:8080. This IP and port was directly hardcoded into the flask app. The following files were added to the flask application directory to complete the containerization process: Requirements (“Requirements.txt”): This file contains all of the required python modules for the application to run. Docker (“Dockerfile”): This file contains a series of CLI commands which initiate the flask app. Dockerfile Contents: FROM python:3RUN apt-get update -yRUN apt-get install -y python-pip python-dev build-essentialCOPY . /appWORKDIR /appRUN pip install -r requirements.txtENTRYPOINT [“python”]CMD [“app.py”] YAML (“Cloudbuild.yaml” ): This file is used with the Google Cloud command line interface (CLI) and provides additional build parameters (this includes the build destination). Yaml file contents: steps:- name: ‘gcr.io/cloud-builders/docker’args: [‘build’, ‘-t’, ‘gcr.io/size-ai/app’, ‘.’]- name: ‘gcr.io/cloud-builders/docker’args: [‘push’, ‘gcr.io/size-ai/app’]images: [‘gcr.io/size-ai/app’] Once these files were added, the containerized application needed to be compressed and uploaded to Google Cloud Storage where it could be used in a web service. Once uploaded, Google Cloud Build would follow the steps provided by cloudbuild.yaml and construct a cloud-based application that would be ready for deployment. The following command was executed in the size-deployment directory to accomplish both of these tasks. $ gcloud builds submit By default, the gcloud interface looks for “cloudbuild.yaml” and completes the upload and build procedure. Once built, A web service was created in Google Cloud Run to host the containerized application. When configuring the service, we used the maximum memory and timeout allowances of 2GiB and 900s to give users the opportunity to upload the highest quality images possible. Once the build revision was selected, our application was successfully deployed on Google Cloud! The Google Cloud dashboard (below) lets us analyze many useful metrics including: Request count, Request latencies, Container CPU utilization, and Container memory utilization. With the ‘Request count’ metric, we can view every instance of our app that has been run. Next Steps: Tune hyper-parameters: We want to try and tune the network to achieve better results. Hyper-parameters could mean number of layers, layer size, or activation functions. Currently we run an off-the-shelf VGG-16/CSRNet structure — there are lots of possibilities for modification. Some areas that we have highlighted include adjusting the learning rate and/or using a longer training period on an enhanced GPU. We want to test different learning rates on a logarithmic scale in the near future. Optimizer choice: Our model currently uses a Stochastic Gradient Descent (SGD) optimizer. This means the mini-batch size is 1 and gradient descent is performed after each training example. We have discussed experimenting with an Adam optimizer or RMSprop. Once we implement a new optimizer we will have more hyperparameters to tune including adjusting our learning rate. Deploy at a larger Scale: Our web application is currently limited because of the size of our model. One potential solution is to use transfer learning to train a more efficient version of the model. We were inspired by Geoffrey Hinton when he presented to us at CUCAI re: Transfer Learning to develop light weight ML models. If we accomplish this, we could look into publishing an IOS app. Western AI: Western AI is the first student-led organization at Western that is aiming to create a community for Artificial Intelligence on campus. This means that we are building a foundation for students interested in engaging with AI to meet one another, learn real skills, and develop an appreciation for the importance of understanding the global implications of AI in a wide variety of industries and economies. In only our first year of ratified operation under the University Students’ Council (USC), we have officially engaged over 170 student members and partnered with numerous professors, industry experts, and other student organizations to create a remarkably strong community in an impressively short timespan. We believe there is so much room to grow, with countless opportunities. Sources: Analytics Vidhya implementation of CSRNet: www.analyticsvidhya.com PyTorch in Flask: github.com Original CSRNet Paper:
[ { "code": null, "e": 257, "s": 171, "text": "Please try the demo of our crowd size estimator: https://app3-qrhrzckmpq-ue.a.run.app" }, { "code": null, "e": 437, "s": 257, "text": "You can choose from some of the images in the ShanghaiTech dataset, or you can upload your own image. If you choose to upload your own image it must be a JPG/JPEG and under 100KB." }, { "code": null, "e": 478, "s": 437, "text": "You can check the image size as follows:" }, { "code": null, "e": 488, "s": 478, "text": "Computer:" }, { "code": null, "e": 545, "s": 488, "text": "Windows: Explorer → Select Image (bottom of the window)." }, { "code": null, "e": 588, "s": 545, "text": "Mac: Control + Click → ‘Get Info’ → ‘Size’" }, { "code": null, "e": 596, "s": 588, "text": "Mobile:" }, { "code": null, "e": 729, "s": 596, "text": "iPhone: Ensure the image is not a screenshot, then you can “Choose Size” of the image (bottom of screen). Choose “Small” and upload." }, { "code": null, "e": 832, "s": 729, "text": "Android: Check out this blog post, https://www.quora.com/How-do-I-reduce-the-size-of-photos-in-Android" }, { "code": null, "e": 976, "s": 832, "text": "In this article, I will explain how my Western AI project team developed a web application that estimates the size of a crowd in a given image." }, { "code": null, "e": 1239, "s": 976, "text": "Our goal from September 2019 was to deploy a machine learning model that could predict the sizes of crowds. We accomplished our goal and we were able to showcase our project at the Canadian Undergraduate Conference on AI (CUCAI) hosted by QMIND — Queen’s AI Hub." }, { "code": null, "e": 1510, "s": 1239, "text": "Crowd size estimation is a popular topic in the machine learning community. It has various applications including crowd control, customer management, and urban planning. Our model could be applicable in a school setting, measuring class attendance or building occupancy." }, { "code": null, "e": 1678, "s": 1510, "text": "Pictured above is our deployed web application. The web host takes a local image from the user in a JPG format then estimates the size (number of people) of the crowd." }, { "code": null, "e": 1713, "s": 1678, "text": "The purpose of this article is to:" }, { "code": null, "e": 1743, "s": 1713, "text": "Showcase our project: Size.AI" }, { "code": null, "e": 1820, "s": 1743, "text": "Give insight into crowd recognition and machine learning as they stand today" }, { "code": null, "e": 1886, "s": 1820, "text": "Provide a tutorial for the deployment of a machine learning model" }, { "code": null, "e": 1929, "s": 1886, "text": "The article will be structured as follows:" }, { "code": null, "e": 2012, "s": 1929, "text": "Brief introduction to machine learning, computer vision, and crowd size estimation" }, { "code": null, "e": 2053, "s": 2012, "text": "Current crowd size estimation approaches" }, { "code": null, "e": 2074, "s": 2053, "text": "Our approach: CSRNet" }, { "code": null, "e": 2131, "s": 2074, "text": "Training, testing, and validation (Google Colab/Python3)" }, { "code": null, "e": 2163, "s": 2131, "text": "Deployment (Flask/Google Cloud)" }, { "code": null, "e": 2199, "s": 2163, "text": "Next steps, sources, and Western AI" }, { "code": null, "e": 2622, "s": 2199, "text": "Artificial intelligence (AI) and machine learning (ML) have different meanings. Machine learning is a type of AI that involves statistical analysis and classification of problems. Popular machine learning applications include Natural Language Processing (NLP) and Computer Vision (CV). These applications are powered by machine learning algorithms which include K Nearest Neighbours (kNN), regression, and neural networks." }, { "code": null, "e": 3004, "s": 2622, "text": "Let’s focus on neural networks. Neural networks are loosely inspired by the structure of our brain. In the brain there is a network of neurons and each neuron stores bits of information. The neurons are attached to each other by axons which can transfer signals between neurons. In an artificial neural network, the neurons are represented by nodes which are organized into layers." }, { "code": null, "e": 3171, "s": 3004, "text": "The first layer of nodes can take some form of input and each layer proceeding will help classify the input. The last layer represents an easily interpretable output." }, { "code": null, "e": 3674, "s": 3171, "text": "Example: The computer wants to determine whether an image contains a dog or a cat. The image will be broken down to its pixels, and each pixel will be represented by an RGB Scale Value (0–255). The RGB values are inputs to the first layer of nodes. Each layer after that can represent some type of feature detection within the image; superposition of the eyes, head size compared to ear size ... etc. The final layer of nodes aggregates all of the information from previous layers and makes a decision." }, { "code": null, "e": 4194, "s": 3674, "text": "The ‘learning’ part of machine learning, involves iterating through many examples that are tagged with metadata which has already been classified by humans. The neural network undergoes the process of back-propagation where the error of the network is minimized. For each example provided, the network will make its prediction, then validate its prediction with the metadata provided and come up with a cost of error (predicted - actual). The goal of back-propagation is to minimize this error by adjusting the network." }, { "code": null, "e": 4369, "s": 4194, "text": "The math behind this is more complicated than I just explained. If you are still interested, check out Jayson’s (Project Manager), Simple classifier intro to neural networks." }, { "code": null, "e": 4587, "s": 4369, "text": "Crowd size estimation uses neural networks to classify people in a crowd then aggregate the amount of people detected. Currently there are three approaches to crowd size estimation: Detection, Regression, and Density." }, { "code": null, "e": 4767, "s": 4587, "text": "Detection: Focuses on object detection; recognizing features of a human (Ex: head, shoulders, body ... etc). This approach is typically more accurate for smaller crowds of people." }, { "code": null, "e": 4927, "s": 4767, "text": "Regression: Uses broader features of a person and puts more focus on edge details. This outperforms the detection models when presented with more dense crowds." }, { "code": null, "e": 5168, "s": 4927, "text": "Density: (See density map example below) Instead of focusing on individual people, density maps are produced that track groups of people. This is the most accurate method for dense crowds, and the method used by our model of choice: CSRNet." }, { "code": null, "e": 5339, "s": 5168, "text": "Congested Scene Recognition Net (CSRNet) is a crowd size estimation model that was proposed by computer scientists at the University of Illinois Urbana-Champaign in 2018." }, { "code": null, "e": 6156, "s": 5339, "text": "CSRNet leverages the VGG-16 image classification network as the frontend portion since it has a flexible and effective architecture. The VGG-16 uses a variety of activation functions (used to abstract node outputs inter-layer) and other hyper-parameters (layer/node configuration) including ReLU and SoftMax. ReLU is standard in machine learning, it means Rectified Linear Unit. SoftMax is less common but noteworthy. The goal of SoftMax is to turn numbers into probabilities and polarize classification. This can be useful in image classification at the last layer because it provides probabilities for any classification scenario. Since our goal is to output a density map instead of one-hot classification, CSRNet’s backend structure replaces the fully connected and SoftMax layers with more convolutional layers." }, { "code": null, "e": 6582, "s": 6156, "text": "Dilated Kernels: In the backend, dilated convolutional layers are used in place of max pooling in order to retain the output dimensions and increase the receptive field. The dilated kernel is a standard convolutional kernel that is dispersed by a dilation factor (seen below). Dilated kernels do not reduce image quality which is important because the larger the density map dimensions, the more accurate our estimate can be." }, { "code": null, "e": 6638, "s": 6582, "text": "The dilated convolutions help produce our density maps:" }, { "code": null, "e": 6745, "s": 6638, "text": "Results: CSRNet achieved better MAE and MSE results than the other popular Crowd Size Estimation Networks." }, { "code": null, "e": 6987, "s": 6745, "text": "For some more context, MAE is the Mean Absolute Error. Mean absolute error is the average of the absolute error for every training image. MSE is the Mean Squared Error. MSE is different than MAE because it puts more emphasis on large errors." }, { "code": null, "e": 7460, "s": 6987, "text": "Now that all the Queen’s students are gone — let’s code! We used a tutorial from Analytics Vidhya: Building your own Crowd Counting Model . We stored all of our pre-processing, training, testing, and validation scripts in a Google Drive folder. In Google Drive we were able to employ Google Colab Notebooks to create and share our model. All scripts were written and compiled in Python 3 or Python 2 in some cases. We also installed a CUDA GPU in order to train our model." }, { "code": null, "e": 7676, "s": 7460, "text": "We used the ShanghaiTech dataset because of its breadth in camera perspective, variety of crowd sizes, and large quantity of annotated data. The dataset contains almost 1200 images with over 330,000 annotated heads." }, { "code": null, "e": 7894, "s": 7676, "text": "The end goal of the training and testing in Google Drive was to produce our trained Model.PT file (PyTorch file) that we could upload to our front-end interface. In order to reach that goal, we had to compile and run:" }, { "code": null, "e": 7925, "s": 7894, "text": "Ground truth production script" }, { "code": null, "e": 7941, "s": 7925, "text": "Training script" }, { "code": null, "e": 7959, "s": 7941, "text": "Validation script" }, { "code": null, "e": 8126, "s": 7959, "text": "Ground truth production script: The purpose of this script was to convert the ground-truths provided by the dataset into density maps that could be used for training." }, { "code": null, "e": 8219, "s": 8126, "text": "Below you can see and example of the output. Converting the ground truth into a density map." }, { "code": null, "e": 8268, "s": 8219, "text": "Show the raw predicted count from a density map:" }, { "code": null, "e": 8307, "s": 8268, "text": "np.sum(groundtruth) # Output -> 166.15" }, { "code": null, "e": 8477, "s": 8307, "text": "Training Script: The training script iterated through all of our train data set images and improved accuracy between each Epoch (Epoch is an iteration through the data)." }, { "code": null, "e": 8546, "s": 8477, "text": "Example code of running the training script with our first data set:" }, { "code": null, "e": 9019, "s": 8546, "text": "root = \"/content/gdrive/My Drive/Western AI - Intro to Computer Vision Project/CSRNet Crowd Counting Model/Data/\"!python2 '/content/gdrive/My Drive/Western AI - Intro to Computer Vision Project/CSRNet Crowd Counting Model/train.py' '/content/gdrive/My Drive/Western AI - Intro to Computer Vision Project/CSRNet Crowd Counting Model/part_A_train.json' '/content/gdrive/My Drive/Western AI - Intro to Computer Vision Project/CSRNet Crowd Counting Model/part_A_test.json' 0 0" }, { "code": null, "e": 9076, "s": 9019, "text": "Here is a snapshot of one of the training Epochs (15th):" }, { "code": null, "e": 9639, "s": 9076, "text": "We were able to train our model for 100 full epochs, time and resource permitting. While monitoring the training we noticed a slight improvement in MAE with each epoch. If you look at the output above, the MAE in the 15th epoch was 70.621. That means the average error was 70.621 people (+/-). The MAE in the first epoch was 250, so we made some progress. With the size of the dataset (1200 images) and the aggregated size of every crowd (330,000 heads), there was an average of 275 people in each crowd. Given the large crowd sizes, our errors are satisfactory." }, { "code": null, "e": 9825, "s": 9639, "text": "Validation Script: This script took our trained model and determined the MAE and percent error over every testing example. (Note: this is an abstracted version of the validation script)" }, { "code": null, "e": 10131, "s": 9825, "text": "checkpoint = torch.load('/content/gdrive/My Drive/Western AI - Intro to Computer Vision Project/CSRNet Crowd Counting Model/model.pt')model.load_state_dict(checkpoint['state_dict'])import numpy as npmae = []for i in xrange(len(img_paths)): ... mae.append(abs(np.sum(groundtruth))) print i, mae[i]" }, { "code": null, "e": 10398, "s": 10131, "text": "The results varied, but finished with a MAE average of 90.19 for testing. This correlates well with the MAE values from the training script and does not indicate any significant overfitting/underfitting of our training set. Here is an snippet of some of the results:" }, { "code": null, "e": 10624, "s": 10398, "text": "We ran a similar variation of this validation script that gave us model error/accuracy. The MAE values above correspond to a total testing error of 15.3% (two test sets: A and B). This means that our model had 84.7% accuracy." }, { "code": null, "e": 10840, "s": 10624, "text": "Model.pt: Once trained and tested we exported our model to a .pt file (PyTorch) that we could deploy on Flask. The model.pt file contains all the network parameters and weights stored in a massive dictionary object." }, { "code": null, "e": 10960, "s": 10840, "text": "You can check out the GitHub Repository for our Flask deployment here: https://github.com/jaysondale/Size.AI-Deployment" }, { "code": null, "e": 11177, "s": 10960, "text": "Flask is a Python web framework built with an easy-to-extend philosophy (https://www.fullstackpython.com/flask.html). Launching your own web application is as easy running an ‘app.py’ Python file with this structure:" }, { "code": null, "e": 11320, "s": 11177, "text": "from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world(): return 'Hello, World!'if __name__ == '__main__': app.run()" }, { "code": null, "e": 11376, "s": 11320, "text": "In our deployment framework there are 5 key components:" }, { "code": null, "e": 11414, "s": 11376, "text": "App— launches our localhost port 5000" }, { "code": null, "e": 11474, "s": 11414, "text": "Inferences— initializes our model and makes the predictions" }, { "code": null, "e": 11509, "s": 11474, "text": "Commons —references our model file" }, { "code": null, "e": 11538, "s": 11509, "text": "Model.pt — our trained model" }, { "code": null, "e": 11607, "s": 11538, "text": "Templates— contains index and result templates (render results page)" }, { "code": null, "e": 12040, "s": 11607, "text": "App (‘app.py’): the hello_world function (above) returns the content and functionality to be displayed in the web app. In our case we needed to accept an image from the user and return a prediction. When dealing with user input, we need to use HTTP Methods. ‘GET’ renders the template that we desire, ‘POST’ registers a user that can perform actions (upload a file). Here you can see the ‘upload_file’ function in the ‘app.py’ file:" }, { "code": null, "e": 12606, "s": 12040, "text": "def upload_file(): if request.method == 'POST': absolute_path = os.path.abspath(\"../\") if 'file' not in request.files: return redirect(request.url) file = request.files['file'] if not file: return print(\"GETTING PREDICTION\") filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename)) prediction = get_prediction(file) return render_template('result.html', Prediction=prediction, File=filename) return render_template('index.html')" }, { "code": null, "e": 12826, "s": 12606, "text": "Inferences (‘inference.py’): initializes our model and gets a prediction from it. The App script sent a file from the user as a parameter. The get_prediction function sends the image to the model and outputs the result:" }, { "code": null, "e": 13147, "s": 12826, "text": "model = get_model() # initialize modeldef get_prediction(file): img = transform(Image.open(file).convert('RGB')).cpu() output = model(img.unsqueeze(0)) prediction=int(output.detach().cpu().sum().numpy()) # prediction print(\"Predicted Count: \",int(output.detach().cpu().sum().numpy())) return prediction" }, { "code": null, "e": 13321, "s": 13147, "text": "Commons (‘commons.py’): references our model.pt file. We import and initialize CSRNet from PyTorch, then we load our state dictionary (our weights and biases from training):" }, { "code": null, "e": 13567, "s": 13321, "text": "def get_model(): model = CSRNet() # original CSRNet model.load_state_dict( torch.load('/Users/charliemackie/CSRNET_DEPLOYMENT/SIZE.AI/Pytorch/model (2).pt', map_location='cpu')) # local reference to model.pt model.eval() return model" }, { "code": null, "e": 13701, "s": 13567, "text": "The ‘/Users/charliemackie/CSRNET_DEPLOYMENT/SIZE.AI/Pytorch/model (2).pt’ is the path to the Model.pt saved in our project directory." }, { "code": null, "e": 13953, "s": 13701, "text": "Templates: has our custom HTML and CSS templates that will display our User Interface. These files have a combination of text labels, buttons, and titles. The most important part is displaying our prediction which is embedded in a text body like this:" }, { "code": null, "e": 14019, "s": 13953, "text": "<h2 class=\"h5 mb-3 font-weight-normal\"><i>{{Prediction}}</i></h2>" }, { "code": null, "e": 14109, "s": 14019, "text": "With all of these components working together, we have our functioning Flask application!" }, { "code": null, "e": 14678, "s": 14109, "text": "Our deployment process utilized three core Google Cloud features: Cloud Storage, Build, and Run. The first step in creating a cloud-based web system was to containerize our flask application, meaning it would contain all requirements and commands to run on any given computer system. While running, the cloud platform is programmed to listen on a specific network port at the IP address 0.0.0.0:8080. This IP and port was directly hardcoded into the flask app. The following files were added to the flask application directory to complete the containerization process:" }, { "code": null, "e": 14795, "s": 14678, "text": "Requirements (“Requirements.txt”): This file contains all of the required python modules for the application to run." }, { "code": null, "e": 14892, "s": 14795, "text": "Docker (“Dockerfile”): This file contains a series of CLI commands which initiate the flask app." }, { "code": null, "e": 14913, "s": 14892, "text": "Dockerfile Contents:" }, { "code": null, "e": 15101, "s": 14913, "text": "FROM python:3RUN apt-get update -yRUN apt-get install -y python-pip python-dev build-essentialCOPY . /appWORKDIR /appRUN pip install -r requirements.txtENTRYPOINT [“python”]CMD [“app.py”]" }, { "code": null, "e": 15277, "s": 15101, "text": "YAML (“Cloudbuild.yaml” ): This file is used with the Google Cloud command line interface (CLI) and provides additional build parameters (this includes the build destination)." }, { "code": null, "e": 15297, "s": 15277, "text": "Yaml file contents:" }, { "code": null, "e": 15494, "s": 15297, "text": "steps:- name: ‘gcr.io/cloud-builders/docker’args: [‘build’, ‘-t’, ‘gcr.io/size-ai/app’, ‘.’]- name: ‘gcr.io/cloud-builders/docker’args: [‘push’, ‘gcr.io/size-ai/app’]images: [‘gcr.io/size-ai/app’]" }, { "code": null, "e": 15919, "s": 15494, "text": "Once these files were added, the containerized application needed to be compressed and uploaded to Google Cloud Storage where it could be used in a web service. Once uploaded, Google Cloud Build would follow the steps provided by cloudbuild.yaml and construct a cloud-based application that would be ready for deployment. The following command was executed in the size-deployment directory to accomplish both of these tasks." }, { "code": null, "e": 15942, "s": 15919, "text": "$ gcloud builds submit" }, { "code": null, "e": 16417, "s": 15942, "text": "By default, the gcloud interface looks for “cloudbuild.yaml” and completes the upload and build procedure. Once built, A web service was created in Google Cloud Run to host the containerized application. When configuring the service, we used the maximum memory and timeout allowances of 2GiB and 900s to give users the opportunity to upload the highest quality images possible. Once the build revision was selected, our application was successfully deployed on Google Cloud!" }, { "code": null, "e": 16684, "s": 16417, "text": "The Google Cloud dashboard (below) lets us analyze many useful metrics including: Request count, Request latencies, Container CPU utilization, and Container memory utilization. With the ‘Request count’ metric, we can view every instance of our app that has been run." }, { "code": null, "e": 16696, "s": 16684, "text": "Next Steps:" }, { "code": null, "e": 17189, "s": 16696, "text": "Tune hyper-parameters: We want to try and tune the network to achieve better results. Hyper-parameters could mean number of layers, layer size, or activation functions. Currently we run an off-the-shelf VGG-16/CSRNet structure — there are lots of possibilities for modification. Some areas that we have highlighted include adjusting the learning rate and/or using a longer training period on an enhanced GPU. We want to test different learning rates on a logarithmic scale in the near future." }, { "code": null, "e": 17560, "s": 17189, "text": "Optimizer choice: Our model currently uses a Stochastic Gradient Descent (SGD) optimizer. This means the mini-batch size is 1 and gradient descent is performed after each training example. We have discussed experimenting with an Adam optimizer or RMSprop. Once we implement a new optimizer we will have more hyperparameters to tune including adjusting our learning rate." }, { "code": null, "e": 17951, "s": 17560, "text": "Deploy at a larger Scale: Our web application is currently limited because of the size of our model. One potential solution is to use transfer learning to train a more efficient version of the model. We were inspired by Geoffrey Hinton when he presented to us at CUCAI re: Transfer Learning to develop light weight ML models. If we accomplish this, we could look into publishing an IOS app." }, { "code": null, "e": 17963, "s": 17951, "text": "Western AI:" }, { "code": null, "e": 18369, "s": 17963, "text": "Western AI is the first student-led organization at Western that is aiming to create a community for Artificial Intelligence on campus. This means that we are building a foundation for students interested in engaging with AI to meet one another, learn real skills, and develop an appreciation for the importance of understanding the global implications of AI in a wide variety of industries and economies." }, { "code": null, "e": 18749, "s": 18369, "text": "In only our first year of ratified operation under the University Students’ Council (USC), we have officially engaged over 170 student members and partnered with numerous professors, industry experts, and other student organizations to create a remarkably strong community in an impressively short timespan. We believe there is so much room to grow, with countless opportunities." }, { "code": null, "e": 18758, "s": 18749, "text": "Sources:" }, { "code": null, "e": 18801, "s": 18758, "text": "Analytics Vidhya implementation of CSRNet:" }, { "code": null, "e": 18825, "s": 18801, "text": "www.analyticsvidhya.com" }, { "code": null, "e": 18843, "s": 18825, "text": "PyTorch in Flask:" }, { "code": null, "e": 18854, "s": 18843, "text": "github.com" } ]
React Class Components
Before React 16.8, Class components were the only way to track state and lifecycle on a React component. Function components were considered "state-less". With the addition of Hooks, Function components are now almost equivalent to Class components. The differences are so minor that you will probably never need to use a Class component in React. Even though Function components are preferred, there are no current plans on removing Class components from React. This section will give you an overview of how to use Class components in React. Feel free to skip this section, and use Function Components instead. Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML via a render() function. Components come in two types, Class components and Function components, in this chapter you will learn about Class components. When creating a React component, the component's name must start with an upper case letter. The component has to include the extends React.Component statement, this statement creates an inheritance to React.Component, and gives your component access to React.Component's functions. The component also requires a render() method, this method returns HTML. Create a Class component called Car class Car extends React.Component { render() { return <h2>Hi, I am a Car!</h2>; } } Now your React application has a component called Car, which returns a <h2> element. To use this component in your application, use similar syntax as normal HTML: <Car /> Display the Car component in the "root" element: const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Car />); Run Example » If there is a constructor() function in your component, this function will be called when the component gets initiated. The constructor function is where you initiate the component's properties. In React, component properties should be kept in an object called state. You will learn more about state later in this tutorial. The constructor function is also where you honor the inheritance of the parent component by including the super() statement, which executes the parent component's constructor function, and your component has access to all the functions of the parent component (React.Component). Create a constructor function in the Car component, and add a color property: class Car extends React.Component { constructor() { super(); this.state = {color: "red"}; } render() { return <h2>I am a Car!</h2>; } } Use the color property in the render() function: class Car extends React.Component { constructor() { super(); this.state = {color: "red"}; } render() { return <h2>I am a {this.state.color} Car!</h2>; } } Run Example » Another way of handling component properties is by using props. Props are like function arguments, and you send them into the component as attributes. You will learn more about props in the next chapter. Use an attribute to pass a color to the Car component, and use it in the render() function: class Car extends React.Component { render() { return <h2>I am a {this.props.color} Car!</h2>; } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Car color="red"/>); Run Example » If your component has a constructor function, the props should always be passed to the constructor and also to the React.Component via the super() method. class Car extends React.Component { constructor(props) { super(props); } render() { return <h2>I am a {this.props.model}!</h2>; } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Car model="Mustang"/>); Run Example » We can refer to components inside other components: Use the Car component inside the Garage component: class Car extends React.Component { render() { return <h2>I am a Car!</h2>; } } class Garage extends React.Component { render() { return ( <div> <h1>Who lives in my Garage?</h1> <Car /> </div> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Garage />); Run Example » React is all about re-using code, and it can be smart to insert some of your components in separate files. To do that, create a new file with a .js file extension and put the code inside it: Note that the file must start by importing React (as before), and it has to end with the statement export default Car;. This is the new file, we named it Car.js: import React from 'react'; class Car extends React.Component { render() { return <h2>Hi, I am a Car!</h2>; } } export default Car; To be able to use the Car component, you have to import the file in your application. Now we import the Car.js file in the application, and we can use the Car component as if it was created here. import React from 'react'; import ReactDOM from 'react-dom/client'; import Car from './Car.js'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Car />); Run Example » React Class components have a built-in state object. You might have noticed that we used state earlier in the component constructor section. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders. The state object is initialized in the constructor: Specify the state object in the constructor method: class Car extends React.Component { constructor(props) { super(props); this.state = {brand: "Ford"}; } render() { return ( <div> <h1>My Car</h1> </div> ); } } The state object can contain as many properties as you like: Specify all the properties your component need: class Car extends React.Component { constructor(props) { super(props); this.state = { brand: "Ford", model: "Mustang", color: "red", year: 1964 }; } render() { return ( <div> <h1>My Car</h1> </div> ); } } Refer to the state object anywhere in the component by using the this.state.propertyname syntax: Refer to the state object in the render() method: class Car extends React.Component { constructor(props) { super(props); this.state = { brand: "Ford", model: "Mustang", color: "red", year: 1964 }; } render() { return ( <div> <h1>My {this.state.brand}</h1> <p> It is a {this.state.color} {this.state.model} from {this.state.year}. </p> </div> ); } } Run Example » To change a value in the state object, use the this.setState() method. When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s). Add a button with an onClick event that will change the color property: class Car extends React.Component { constructor(props) { super(props); this.state = { brand: "Ford", model: "Mustang", color: "red", year: 1964 }; } changeColor = () => { this.setState({color: "blue"}); } render() { return ( <div> <h1>My {this.state.brand}</h1> <p> It is a {this.state.color} {this.state.model} from {this.state.year}. </p> <button type="button" onClick={this.changeColor} >Change color</button> </div> ); } } Run Example » Always use the setState() method to change the state object, it will ensure that the component knows its been updated and calls the render() method (and all the other lifecycle methods). Each component in React has a lifecycle which you can monitor and manipulate during its three main phases. The three phases are: Mounting, Updating, and Unmounting. Mounting means putting elements into the DOM. React has four built-in methods that gets called, in this order, when mounting a component: constructor() getDerivedStateFromProps() render() componentDidMount() constructor() getDerivedStateFromProps() render() componentDidMount() The render() method is required and will always be called, the others are optional and will be called if you define them. The constructor() method is called before anything else, when the component is initiated, and it is the natural place to set up the initial state and other initial values. The constructor() method is called with the props, as arguments, and you should always start by calling the super(props) before anything else, this will initiate the parent's constructor method and allows the component to inherit methods from its parent (React.Component). The constructor method is called, by React, every time you make a component: class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } render() { return ( <h1>My Favorite Color is {this.state.favoritecolor}</h1> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header />); Run Example » The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM. This is the natural place to set the state object based on the initial props. It takes state as an argument, and returns an object with changes to the state. The example below starts with the favorite color being "red", but the getDerivedStateFromProps() method updates the favorite color based on the favcol attribute: The getDerivedStateFromProps method is called right before the render method: class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } static getDerivedStateFromProps(props, state) { return {favoritecolor: props.favcol }; } render() { return ( <h1>My Favorite Color is {this.state.favoritecolor}</h1> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header favcol="yellow"/>); Run Example » The render() method is required, and is the method that actually outputs the HTML to the DOM. A simple component with a simple render() method: class Header extends React.Component { render() { return ( <h1>This is the content of the Header component</h1> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header />); Run Example » The componentDidMount() method is called after the component is rendered. This is where you run statements that requires that the component is already placed in the DOM. At first my favorite color is red, but give me a second, and it is yellow instead: class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } componentDidMount() { setTimeout(() => { this.setState({favoritecolor: "yellow"}) }, 1000) } render() { return ( <h1>My Favorite Color is {this.state.favoritecolor}</h1> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header />); Run Example » The next phase in the lifecycle is when a component is updated. A component is updated whenever there is a change in the component's state or props. React has five built-in methods that gets called, in this order, when a component is updated: getDerivedStateFromProps() shouldComponentUpdate() render() getSnapshotBeforeUpdate() componentDidUpdate() getDerivedStateFromProps() shouldComponentUpdate() render() getSnapshotBeforeUpdate() componentDidUpdate() The render() method is required and will always be called, the others are optional and will be called if you define them. Also at updates the getDerivedStateFromProps method is called. This is the first method that is called when a component gets updated. This is still the natural place to set the state object based on the initial props. The example below has a button that changes the favorite color to blue, but since the getDerivedStateFromProps() method is called, which updates the state with the color from the favcol attribute, the favorite color is still rendered as yellow: If the component gets updated, the getDerivedStateFromProps() method is called: class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } static getDerivedStateFromProps(props, state) { return {favoritecolor: props.favcol }; } changeColor = () => { this.setState({favoritecolor: "blue"}); } render() { return ( <div> <h1>My Favorite Color is {this.state.favoritecolor}</h1> <button type="button" onClick={this.changeColor}>Change color</button> </div> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header favcol="yellow" />); Run Example » In the shouldComponentUpdate() method you can return a Boolean value that specifies whether React should continue with the rendering or not. The default value is true. The example below shows what happens when the shouldComponentUpdate() method returns false: Stop the component from rendering at any update: class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } shouldComponentUpdate() { return false; } changeColor = () => { this.setState({favoritecolor: "blue"}); } render() { return ( <div> <h1>My Favorite Color is {this.state.favoritecolor}</h1> <button type="button" onClick={this.changeColor}>Change color</button> </div> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header />); Run Example » Same example as above, but this time the shouldComponentUpdate() method returns true instead: class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } shouldComponentUpdate() { return true; } changeColor = () => { this.setState({favoritecolor: "blue"}); } render() { return ( <div> <h1>My Favorite Color is {this.state.favoritecolor}</h1> <button type="button" onClick={this.changeColor}>Change color</button> </div> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header />); Run Example » The render() method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes. The example below has a button that changes the favorite color to blue: Click the button to make a change in the component's state: class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } changeColor = () => { this.setState({favoritecolor: "blue"}); } render() { return ( <div> <h1>My Favorite Color is {this.state.favoritecolor}</h1> <button type="button" onClick={this.changeColor}>Change color</button> </div> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header />); Run Example » In the getSnapshotBeforeUpdate() method you have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update. If the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate() method, otherwise you will get an error. The example below might seem complicated, but all it does is this: When the component is mounting it is rendered with the favorite color "red". When the component has been mounted, a timer changes the state, and after one second, the favorite color becomes "yellow". This action triggers the update phase, and since this component has a getSnapshotBeforeUpdate() method, this method is executed, and writes a message to the empty DIV1 element. Then the componentDidUpdate() method is executed and writes a message in the empty DIV2 element: Use the getSnapshotBeforeUpdate() method to find out what the state object looked like before the update: class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } componentDidMount() { setTimeout(() => { this.setState({favoritecolor: "yellow"}) }, 1000) } getSnapshotBeforeUpdate(prevProps, prevState) { document.getElementById("div1").innerHTML = "Before the update, the favorite was " + prevState.favoritecolor; } componentDidUpdate() { document.getElementById("div2").innerHTML = "The updated favorite is " + this.state.favoritecolor; } render() { return ( <div> <h1>My Favorite Color is {this.state.favoritecolor}</h1> <div id="div1"></div> <div id="div2"></div> </div> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header />); Run Example » The componentDidUpdate method is called after the component is updated in the DOM. The example below might seem complicated, but all it does is this: When the component is mounting it is rendered with the favorite color "red". When the component has been mounted, a timer changes the state, and the color becomes "yellow". This action triggers the update phase, and since this component has a componentDidUpdate method, this method is executed and writes a message in the empty DIV element: The componentDidUpdate method is called after the update has been rendered in the DOM: class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } componentDidMount() { setTimeout(() => { this.setState({favoritecolor: "yellow"}) }, 1000) } componentDidUpdate() { document.getElementById("mydiv").innerHTML = "The updated favorite is " + this.state.favoritecolor; } render() { return ( <div> <h1>My Favorite Color is {this.state.favoritecolor}</h1> <div id="mydiv"></div> </div> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header />); Run Example » The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it. React has only one built-in method that gets called when a component is unmounted: componentWillUnmount() The componentWillUnmount method is called when the component is about to be removed from the DOM. Click the button to delete the header: class Container extends React.Component { constructor(props) { super(props); this.state = {show: true}; } delHeader = () => { this.setState({show: false}); } render() { let myheader; if (this.state.show) { myheader = <Child />; }; return ( <div> {myheader} <button type="button" onClick={this.delHeader}>Delete Header</button> </div> ); } } class Child extends React.Component { componentWillUnmount() { alert("The component named Header is about to be unmounted."); } render() { return ( <h1>Hello World!</h1> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Container />); Run Example » 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 155, "s": 0, "text": "Before React 16.8, Class components were the only way to track state and lifecycle on a React component.\nFunction components were considered \"state-less\"." }, { "code": null, "e": 348, "s": 155, "text": "With the addition of Hooks, Function components are now almost equivalent to Class components.\nThe differences are so minor that you will probably never need to use a Class component in React." }, { "code": null, "e": 463, "s": 348, "text": "Even though Function components are preferred, there are no current plans on removing Class components from React." }, { "code": null, "e": 543, "s": 463, "text": "This section will give you an overview of how to use Class components in React." }, { "code": null, "e": 612, "s": 543, "text": "Feel free to skip this section, and use Function Components instead." }, { "code": null, "e": 782, "s": 612, "text": "Components are independent and reusable bits of code.\nThey serve the same purpose as JavaScript functions,\nbut work in isolation and return HTML via a render() function." }, { "code": null, "e": 910, "s": 782, "text": "Components come in two types, Class components and Function components, in \nthis chapter you will learn about Class components." }, { "code": null, "e": 1003, "s": 910, "text": "When creating a React component, the component's name must start with an \nupper case letter." }, { "code": null, "e": 1194, "s": 1003, "text": "The component has to include the extends React.Component statement, this statement creates an inheritance to \nReact.Component, and gives your component access to React.Component's functions." }, { "code": null, "e": 1268, "s": 1194, "text": "The component also requires a render() method, \nthis method returns HTML." }, { "code": null, "e": 1304, "s": 1268, "text": "Create a Class component called Car" }, { "code": null, "e": 1397, "s": 1304, "text": "class Car extends React.Component {\n render() {\n return <h2>Hi, I am a Car!</h2>;\n }\n}\n" }, { "code": null, "e": 1483, "s": 1397, "text": "Now your React application has a component called Car, which returns a \n<h2> element." }, { "code": null, "e": 1569, "s": 1483, "text": "To use this component in your application, use similar syntax as normal HTML:\n<Car />" }, { "code": null, "e": 1618, "s": 1569, "text": "Display the Car component in the \"root\" element:" }, { "code": null, "e": 1707, "s": 1618, "text": "const root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Car />);" }, { "code": null, "e": 1724, "s": 1707, "text": "\nRun \nExample »\n" }, { "code": null, "e": 1845, "s": 1724, "text": "If there is a constructor() function in your component, this function will be called when the \ncomponent gets initiated." }, { "code": null, "e": 1920, "s": 1845, "text": "The constructor function is where you initiate the component's properties." }, { "code": null, "e": 1993, "s": 1920, "text": "In React, component properties should be kept in an object called\nstate." }, { "code": null, "e": 2050, "s": 1993, "text": "You will learn more about state later in \nthis tutorial." }, { "code": null, "e": 2332, "s": 2050, "text": "The constructor function is also where you honor the inheritance of the \nparent component by including the super() \nstatement, which executes the parent component's constructor function, and your component has access to all the functions of \nthe parent component (React.Component)." }, { "code": null, "e": 2410, "s": 2332, "text": "Create a constructor function in the Car component, and add a color property:" }, { "code": null, "e": 2567, "s": 2410, "text": "class Car extends React.Component {\n constructor() {\n super();\n this.state = {color: \"red\"};\n }\n render() {\n return <h2>I am a Car!</h2>;\n }\n}\n" }, { "code": null, "e": 2616, "s": 2567, "text": "Use the color property in the render() function:" }, { "code": null, "e": 2792, "s": 2616, "text": "class Car extends React.Component {\n constructor() {\n super();\n this.state = {color: \"red\"};\n }\n render() {\n return <h2>I am a {this.state.color} Car!</h2>;\n }\n}\n" }, { "code": null, "e": 2809, "s": 2792, "text": "\nRun \nExample »\n" }, { "code": null, "e": 2873, "s": 2809, "text": "Another way of handling component properties is by using props." }, { "code": null, "e": 2960, "s": 2873, "text": "Props are like function arguments, and you send them into the component as attributes." }, { "code": null, "e": 3013, "s": 2960, "text": "You will learn more about props in the next chapter." }, { "code": null, "e": 3106, "s": 3013, "text": "Use an attribute to pass a color to the Car component, and use it in the \nrender() function:" }, { "code": null, "e": 3315, "s": 3106, "text": "class Car extends React.Component {\n render() {\n return <h2>I am a {this.props.color} Car!</h2>;\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Car color=\"red\"/>);\n" }, { "code": null, "e": 3332, "s": 3315, "text": "\nRun \nExample »\n" }, { "code": null, "e": 3487, "s": 3332, "text": "If your component has a constructor function,\nthe props should always be passed to the constructor and also to the React.Component via the super() method." }, { "code": null, "e": 3741, "s": 3487, "text": "class Car extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return <h2>I am a {this.props.model}!</h2>;\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Car model=\"Mustang\"/>);\n" }, { "code": null, "e": 3758, "s": 3741, "text": "\nRun \nExample »\n" }, { "code": null, "e": 3810, "s": 3758, "text": "We can refer to components inside other components:" }, { "code": null, "e": 3861, "s": 3810, "text": "Use the Car component inside the Garage component:" }, { "code": null, "e": 4200, "s": 3861, "text": "class Car extends React.Component {\n render() {\n return <h2>I am a Car!</h2>;\n }\n}\n\nclass Garage extends React.Component {\n render() {\n return (\n <div>\n <h1>Who lives in my Garage?</h1>\n <Car />\n </div>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Garage />);\n" }, { "code": null, "e": 4217, "s": 4200, "text": "\nRun \nExample »\n" }, { "code": null, "e": 4325, "s": 4217, "text": "React is all about re-using code, and it can be smart to insert some of your \ncomponents in separate files." }, { "code": null, "e": 4410, "s": 4325, "text": "To do that, create a new file with a .js \nfile extension and put the code inside it:" }, { "code": null, "e": 4531, "s": 4410, "text": "Note that the file must start by importing React (as before), and it has to \nend with the statement export default Car;." }, { "code": null, "e": 4573, "s": 4531, "text": "This is the new file, we named it Car.js:" }, { "code": null, "e": 4715, "s": 4573, "text": "import React from 'react';\n\nclass Car extends React.Component {\n render() {\n return <h2>Hi, I am a Car!</h2>;\n }\n}\n\nexport default Car;\n" }, { "code": null, "e": 4802, "s": 4715, "text": "To be able to use the Car component, you have to import the file in your \napplication." }, { "code": null, "e": 4914, "s": 4802, "text": "Now we import the Car.js file in the application, and we can use the \nCar \ncomponent as if it was created here." }, { "code": null, "e": 5101, "s": 4914, "text": "import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport Car from './Car.js';\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Car />);\n" }, { "code": null, "e": 5118, "s": 5101, "text": "\nRun \nExample »\n" }, { "code": null, "e": 5171, "s": 5118, "text": "React Class components have a built-in state object." }, { "code": null, "e": 5259, "s": 5171, "text": "You might have noticed that we used state earlier in the component constructor section." }, { "code": null, "e": 5342, "s": 5259, "text": "The state object is where you store property values that belongs to the component." }, { "code": null, "e": 5399, "s": 5342, "text": "When the state object changes, the component re-renders." }, { "code": null, "e": 5451, "s": 5399, "text": "The state object is initialized in the constructor:" }, { "code": null, "e": 5503, "s": 5451, "text": "Specify the state object in the constructor method:" }, { "code": null, "e": 5705, "s": 5503, "text": "class Car extends React.Component {\n constructor(props) {\n super(props);\n this.state = {brand: \"Ford\"};\n }\n render() {\n return (\n <div>\n <h1>My Car</h1>\n </div>\n );\n }\n}\n" }, { "code": null, "e": 5766, "s": 5705, "text": "The state object can contain as many properties as you like:" }, { "code": null, "e": 5814, "s": 5766, "text": "Specify all the properties your component need:" }, { "code": null, "e": 6092, "s": 5814, "text": "class Car extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n brand: \"Ford\",\n model: \"Mustang\",\n color: \"red\",\n year: 1964\n };\n }\n render() {\n return (\n <div>\n <h1>My Car</h1>\n </div>\n );\n }\n}\n" }, { "code": null, "e": 6189, "s": 6092, "text": "Refer to the state object anywhere in the component by using the\nthis.state.propertyname syntax:" }, { "code": null, "e": 6242, "s": 6189, "text": "Refer to the state object in the \n render() method:" }, { "code": null, "e": 6660, "s": 6242, "text": "class Car extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n brand: \"Ford\",\n model: \"Mustang\",\n color: \"red\",\n year: 1964\n };\n }\n render() {\n return (\n <div>\n <h1>My {this.state.brand}</h1>\n <p>\n It is a {this.state.color}\n {this.state.model}\n from {this.state.year}.\n </p>\n </div>\n );\n }\n}\n" }, { "code": null, "e": 6677, "s": 6660, "text": "\nRun \nExample »\n" }, { "code": null, "e": 6748, "s": 6677, "text": "To change a value in the state object, use the this.setState() method." }, { "code": null, "e": 6889, "s": 6748, "text": "When a value in the state object changes, \nthe component will re-render, meaning that the output will change according to \nthe new value(s)." }, { "code": null, "e": 6964, "s": 6889, "text": "Add a button with an onClick event that \n will change the color property:" }, { "code": null, "e": 7554, "s": 6964, "text": "class Car extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n brand: \"Ford\",\n model: \"Mustang\",\n color: \"red\",\n year: 1964\n };\n }\n changeColor = () => {\n this.setState({color: \"blue\"});\n }\n render() {\n return (\n <div>\n <h1>My {this.state.brand}</h1>\n <p>\n It is a {this.state.color}\n {this.state.model}\n from {this.state.year}.\n </p>\n <button\n type=\"button\"\n onClick={this.changeColor}\n >Change color</button>\n </div>\n );\n }\n}\n" }, { "code": null, "e": 7571, "s": 7554, "text": "\nRun \nExample »\n" }, { "code": null, "e": 7758, "s": 7571, "text": "Always use the setState() method to change the state object,\nit will ensure that the component knows its been updated and calls the render() method\n(and all the other lifecycle methods)." }, { "code": null, "e": 7866, "s": 7758, "text": "Each component in React has a lifecycle which you can monitor and manipulate during its \nthree main phases." }, { "code": null, "e": 7924, "s": 7866, "text": "The three phases are: Mounting, Updating, and\nUnmounting." }, { "code": null, "e": 7970, "s": 7924, "text": "Mounting means putting elements into the DOM." }, { "code": null, "e": 8063, "s": 7970, "text": "React has four built-in methods that gets called, in this order, when \nmounting a component:" }, { "code": null, "e": 8135, "s": 8063, "text": "\nconstructor()\ngetDerivedStateFromProps()\nrender()\ncomponentDidMount()\n" }, { "code": null, "e": 8149, "s": 8135, "text": "constructor()" }, { "code": null, "e": 8176, "s": 8149, "text": "getDerivedStateFromProps()" }, { "code": null, "e": 8185, "s": 8176, "text": "render()" }, { "code": null, "e": 8205, "s": 8185, "text": "componentDidMount()" }, { "code": null, "e": 8328, "s": 8205, "text": "The render() method is required and will \nalways be called, the others are optional and will be called if you define them." }, { "code": null, "e": 8503, "s": 8328, "text": "The constructor() method is called before anything else, \nwhen the component is initiated, and it is the natural \nplace to set up the initial state and other \ninitial values." }, { "code": null, "e": 8780, "s": 8503, "text": "The constructor() method is called with the \nprops, as arguments, and you should always \nstart by calling the super(props) before \nanything else, this will initiate the parent's constructor method and allows the \ncomponent to inherit methods from its parent (React.Component)." }, { "code": null, "e": 8860, "s": 8780, "text": "The constructor method is called, by \n React, every time you make a component:" }, { "code": null, "e": 9181, "s": 8860, "text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n render() {\n return (\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header />);\n" }, { "code": null, "e": 9198, "s": 9181, "text": "\nRun \nExample »\n" }, { "code": null, "e": 9297, "s": 9198, "text": "The getDerivedStateFromProps() method is \ncalled right before rendering the element(s) in the DOM." }, { "code": null, "e": 9377, "s": 9297, "text": "This is the natural place to set the state object based on the initial \nprops.\n" }, { "code": null, "e": 9458, "s": 9377, "text": "It takes \nstate as an argument, and returns an object with changes to the\nstate." }, { "code": null, "e": 9622, "s": 9458, "text": "The example below starts with the favorite color being \n\"red\", but the\n\ngetDerivedStateFromProps() method updates the favorite color based on the\nfavcol attribute:" }, { "code": null, "e": 9703, "s": 9622, "text": "The getDerivedStateFromProps method is called \n right before the render method:" }, { "code": null, "e": 10135, "s": 9703, "text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n static getDerivedStateFromProps(props, state) {\n return {favoritecolor: props.favcol };\n }\n render() {\n return (\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header favcol=\"yellow\"/>);" }, { "code": null, "e": 10152, "s": 10135, "text": "\nRun \nExample »\n" }, { "code": null, "e": 10247, "s": 10152, "text": "The render() method is required, and is the \nmethod that actually outputs the HTML to the DOM." }, { "code": null, "e": 10300, "s": 10247, "text": "A simple component with a simple render() \n method:" }, { "code": null, "e": 10531, "s": 10300, "text": "class Header extends React.Component {\n render() {\n return (\n <h1>This is the content of the Header component</h1>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header />);\n" }, { "code": null, "e": 10548, "s": 10531, "text": "\nRun \nExample »\n" }, { "code": null, "e": 10623, "s": 10548, "text": "The componentDidMount() method is called after the \ncomponent is rendered." }, { "code": null, "e": 10719, "s": 10623, "text": "This is where you run statements that requires that the component is already placed in the DOM." }, { "code": null, "e": 10805, "s": 10719, "text": "At first my favorite color is red, but give me a second, and it is yellow \n instead:" }, { "code": null, "e": 11237, "s": 10805, "text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n componentDidMount() {\n setTimeout(() => {\n this.setState({favoritecolor: \"yellow\"})\n }, 1000)\n }\n render() {\n return (\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header />);\n" }, { "code": null, "e": 11254, "s": 11237, "text": "\nRun \nExample »\n" }, { "code": null, "e": 11318, "s": 11254, "text": "The next phase in the lifecycle is when a component is updated." }, { "code": null, "e": 11403, "s": 11318, "text": "A component is updated whenever there is a change in the component's\nstate or props." }, { "code": null, "e": 11498, "s": 11403, "text": "React has five built-in methods that gets called, in this order, when a component \nis updated:" }, { "code": null, "e": 11607, "s": 11498, "text": "\ngetDerivedStateFromProps()\nshouldComponentUpdate()\nrender()\ngetSnapshotBeforeUpdate()\ncomponentDidUpdate()\n" }, { "code": null, "e": 11634, "s": 11607, "text": "getDerivedStateFromProps()" }, { "code": null, "e": 11658, "s": 11634, "text": "shouldComponentUpdate()" }, { "code": null, "e": 11667, "s": 11658, "text": "render()" }, { "code": null, "e": 11693, "s": 11667, "text": "getSnapshotBeforeUpdate()" }, { "code": null, "e": 11714, "s": 11693, "text": "componentDidUpdate()" }, { "code": null, "e": 11837, "s": 11714, "text": "The render() method is required and will \nalways be called, the others are optional and will be called if you define them." }, { "code": null, "e": 11972, "s": 11837, "text": "Also at updates the getDerivedStateFromProps method is \ncalled. This is the first method that is called when a component gets updated." }, { "code": null, "e": 12059, "s": 11972, "text": "This is still the natural place to set the state object based on the initial props.\n\n\n" }, { "code": null, "e": 12308, "s": 12059, "text": "The example below has a button that changes the favorite color to blue, but \nsince the getDerivedStateFromProps() method is called, \nwhich updates the state with the color from the favcol attribute, the favorite color is \nstill \nrendered as yellow:" }, { "code": null, "e": 12388, "s": 12308, "text": "If the component gets updated, the getDerivedStateFromProps() method is called:" }, { "code": null, "e": 12996, "s": 12388, "text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n static getDerivedStateFromProps(props, state) {\n return {favoritecolor: props.favcol };\n }\n changeColor = () => {\n this.setState({favoritecolor: \"blue\"});\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <button type=\"button\" onClick={this.changeColor}>Change color</button>\n </div>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header favcol=\"yellow\" />);\n" }, { "code": null, "e": 13013, "s": 12996, "text": "\nRun \nExample »\n" }, { "code": null, "e": 13154, "s": 13013, "text": "In the shouldComponentUpdate() method\nyou can return a Boolean value that specifies whether React should continue with the rendering or not." }, { "code": null, "e": 13181, "s": 13154, "text": "The default value is true." }, { "code": null, "e": 13274, "s": 13181, "text": "The example below shows what happens when the \nshouldComponentUpdate() method returns false:" }, { "code": null, "e": 13323, "s": 13274, "text": "Stop the component from rendering at any update:" }, { "code": null, "e": 13868, "s": 13323, "text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n shouldComponentUpdate() {\n return false;\n }\n changeColor = () => {\n this.setState({favoritecolor: \"blue\"});\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <button type=\"button\" onClick={this.changeColor}>Change color</button>\n </div>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header />);\n" }, { "code": null, "e": 13885, "s": 13868, "text": "\nRun \nExample »\n" }, { "code": null, "e": 13982, "s": 13885, "text": "Same example as above, but this time the shouldComponentUpdate() method returns \n true instead:" }, { "code": null, "e": 14526, "s": 13982, "text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n shouldComponentUpdate() {\n return true;\n }\n changeColor = () => {\n this.setState({favoritecolor: \"blue\"});\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <button type=\"button\" onClick={this.changeColor}>Change color</button>\n </div>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header />);\n" }, { "code": null, "e": 14543, "s": 14526, "text": "\nRun \nExample »\n" }, { "code": null, "e": 14678, "s": 14543, "text": "The render() method is of course called when a component gets updated, \nit has to re-render the HTML to the DOM, with the new changes." }, { "code": null, "e": 14750, "s": 14678, "text": "The example below has a button that changes the favorite color to blue:" }, { "code": null, "e": 14810, "s": 14750, "text": "Click the button to make a change in the component's state:" }, { "code": null, "e": 15305, "s": 14810, "text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n changeColor = () => {\n this.setState({favoritecolor: \"blue\"});\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <button type=\"button\" onClick={this.changeColor}>Change color</button>\n </div>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header />);\n" }, { "code": null, "e": 15322, "s": 15305, "text": "\nRun \nExample »\n" }, { "code": null, "e": 15513, "s": 15322, "text": "In the getSnapshotBeforeUpdate() method\nyou have access to the props and \nstate before the update, meaning that \neven after the update, you can check what the values were before the \nupdate." }, { "code": null, "e": 15656, "s": 15513, "text": "If the getSnapshotBeforeUpdate() method\nis present, you should also include the \ncomponentDidUpdate() method, otherwise you will get an error." }, { "code": null, "e": 15723, "s": 15656, "text": "The example below might seem complicated, but all it does is this:" }, { "code": null, "e": 15801, "s": 15723, "text": "When the component is mounting it is rendered with the favorite \ncolor \"red\"." }, { "code": null, "e": 15925, "s": 15801, "text": "When the component has been mounted, a timer changes the state, and \nafter one second, the favorite color becomes \"yellow\"." }, { "code": null, "e": 16104, "s": 15925, "text": "This action triggers the update phase, and since this component has a \ngetSnapshotBeforeUpdate() method, this method is executed, and writes a \nmessage to the empty DIV1 element." }, { "code": null, "e": 16202, "s": 16104, "text": "Then the componentDidUpdate() method is \nexecuted and writes a message in the empty DIV2 element:" }, { "code": null, "e": 16319, "s": 16204, "text": "Use the \n getSnapshotBeforeUpdate() method to find out \n what the state object looked like before \n the update:" }, { "code": null, "e": 17146, "s": 16319, "text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n componentDidMount() {\n setTimeout(() => {\n this.setState({favoritecolor: \"yellow\"})\n }, 1000)\n }\n getSnapshotBeforeUpdate(prevProps, prevState) {\n document.getElementById(\"div1\").innerHTML =\n \"Before the update, the favorite was \" + prevState.favoritecolor;\n }\n componentDidUpdate() {\n document.getElementById(\"div2\").innerHTML =\n \"The updated favorite is \" + this.state.favoritecolor;\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <div id=\"div1\"></div>\n <div id=\"div2\"></div>\n </div>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header />);\n" }, { "code": null, "e": 17163, "s": 17146, "text": "\nRun \nExample »\n" }, { "code": null, "e": 17246, "s": 17163, "text": "The componentDidUpdate method\nis called after the component is updated in the DOM." }, { "code": null, "e": 17313, "s": 17246, "text": "The example below might seem complicated, but all it does is this:" }, { "code": null, "e": 17391, "s": 17313, "text": "When the component is mounting it is rendered with the favorite \ncolor \"red\"." }, { "code": null, "e": 17488, "s": 17391, "text": "When the component has been mounted, a timer changes the state, and \nthe color becomes \"yellow\"." }, { "code": null, "e": 17658, "s": 17488, "text": "This action triggers the update phase, and since this component has \na componentDidUpdate method, this method is \nexecuted and writes a message in the empty DIV element:" }, { "code": null, "e": 17748, "s": 17658, "text": "The componentDidUpdate method is called \n after the update has been rendered in the DOM:" }, { "code": null, "e": 18371, "s": 17748, "text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n componentDidMount() {\n setTimeout(() => {\n this.setState({favoritecolor: \"yellow\"})\n }, 1000)\n }\n componentDidUpdate() {\n document.getElementById(\"mydiv\").innerHTML =\n \"The updated favorite is \" + this.state.favoritecolor;\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <div id=\"mydiv\"></div>\n </div>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header />);\n" }, { "code": null, "e": 18388, "s": 18371, "text": "\nRun \nExample »\n" }, { "code": null, "e": 18506, "s": 18388, "text": "The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it." }, { "code": null, "e": 18589, "s": 18506, "text": "React has only one built-in method that gets called when a component is unmounted:" }, { "code": null, "e": 18612, "s": 18589, "text": "componentWillUnmount()" }, { "code": null, "e": 18711, "s": 18612, "text": "The componentWillUnmount method is \ncalled when the component is about to be removed from the DOM." }, { "code": null, "e": 18750, "s": 18711, "text": "Click the button to delete the header:" }, { "code": null, "e": 19466, "s": 18750, "text": "class Container extends React.Component {\n constructor(props) {\n super(props);\n this.state = {show: true};\n }\n delHeader = () => {\n this.setState({show: false});\n }\n render() {\n let myheader;\n if (this.state.show) {\n myheader = <Child />;\n };\n return (\n <div>\n {myheader}\n <button type=\"button\" onClick={this.delHeader}>Delete Header</button>\n </div>\n );\n }\n}\n\nclass Child extends React.Component {\n componentWillUnmount() {\n alert(\"The component named Header is about to be unmounted.\");\n }\n render() {\n return (\n <h1>Hello World!</h1>\n );\n }\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Container />);\n" }, { "code": null, "e": 19483, "s": 19466, "text": "\nRun \nExample »\n" }, { "code": null, "e": 19516, "s": 19483, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 19558, "s": 19516, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 19665, "s": 19558, "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": 19684, "s": 19665, "text": "[email protected]" } ]
How to create shock wave or explosion effect using HTML and CSS ? - GeeksforGeeks
27 Apr, 2020 The shock wave effect is also known as the explosion effect. It is one of the simple CSS effects. For a beginner, it is one of the best examples to learn the concept of pseudo-elements. The pseudo-element that we are using is hover. I recommend you to go through it before jumping into the code to understand it better. For the briefing, hover is used to applying styles to an element when the mouse hovers over it. HTML Code: By using HTML, we will create a normal structure where we use the explosion or shock wave effect.<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title></head> <body> <div class="geeks"></div></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title></head> <body> <div class="geeks"></div></body> </html> CSS Code: The first step is to aligning our div to the center of the page using flexbox, then we have to create a circle using border-radius property. We have increased the value of it’s offset at every step. Then we will use a transition duration to the div. Now use hover selector and copy and paste the box-shadow property which we used earlier and increased it’s offset value. We have increased its value so that on hover it feels like coming out of the center(explosion effect). You can play with the color of the box-shadow to have a different or even multiple color explosion.<style> body { margin: 0; padding: 0; background: black; display: flex; justify-content: center; align-items: center; height: 100vh; } .geeks { width: 20px; height: 20px; background: green; border-radius: 50%; box-shadow: 0 0 20px rgb(127, 153, 127), 0 0 40px rgb(127, 153, 127), 0 0 60px rgb(127, 153, 127), 0 0 80px rgb(127, 153, 127), 0 0 120px rgb(127, 153, 127), 0 0 220px rgb(127, 153, 127), 0 0 320px rgb(127, 153, 127); transition: 2s; } .geeks:hover { box-shadow: 0 0 0 30px rgb(83, 224, 83), 0 0 0 60px rgb(83, 224, 83), 0 0 0 100px rgb(83, 224, 83), 0 0 0 120px rgb(82, 226, 82), 0 0 0 200px rgb(37, 214, 37), 0 0 0 400px rgb(27, 165, 27), 0 0 0 450px rgb(63, 235, 63); }</style> <style> body { margin: 0; padding: 0; background: black; display: flex; justify-content: center; align-items: center; height: 100vh; } .geeks { width: 20px; height: 20px; background: green; border-radius: 50%; box-shadow: 0 0 20px rgb(127, 153, 127), 0 0 40px rgb(127, 153, 127), 0 0 60px rgb(127, 153, 127), 0 0 80px rgb(127, 153, 127), 0 0 120px rgb(127, 153, 127), 0 0 220px rgb(127, 153, 127), 0 0 320px rgb(127, 153, 127); transition: 2s; } .geeks:hover { box-shadow: 0 0 0 30px rgb(83, 224, 83), 0 0 0 60px rgb(83, 224, 83), 0 0 0 100px rgb(83, 224, 83), 0 0 0 120px rgb(82, 226, 82), 0 0 0 200px rgb(37, 214, 37), 0 0 0 400px rgb(27, 165, 27), 0 0 0 450px rgb(63, 235, 63); }</style> Final solution: In this section we will combine the above two sections together to achieve the mentioned task. Program:<!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 { margin: 0; padding: 0; background: black; display: flex; justify-content: center; align-items: center; height: 100vh; } .geeks { width: 20px; height: 20px; background: green; border-radius: 50%; box-shadow: 0 0 20px rgb(127, 153, 127), 0 0 40px rgb(127, 153, 127), 0 0 60px rgb(127, 153, 127), 0 0 80px rgb(127, 153, 127), 0 0 120px rgb(127, 153, 127), 0 0 220px rgb(127, 153, 127), 0 0 320px rgb(127, 153, 127); transition: 2s; } .geeks:hover { box-shadow: 0 0 0 30px rgb(83, 224, 83), 0 0 0 60px rgb(83, 224, 83), 0 0 0 100px rgb(83, 224, 83), 0 0 0 120px rgb(82, 226, 82), 0 0 0 200px rgb(37, 214, 37), 0 0 0 400px rgb(27, 165, 27), 0 0 0 450px rgb(63, 235, 63); } </style></head> <body> <div class="geeks"></div></body> </html> <!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 { margin: 0; padding: 0; background: black; display: flex; justify-content: center; align-items: center; height: 100vh; } .geeks { width: 20px; height: 20px; background: green; border-radius: 50%; box-shadow: 0 0 20px rgb(127, 153, 127), 0 0 40px rgb(127, 153, 127), 0 0 60px rgb(127, 153, 127), 0 0 80px rgb(127, 153, 127), 0 0 120px rgb(127, 153, 127), 0 0 220px rgb(127, 153, 127), 0 0 320px rgb(127, 153, 127); transition: 2s; } .geeks:hover { box-shadow: 0 0 0 30px rgb(83, 224, 83), 0 0 0 60px rgb(83, 224, 83), 0 0 0 100px rgb(83, 224, 83), 0 0 0 120px rgb(82, 226, 82), 0 0 0 200px rgb(37, 214, 37), 0 0 0 400px rgb(27, 165, 27), 0 0 0 450px rgb(63, 235, 63); } </style></head> <body> <div class="geeks"></div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc CSS-Selectors HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS How to position a div at the bottom of its container using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? Hide or show elements in HTML using display property REST API (Introduction)
[ { "code": null, "e": 24780, "s": 24752, "text": "\n27 Apr, 2020" }, { "code": null, "e": 25196, "s": 24780, "text": "The shock wave effect is also known as the explosion effect. It is one of the simple CSS effects. For a beginner, it is one of the best examples to learn the concept of pseudo-elements. The pseudo-element that we are using is hover. I recommend you to go through it before jumping into the code to understand it better. For the briefing, hover is used to applying styles to an element when the mouse hovers over it." }, { "code": null, "e": 25562, "s": 25196, "text": "HTML Code: By using HTML, we will create a normal structure where we use the explosion or shock wave effect.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title></head> <body> <div class=\"geeks\"></div></body> </html> " }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title></head> <body> <div class=\"geeks\"></div></body> </html> ", "e": 25820, "s": 25562, "text": null }, { "code": null, "e": 27451, "s": 25820, "text": "CSS Code: The first step is to aligning our div to the center of the page using flexbox, then we have to create a circle using border-radius property. We have increased the value of it’s offset at every step. Then we will use a transition duration to the div. Now use hover selector and copy and paste the box-shadow property which we used earlier and increased it’s offset value. We have increased its value so that on hover it feels like coming out of the center(explosion effect). You can play with the color of the box-shadow to have a different or even multiple color explosion.<style> body { margin: 0; padding: 0; background: black; display: flex; justify-content: center; align-items: center; height: 100vh; } .geeks { width: 20px; height: 20px; background: green; border-radius: 50%; box-shadow: 0 0 20px rgb(127, 153, 127), 0 0 40px rgb(127, 153, 127), 0 0 60px rgb(127, 153, 127), 0 0 80px rgb(127, 153, 127), 0 0 120px rgb(127, 153, 127), 0 0 220px rgb(127, 153, 127), 0 0 320px rgb(127, 153, 127); transition: 2s; } .geeks:hover { box-shadow: 0 0 0 30px rgb(83, 224, 83), 0 0 0 60px rgb(83, 224, 83), 0 0 0 100px rgb(83, 224, 83), 0 0 0 120px rgb(82, 226, 82), 0 0 0 200px rgb(37, 214, 37), 0 0 0 400px rgb(27, 165, 27), 0 0 0 450px rgb(63, 235, 63); }</style>" }, { "code": "<style> body { margin: 0; padding: 0; background: black; display: flex; justify-content: center; align-items: center; height: 100vh; } .geeks { width: 20px; height: 20px; background: green; border-radius: 50%; box-shadow: 0 0 20px rgb(127, 153, 127), 0 0 40px rgb(127, 153, 127), 0 0 60px rgb(127, 153, 127), 0 0 80px rgb(127, 153, 127), 0 0 120px rgb(127, 153, 127), 0 0 220px rgb(127, 153, 127), 0 0 320px rgb(127, 153, 127); transition: 2s; } .geeks:hover { box-shadow: 0 0 0 30px rgb(83, 224, 83), 0 0 0 60px rgb(83, 224, 83), 0 0 0 100px rgb(83, 224, 83), 0 0 0 120px rgb(82, 226, 82), 0 0 0 200px rgb(37, 214, 37), 0 0 0 400px rgb(27, 165, 27), 0 0 0 450px rgb(63, 235, 63); }</style>", "e": 28499, "s": 27451, "text": null }, { "code": null, "e": 28610, "s": 28499, "text": "Final solution: In this section we will combine the above two sections together to achieve the mentioned task." }, { "code": null, "e": 30055, "s": 28610, "text": "Program:<!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 { margin: 0; padding: 0; background: black; display: flex; justify-content: center; align-items: center; height: 100vh; } .geeks { width: 20px; height: 20px; background: green; border-radius: 50%; box-shadow: 0 0 20px rgb(127, 153, 127), 0 0 40px rgb(127, 153, 127), 0 0 60px rgb(127, 153, 127), 0 0 80px rgb(127, 153, 127), 0 0 120px rgb(127, 153, 127), 0 0 220px rgb(127, 153, 127), 0 0 320px rgb(127, 153, 127); transition: 2s; } .geeks:hover { box-shadow: 0 0 0 30px rgb(83, 224, 83), 0 0 0 60px rgb(83, 224, 83), 0 0 0 100px rgb(83, 224, 83), 0 0 0 120px rgb(82, 226, 82), 0 0 0 200px rgb(37, 214, 37), 0 0 0 400px rgb(27, 165, 27), 0 0 0 450px rgb(63, 235, 63); } </style></head> <body> <div class=\"geeks\"></div></body> </html>" }, { "code": "<!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 { margin: 0; padding: 0; background: black; display: flex; justify-content: center; align-items: center; height: 100vh; } .geeks { width: 20px; height: 20px; background: green; border-radius: 50%; box-shadow: 0 0 20px rgb(127, 153, 127), 0 0 40px rgb(127, 153, 127), 0 0 60px rgb(127, 153, 127), 0 0 80px rgb(127, 153, 127), 0 0 120px rgb(127, 153, 127), 0 0 220px rgb(127, 153, 127), 0 0 320px rgb(127, 153, 127); transition: 2s; } .geeks:hover { box-shadow: 0 0 0 30px rgb(83, 224, 83), 0 0 0 60px rgb(83, 224, 83), 0 0 0 100px rgb(83, 224, 83), 0 0 0 120px rgb(82, 226, 82), 0 0 0 200px rgb(37, 214, 37), 0 0 0 400px rgb(27, 165, 27), 0 0 0 450px rgb(63, 235, 63); } </style></head> <body> <div class=\"geeks\"></div></body> </html>", "e": 31492, "s": 30055, "text": null }, { "code": null, "e": 31500, "s": 31492, "text": "Output:" }, { "code": null, "e": 31637, "s": 31500, "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": 31646, "s": 31637, "text": "CSS-Misc" }, { "code": null, "e": 31660, "s": 31646, "text": "CSS-Selectors" }, { "code": null, "e": 31670, "s": 31660, "text": "HTML-Misc" }, { "code": null, "e": 31674, "s": 31670, "text": "CSS" }, { "code": null, "e": 31679, "s": 31674, "text": "HTML" }, { "code": null, "e": 31696, "s": 31679, "text": "Web Technologies" }, { "code": null, "e": 31723, "s": 31696, "text": "Web technologies Questions" }, { "code": null, "e": 31728, "s": 31723, "text": "HTML" }, { "code": null, "e": 31826, "s": 31728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31835, "s": 31826, "text": "Comments" }, { "code": null, "e": 31848, "s": 31835, "text": "Old Comments" }, { "code": null, "e": 31906, "s": 31848, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 31943, "s": 31906, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 31980, "s": 31943, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32021, "s": 31980, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 32085, "s": 32021, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 32145, "s": 32085, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32206, "s": 32145, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32256, "s": 32206, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 32309, "s": 32256, "text": "Hide or show elements in HTML using display property" } ]
Multiple Time Series Forecast & Demand Pattern Classification using R — Part 1 | by Gouthaman Tharmathasan | Towards Data Science
Time Series Analysis is a widely used method in business in order to get useful pieces of information such as demand forecasting, identify seasonal products, demand pattern categorization and other characteristics. Here we are going to focus on Time Series forecasting (using Statistical / Machine Learning / Deep Learning model to predict future values) & demand pattern categorization (categorizing products based on quantity and time). In this blog, I am going to explain how we can fit multiple (1000+) time series models using Statistical (Classical Models), Machine Learning & Deep Learning models, time-series feature engineering & demand pattern categorization. This series will have the following 5 parts: Part 1: Data Cleaning & Demand categorization. Part 2: Fit statistical Time Series models (ARIMA, ETS, CROSTON etc.) using fpp3 (tidy forecasting) R Package. Part 3: Time Series Feature Engineering using timetk R Package. Part 4: Fit Machine Learning models (XGBoost, Random Forest, etc.) & Hyperparameter tuning using modeltime & tidymodels R packages. Part 5: Fit Deeplearning models (NBeats & DeepAR) & Hyperparameter tuning using modeltime, modeltime.gluonts R packages. Let’s get started! PS: This is not the ONLY method to tackle this problem. However, this is one way to tackle this problem. The data I'm using is from the Food Demand Forecasting hackathon in AnalyticsVidhya. The goal of this hackathon is to forecast the number of orders for each meal/centre combos to a food delivery service. We have a total of 3,548 meal/centre combos (i.e. 77 centres & 51 meals), meaning that 3,548-time series models will have to be fitted. This technique in a business environment is also known as Scalable Forecasting. Let’s import libraries. pacman::p_load(tidyverse, magrittr) # data wrangling packagespacman::p_load(lubridate, tsintermittent, fpp3, modeltime, timetk, modeltime.gluonts, tidymodels, modeltime.ensemble, modeltime.resample) # time series model packagespacman::p_load(foreach, future) # parallel functionspacman::p_load(viridis, plotly) # visualizations packagestheme_set(hrbrthemes::theme_ipsum()) # set default themes Now read the train data to fit time series models and submission data to predict future values. meal_demand_tbl <- read.csv(unz("data/raw/train_GzS76OK.zip", "train.csv")) # reading train datanew_tbl <- read.csv("data/raw/test_QoiMO9B.csv") # the data need to forecastskimr::skim(meal_demand_tbl %>% # remove id select(-id) %>% # make center & meal id factors mutate(center_id = factor(center_id), meal_id = factor(meal_id))) # summary of data In this stage, data preprocessing steps were performed. This data was then transformed to time-series data (i.e. to tsibble object: this is a special type of data that handles time series models in fpp3 package). The above summary shows that there are 51 types of meals sold in 77 centres, which makes a total of 3,548-time series data, with each time series data consisting of 145 weeks. Here we will need to forecast the number of orders ( num_orders ) for each meal/centre combo. Furthermore, by looking at the column complete_rate , we can see that there are no missing values in variables. The column weekis in numbers from 1–145, so we will need to change this to dates. We will also remove combos (meal/centre) that did not require forecasting. date_list <- tibble(id = seq(1, 155, 1), week_date = seq(from = as.Date("2016-01-02"), by = "week", length.out = 155))master_data_tbl <- meal_demand_tbl %>% left_join(date_list, by = c("week" = "id")) %>% # joining the date inner_join(distinct(new_tbl, meal_id, center_id), by = c("meal_id", "center_id")) %>% # remove combos that did not want to forecast select(week_date, num_orders, everything(), -c(week, id)) Now let’s transform the train and submission data into complete data i.e. make irregular time series data to regular time series data by inserting new daterows. These newly created daterows make missing values for num_orders & other variables. Hence, zero was imputed for the variablenum_orders by assuming that no sales occurred on these specific weeks and for the other variables, we replaced them with their corresponding previous week values. For example, the following time series data (Table 1)shows that after the 4th week there is data missing up to 7th week. Table 2 shows the completed data with the new entries for those missing weeks (i.e. weeks 5 & 6). Then emailer_for_promotion & homepage_featured variables are transformed into a factor. master_data_tbl <- master_data_tbl %>% as_tsibble(key = c(meal_id, center_id), index = week_date) %>% ## num_urders missing value imputation ---- fill_gaps(num_orders = 0, .full = end()) %>% # make it complete by max week dates ## X variables missing value imputation ---- group_by_key() %>% fill_(fill_cols = c("emailer_for_promotion", "homepage_featured", "base_price", "checkout_price")) %>% # filling other variables ungroup() %>% ## change variables to factor ---- mutate(emailer_for_promotion = factor(emailer_for_promotion), homepage_featured = factor(homepage_featured)) A similar operation is carried out withsubmission file. ## New Table (Submission file) data wrangling ----new_tbl <- new_tbl %>% left_join(date_list, by = c("week" = "id")) %>% # joining the date full_join(new_data(master_data_tbl, n = 10), by = c("center_id", "meal_id", "week_date")) %>% as_tsibble(key = c(meal_id, center_id), index = week_date) %>% group_by_key() %>% fill_(fill_cols = c("emailer_for_promotion", "homepage_featured", "base_price", "checkout_price")) %>% # filling other variables ungroup() %>% # change variables to factor mutate(emailer_for_promotion = factor(emailer_for_promotion), homepage_featured = factor(homepage_featured)) Plot 1: Number of orders by Centres master_data_tbl %>% # Randomly Pick 4 Centres distinct(center_id) %>% sample_n(4) %>% # Joining the transaction data left_join(master_data_tbl) %>% group_by(week_date, center_id) %>% # aggregate to centres summarise(num_orders = sum(num_orders, na.rm = T)) %>% as_tsibble(key = center_id, index = week_date) %>% fill_gaps(num_orders = 0, .full = end()) %>% autoplot(num_orders) + scale_color_viridis(discrete = T) The above plot shows that the first few weeks of transactions for Center #24 are 0; these transactions have been removed. However, there are continuous transactions after this time period which have been included in the data to fit the model. master_data_tbl <- master_data_tbl %>% filter(center_id != 24) %>% bind_rows(master_data_tbl %>% filter(center_id == 24 & week_date > as.Date("2016-07-16"))) # remove entries before 2016/07/16 for center 24 Plot 2: Number of Orders by Meal ID’s master_data_tbl %>% # Randomly Pick 4 Meals distinct(meal_id) %>% sample_n(3) %>% # Joining the transaction data left_join(master_data_tbl) %>% group_by(week_date, meal_id) %>% summarise(num_orders = sum(num_orders, na.rm = T)) %>% as_tsibble(key = meal_id, index = week_date) %>% fill_gaps(num_orders = 0, .full = end()) %>% autoplot(num_orders) + scale_color_viridis(discrete = T) The above plot shows the introduction of new meals, making a shorter time series data. So there is a possibility that these types of time series data should be treated separately by Cross-Validation method. Now we are going to identify each meal/centre combos demand pattern category (Smooth, Erratic, Lumpy & Intermittent). Why? When you are doing forecast on real-world data (i.e. your organization data), you will end up with the majority of your products in a sporadic demand pattern. These type of products show low forecast accuracy and it is difficult to increase their accuracy. This is due to their forecastability being low. So what can we do for these type of products? We must calculate the safety stock value rather than spend time on increasing their forecast accuracy. Furthermore, in the majority of the time, these sporadic products are not high revenue generators. This will help us differentiate our forecasting project into two parts. For regular demand, products focus on increasing forecast accuracy and sporadic demand products calculate safety stock. Also, identifying these demand patterns means that different times series models can be applied to them specifically. For example, Croston & SBA are suitable for sporadic demand patterns. How? In R we can use the function idclass in the R packagetsintermittent . In the function idclass, when the parameter typeis equal to SBC,this will calculate the following two values: cv2 — measures the variation in quantitiesp — measures the inter-demand interval cv2 — measures the variation in quantities p — measures the inter-demand interval Based on these two measures, we can categorize the demand pattern into Smooth (p < 1.32 & cv2 < 0.49), Erratic (p < 1.32 & cv2 ≥ 0.49), Lumpy (p ≥1.32 & cv2 ≥0.49) & Intermittent (p ≥1.32 & cv2 < 0.49). Smooth: The smooth demand pattern shows a regular demand and regular time. i.e. This type of products can be sold every day or every week. Erratic: The erratic demand pattern shows regularity in time but the selling quantity varied dramatically. i.e. This type of products can be sold every day or every week however, for example, one day it may sell 3 in quantity whereas, another day it could sell 100 in quantity. Intermittent: The intermittent demand pattern shows irregularity in time and regularity in quantity pattern. i.e. This type of product is sold for the first week then for several weeks it will not sell but in the end, the same amount of product is sold. Lumpy: The lumpy demand pattern shows irregularity in time and irregularity in the quantity pattern. This particular type of demand pattern is difficult to forecast no matter what type of time series models is used. A solution for this type of product is to have a safety stock. Let’s start the coding! First, we transform longer format data into wider format i.e. create 3,548 columns (total number of meal/centre time-series data). For example: # make each combo ts as column wide_dt <- .x %>% transmute(week_date, id = paste0("x_", center_id, "_", meal_id), num_orders) %>% pivot_wider(names_from = id, values_from = num_orders, values_fill = 0) %>% arrange(week_date) %>% # arrange by week date select(-week_date) %>% data.frame() Then apply idclass to the transformed data frame. ts_cate_obj <- idclass(wide_dt, type = "SBC", outplot = "none") ts_cate_obj shown above is a matrix. We will now change this matrix format to thedata.frame and then apply cutoff values to categorize the demand patterns. ts_categorization <- data.frame(id = row.names(t(wide_dt)), cv2 = ts_cate_obj$cv2, p = ts_cate_obj$p) %>% separate(id, into = c("x", "center_id", "meal_id"), sep = "_") %>% select(-x) %>% mutate(demand_cate = case_when(p < 1.32 & cv2 < 0.49 ~ "Smooth", p >= 1.32 & cv2 < 0.49 ~ "Intermittent", p < 1.32 & cv2 >= 0.49 ~ "Erratic", p >= 1.32 & cv2 >= 0.49 ~ "Lumpy")) %>% mutate(center_id = as.integer(as.character(center_id)), meal_id = as.integer(as.character(meal_id))) Let’s see the summary of the above analysis in a bar chart. The above plot shows that in the data, a majority of time series meal/centre combos fall under Smooth & Erratic. This means that a regular time series model such as ARIMA, ETS etc. would have suited well. Also, advanced models such as Croston & SBA have been fitted in order to tackle the intermittent & lumpy demand pattern. Machine learning / deep learning models can also be fitted by using these demand pattern type as a feature. The Cross-Validation method has been used to fit No Demand (i.e. transactions less than 20) combos. In the following parts, we will do feature engineering, fit time series models, machine learning models, deep learning models and compare their accuracies to find a suitable model. Kourentzes, N., 2014. Intermittent Demand Forecasting Package For R — Nikolaos Kourentzes. Kourentzes.com. Available at: <https://kourentzes.com/forecasting/2014/06/23/intermittent-demand-forecasting-package-for-r/> [Accessed 22 January 2021]. frePPLe. 2021. Demand Classification: Why Forecastability Matters — Frepple APS. Available at: <https://frepple.com/blog/demand-classification/> [Accessed 22 January 2021].
[ { "code": null, "e": 611, "s": 172, "text": "Time Series Analysis is a widely used method in business in order to get useful pieces of information such as demand forecasting, identify seasonal products, demand pattern categorization and other characteristics. Here we are going to focus on Time Series forecasting (using Statistical / Machine Learning / Deep Learning model to predict future values) & demand pattern categorization (categorizing products based on quantity and time)." }, { "code": null, "e": 887, "s": 611, "text": "In this blog, I am going to explain how we can fit multiple (1000+) time series models using Statistical (Classical Models), Machine Learning & Deep Learning models, time-series feature engineering & demand pattern categorization. This series will have the following 5 parts:" }, { "code": null, "e": 934, "s": 887, "text": "Part 1: Data Cleaning & Demand categorization." }, { "code": null, "e": 1045, "s": 934, "text": "Part 2: Fit statistical Time Series models (ARIMA, ETS, CROSTON etc.) using fpp3 (tidy forecasting) R Package." }, { "code": null, "e": 1109, "s": 1045, "text": "Part 3: Time Series Feature Engineering using timetk R Package." }, { "code": null, "e": 1241, "s": 1109, "text": "Part 4: Fit Machine Learning models (XGBoost, Random Forest, etc.) & Hyperparameter tuning using modeltime & tidymodels R packages." }, { "code": null, "e": 1362, "s": 1241, "text": "Part 5: Fit Deeplearning models (NBeats & DeepAR) & Hyperparameter tuning using modeltime, modeltime.gluonts R packages." }, { "code": null, "e": 1381, "s": 1362, "text": "Let’s get started!" }, { "code": null, "e": 1486, "s": 1381, "text": "PS: This is not the ONLY method to tackle this problem. However, this is one way to tackle this problem." }, { "code": null, "e": 1906, "s": 1486, "text": "The data I'm using is from the Food Demand Forecasting hackathon in AnalyticsVidhya. The goal of this hackathon is to forecast the number of orders for each meal/centre combos to a food delivery service. We have a total of 3,548 meal/centre combos (i.e. 77 centres & 51 meals), meaning that 3,548-time series models will have to be fitted. This technique in a business environment is also known as Scalable Forecasting." }, { "code": null, "e": 1930, "s": 1906, "text": "Let’s import libraries." }, { "code": null, "e": 2324, "s": 1930, "text": "pacman::p_load(tidyverse, magrittr) # data wrangling packagespacman::p_load(lubridate, tsintermittent, fpp3, modeltime, timetk, modeltime.gluonts, tidymodels, modeltime.ensemble, modeltime.resample) # time series model packagespacman::p_load(foreach, future) # parallel functionspacman::p_load(viridis, plotly) # visualizations packagestheme_set(hrbrthemes::theme_ipsum()) # set default themes" }, { "code": null, "e": 2420, "s": 2324, "text": "Now read the train data to fit time series models and submission data to predict future values." }, { "code": null, "e": 2842, "s": 2420, "text": "meal_demand_tbl <- read.csv(unz(\"data/raw/train_GzS76OK.zip\", \"train.csv\")) # reading train datanew_tbl <- read.csv(\"data/raw/test_QoiMO9B.csv\") # the data need to forecastskimr::skim(meal_demand_tbl %>% # remove id select(-id) %>% # make center & meal id factors mutate(center_id = factor(center_id), meal_id = factor(meal_id))) # summary of data" }, { "code": null, "e": 3055, "s": 2842, "text": "In this stage, data preprocessing steps were performed. This data was then transformed to time-series data (i.e. to tsibble object: this is a special type of data that handles time series models in fpp3 package)." }, { "code": null, "e": 3437, "s": 3055, "text": "The above summary shows that there are 51 types of meals sold in 77 centres, which makes a total of 3,548-time series data, with each time series data consisting of 145 weeks. Here we will need to forecast the number of orders ( num_orders ) for each meal/centre combo. Furthermore, by looking at the column complete_rate , we can see that there are no missing values in variables." }, { "code": null, "e": 3594, "s": 3437, "text": "The column weekis in numbers from 1–145, so we will need to change this to dates. We will also remove combos (meal/centre) that did not require forecasting." }, { "code": null, "e": 4030, "s": 3594, "text": "date_list <- tibble(id = seq(1, 155, 1), week_date = seq(from = as.Date(\"2016-01-02\"), by = \"week\", length.out = 155))master_data_tbl <- meal_demand_tbl %>% left_join(date_list, by = c(\"week\" = \"id\")) %>% # joining the date inner_join(distinct(new_tbl, meal_id, center_id), by = c(\"meal_id\", \"center_id\")) %>% # remove combos that did not want to forecast select(week_date, num_orders, everything(), -c(week, id))" }, { "code": null, "e": 4477, "s": 4030, "text": "Now let’s transform the train and submission data into complete data i.e. make irregular time series data to regular time series data by inserting new daterows. These newly created daterows make missing values for num_orders & other variables. Hence, zero was imputed for the variablenum_orders by assuming that no sales occurred on these specific weeks and for the other variables, we replaced them with their corresponding previous week values." }, { "code": null, "e": 4696, "s": 4477, "text": "For example, the following time series data (Table 1)shows that after the 4th week there is data missing up to 7th week. Table 2 shows the completed data with the new entries for those missing weeks (i.e. weeks 5 & 6)." }, { "code": null, "e": 4784, "s": 4696, "text": "Then emailer_for_promotion & homepage_featured variables are transformed into a factor." }, { "code": null, "e": 5381, "s": 4784, "text": "master_data_tbl <- master_data_tbl %>% as_tsibble(key = c(meal_id, center_id), index = week_date) %>% ## num_urders missing value imputation ---- fill_gaps(num_orders = 0, .full = end()) %>% # make it complete by max week dates ## X variables missing value imputation ---- group_by_key() %>% fill_(fill_cols = c(\"emailer_for_promotion\", \"homepage_featured\", \"base_price\", \"checkout_price\")) %>% # filling other variables ungroup() %>% ## change variables to factor ---- mutate(emailer_for_promotion = factor(emailer_for_promotion), homepage_featured = factor(homepage_featured))" }, { "code": null, "e": 5437, "s": 5381, "text": "A similar operation is carried out withsubmission file." }, { "code": null, "e": 6051, "s": 5437, "text": "## New Table (Submission file) data wrangling ----new_tbl <- new_tbl %>% left_join(date_list, by = c(\"week\" = \"id\")) %>% # joining the date full_join(new_data(master_data_tbl, n = 10), by = c(\"center_id\", \"meal_id\", \"week_date\")) %>% as_tsibble(key = c(meal_id, center_id), index = week_date) %>% group_by_key() %>% fill_(fill_cols = c(\"emailer_for_promotion\", \"homepage_featured\", \"base_price\", \"checkout_price\")) %>% # filling other variables ungroup() %>% # change variables to factor mutate(emailer_for_promotion = factor(emailer_for_promotion), homepage_featured = factor(homepage_featured))" }, { "code": null, "e": 6087, "s": 6051, "text": "Plot 1: Number of orders by Centres" }, { "code": null, "e": 6517, "s": 6087, "text": "master_data_tbl %>% # Randomly Pick 4 Centres distinct(center_id) %>% sample_n(4) %>% # Joining the transaction data left_join(master_data_tbl) %>% group_by(week_date, center_id) %>% # aggregate to centres summarise(num_orders = sum(num_orders, na.rm = T)) %>% as_tsibble(key = center_id, index = week_date) %>% fill_gaps(num_orders = 0, .full = end()) %>% autoplot(num_orders) + scale_color_viridis(discrete = T)" }, { "code": null, "e": 6760, "s": 6517, "text": "The above plot shows that the first few weeks of transactions for Center #24 are 0; these transactions have been removed. However, there are continuous transactions after this time period which have been included in the data to fit the model." }, { "code": null, "e": 6982, "s": 6760, "text": "master_data_tbl <- master_data_tbl %>% filter(center_id != 24) %>% bind_rows(master_data_tbl %>% filter(center_id == 24 & week_date > as.Date(\"2016-07-16\"))) # remove entries before 2016/07/16 for center 24" }, { "code": null, "e": 7020, "s": 6982, "text": "Plot 2: Number of Orders by Meal ID’s" }, { "code": null, "e": 7415, "s": 7020, "text": "master_data_tbl %>% # Randomly Pick 4 Meals distinct(meal_id) %>% sample_n(3) %>% # Joining the transaction data left_join(master_data_tbl) %>% group_by(week_date, meal_id) %>% summarise(num_orders = sum(num_orders, na.rm = T)) %>% as_tsibble(key = meal_id, index = week_date) %>% fill_gaps(num_orders = 0, .full = end()) %>% autoplot(num_orders) + scale_color_viridis(discrete = T)" }, { "code": null, "e": 7622, "s": 7415, "text": "The above plot shows the introduction of new meals, making a shorter time series data. So there is a possibility that these types of time series data should be treated separately by Cross-Validation method." }, { "code": null, "e": 7740, "s": 7622, "text": "Now we are going to identify each meal/centre combos demand pattern category (Smooth, Erratic, Lumpy & Intermittent)." }, { "code": null, "e": 7745, "s": 7740, "text": "Why?" }, { "code": null, "e": 8199, "s": 7745, "text": "When you are doing forecast on real-world data (i.e. your organization data), you will end up with the majority of your products in a sporadic demand pattern. These type of products show low forecast accuracy and it is difficult to increase their accuracy. This is due to their forecastability being low. So what can we do for these type of products? We must calculate the safety stock value rather than spend time on increasing their forecast accuracy." }, { "code": null, "e": 8490, "s": 8199, "text": "Furthermore, in the majority of the time, these sporadic products are not high revenue generators. This will help us differentiate our forecasting project into two parts. For regular demand, products focus on increasing forecast accuracy and sporadic demand products calculate safety stock." }, { "code": null, "e": 8678, "s": 8490, "text": "Also, identifying these demand patterns means that different times series models can be applied to them specifically. For example, Croston & SBA are suitable for sporadic demand patterns." }, { "code": null, "e": 8683, "s": 8678, "text": "How?" }, { "code": null, "e": 8863, "s": 8683, "text": "In R we can use the function idclass in the R packagetsintermittent . In the function idclass, when the parameter typeis equal to SBC,this will calculate the following two values:" }, { "code": null, "e": 8944, "s": 8863, "text": "cv2 — measures the variation in quantitiesp — measures the inter-demand interval" }, { "code": null, "e": 8987, "s": 8944, "text": "cv2 — measures the variation in quantities" }, { "code": null, "e": 9026, "s": 8987, "text": "p — measures the inter-demand interval" }, { "code": null, "e": 9229, "s": 9026, "text": "Based on these two measures, we can categorize the demand pattern into Smooth (p < 1.32 & cv2 < 0.49), Erratic (p < 1.32 & cv2 ≥ 0.49), Lumpy (p ≥1.32 & cv2 ≥0.49) & Intermittent (p ≥1.32 & cv2 < 0.49)." }, { "code": null, "e": 9237, "s": 9229, "text": "Smooth:" }, { "code": null, "e": 9368, "s": 9237, "text": "The smooth demand pattern shows a regular demand and regular time. i.e. This type of products can be sold every day or every week." }, { "code": null, "e": 9377, "s": 9368, "text": "Erratic:" }, { "code": null, "e": 9646, "s": 9377, "text": "The erratic demand pattern shows regularity in time but the selling quantity varied dramatically. i.e. This type of products can be sold every day or every week however, for example, one day it may sell 3 in quantity whereas, another day it could sell 100 in quantity." }, { "code": null, "e": 9660, "s": 9646, "text": "Intermittent:" }, { "code": null, "e": 9900, "s": 9660, "text": "The intermittent demand pattern shows irregularity in time and regularity in quantity pattern. i.e. This type of product is sold for the first week then for several weeks it will not sell but in the end, the same amount of product is sold." }, { "code": null, "e": 9907, "s": 9900, "text": "Lumpy:" }, { "code": null, "e": 10179, "s": 9907, "text": "The lumpy demand pattern shows irregularity in time and irregularity in the quantity pattern. This particular type of demand pattern is difficult to forecast no matter what type of time series models is used. A solution for this type of product is to have a safety stock." }, { "code": null, "e": 10203, "s": 10179, "text": "Let’s start the coding!" }, { "code": null, "e": 10347, "s": 10203, "text": "First, we transform longer format data into wider format i.e. create 3,548 columns (total number of meal/centre time-series data). For example:" }, { "code": null, "e": 10651, "s": 10347, "text": "# make each combo ts as column wide_dt <- .x %>% transmute(week_date, id = paste0(\"x_\", center_id, \"_\", meal_id), num_orders) %>% pivot_wider(names_from = id, values_from = num_orders, values_fill = 0) %>% arrange(week_date) %>% # arrange by week date select(-week_date) %>% data.frame()" }, { "code": null, "e": 10701, "s": 10651, "text": "Then apply idclass to the transformed data frame." }, { "code": null, "e": 10765, "s": 10701, "text": "ts_cate_obj <- idclass(wide_dt, type = \"SBC\", outplot = \"none\")" }, { "code": null, "e": 10921, "s": 10765, "text": "ts_cate_obj shown above is a matrix. We will now change this matrix format to thedata.frame and then apply cutoff values to categorize the demand patterns." }, { "code": null, "e": 11582, "s": 10921, "text": "ts_categorization <- data.frame(id = row.names(t(wide_dt)), cv2 = ts_cate_obj$cv2, p = ts_cate_obj$p) %>% separate(id, into = c(\"x\", \"center_id\", \"meal_id\"), sep = \"_\") %>% select(-x) %>% mutate(demand_cate = case_when(p < 1.32 & cv2 < 0.49 ~ \"Smooth\", p >= 1.32 & cv2 < 0.49 ~ \"Intermittent\", p < 1.32 & cv2 >= 0.49 ~ \"Erratic\", p >= 1.32 & cv2 >= 0.49 ~ \"Lumpy\")) %>% mutate(center_id = as.integer(as.character(center_id)), meal_id = as.integer(as.character(meal_id)))" }, { "code": null, "e": 11642, "s": 11582, "text": "Let’s see the summary of the above analysis in a bar chart." }, { "code": null, "e": 12176, "s": 11642, "text": "The above plot shows that in the data, a majority of time series meal/centre combos fall under Smooth & Erratic. This means that a regular time series model such as ARIMA, ETS etc. would have suited well. Also, advanced models such as Croston & SBA have been fitted in order to tackle the intermittent & lumpy demand pattern. Machine learning / deep learning models can also be fitted by using these demand pattern type as a feature. The Cross-Validation method has been used to fit No Demand (i.e. transactions less than 20) combos." }, { "code": null, "e": 12357, "s": 12176, "text": "In the following parts, we will do feature engineering, fit time series models, machine learning models, deep learning models and compare their accuracies to find a suitable model." }, { "code": null, "e": 12601, "s": 12357, "text": "Kourentzes, N., 2014. Intermittent Demand Forecasting Package For R — Nikolaos Kourentzes. Kourentzes.com. Available at: <https://kourentzes.com/forecasting/2014/06/23/intermittent-demand-forecasting-package-for-r/> [Accessed 22 January 2021]." } ]
How to improve the accuracy of a Regression Model | by Shwetha Acharya | Towards Data Science
In this post, we will see how to approach a regression problem and how we can increase the accuracy of a machine learning model by using concepts such as feature transformation, feature engineering, clustering, boosting algorithms, and so on. Data Science is an iterative process and only after repeated experiments can we get the best model/solution for our requirement. Let’s focus on each of the above phases through an example. I have a health insurance dataset(CSV file) with customer information on insurance charges, age, sex, BMI, etc. We have to predict insurance charges based on these parameters in the dataset. This is a regression problem as our target variable — Charges/insurance cost — is numeric. Let’s begin by loading the dataset and exploring the attributes (EDA — Exploratory Data Analysis) #Load csv into a dataframedf=pd.read_csv('insurance_data.csv')df.head(3)#Get the number of rows and columnsprint(f'Dataset size: {df.shape}')(1338,7) Dataset has 1338 records and 6 features. Smoker, sex, and region are categorical variables while age, BMI, and children are numeric. Handling Null/Missing Values Let’s examine the proportion of missing values in the dataset: df.isnull().sum().sort_values(ascending=False)/df.shape[0] Age and BMI have some null values — very few though. We will handle this missing data and then begin our data analysis. Sklearn’s SimpleImputer allows you to replace missing values based on mean/median/most frequent values in the respective columns. In this example, I am using the median to fill null values. #Instantiate SimpleImputer si=SimpleImputer(missing_values = np.nan, strategy="median")si.fit(df[[’age’, 'bmi’]]) #Filling missing data with mediandf[[’age’, 'bmi’]] = si.transform(df[[’age’, 'bmi’]]) Data Visualization Now that our data is clean, we will look at analyzing data through visualizations and maps. A simple seaborn pairplot can give us a lot of insights! sns.pairplot(data=df, diag_kind='kde') What do we see..? Charges and children are skewed.Age shows a positive correlation with Charges.BMI follows a normal distribution! 😎 Charges and children are skewed. Age shows a positive correlation with Charges. BMI follows a normal distribution! 😎 Seaborn’s boxplot and countplot can be used to bring out the impact of categorical variables on charges. Observations based on the above plots: Males and females are almost equal in number and on average median charges of males and females are also the same, but males have a higher range of charges.Insurance charges are relatively higher for smokers.Charges are highest for people with 2–3 childrenCustomers are almost equally distributed across the 4 regions and all of them have almost the same charges.Percentage of female smokers is less than the percentage of male smokers. Males and females are almost equal in number and on average median charges of males and females are also the same, but males have a higher range of charges. Insurance charges are relatively higher for smokers. Charges are highest for people with 2–3 children Customers are almost equally distributed across the 4 regions and all of them have almost the same charges. Percentage of female smokers is less than the percentage of male smokers. Thus, we can conclude that ‘smoker’ has a considerable impact on the insurance charges, while gender has the least impact. Let’s create a heatmap to understand the strength of the correlation between charges and numeric features — age, BMI, and children. sns.heatmap(df[['age', 'bmi', 'children', 'charges']].corr(), cmap='Blues', annot=True)plt.show() We see that age and BMI have an average +ve correlation with charges. We will now go over the steps of model preparation and model development one by one. Feature Encoding Feature Encoding In this step, we convert categorical variables — smoker, sex, and region — to numeric format(0, 1,2, 3, etc.) as most of the algorithms cannot handle non-numeric data. This process is called encoding and there are many ways to do this : LabelEncoding — Represent categorical values as numbers (For example, a feature such as Region with values Italy, India, USA, UK can be represented as 1, 2, 3, 4)OrdinalEncoding — Used for representing rank-based categorical data values as numbers. (For example representing high, medium, low as 1,2,3)One-hot Encoding — Represent categorical data as binary values — 0s,1s only. I prefer to use one-hot encoding over label encoding if there aren’t many unique values in the categorical feature. In here, I have used pandas’ one hot encoding function (get_dummies) on Region and split it into 4 columns — location_NE, location_SE, location_NW, and location_SW. One can also use label encoding for this column, however, one hot encoding gave me a better result. LabelEncoding — Represent categorical values as numbers (For example, a feature such as Region with values Italy, India, USA, UK can be represented as 1, 2, 3, 4) OrdinalEncoding — Used for representing rank-based categorical data values as numbers. (For example representing high, medium, low as 1,2,3) One-hot Encoding — Represent categorical data as binary values — 0s,1s only. I prefer to use one-hot encoding over label encoding if there aren’t many unique values in the categorical feature. In here, I have used pandas’ one hot encoding function (get_dummies) on Region and split it into 4 columns — location_NE, location_SE, location_NW, and location_SW. One can also use label encoding for this column, however, one hot encoding gave me a better result. #One hot encodingregion=pd.get_dummies(df.region, prefix='location')df = pd.concat([df,region],axis=1)df.drop(columns='region', inplace=True)df.sex.replace(to_replace=['male','female'],value=[1,0], inplace=True)df.smoker.replace(to_replace=['yes', 'no'], value=[1,0], inplace=True) 2. Feature Selection and Scaling Next, we will select features that affect ‘charges’ the most. I have selected all the features except gender as its effect on ‘charges’ is very less(concluded from the viz charts above). These features will form our ‘X’ variable while charges will be our ‘y’ variable. If there are many features, I suggest you use scikit-learn’s SelectKBest for feature selection to arrive at the top features. #Feature Selection y=df.charges.valuesX=df[['age', 'bmi', 'smoker', 'children', 'location_northeast', 'location_northwest', 'location_southeast', 'location_southwest']]#Split data into test and trainX_train, X_test, y_train, y_test=train_test_split(X,y, test_size=0.2, random_state=42) Once we have selected our features, we need to ‘standardize’ the numeric ones — age, BMI, children. Standardization process converts data to smaller values in the range 0 to 1 so that all of them lie on the same scale and one doesn’t overpower the other. I have used StandardScaler here. #Scaling numeric features using sklearn StandardScalarnumeric=['age', 'bmi', 'children']sc=StandardScalar()X_train[numeric]=sc.fit_transform(X_train[numeric])X_test[numeric]=sc.transform(X_test[numeric]) Now, we are all set to create our first basic model😀 . We will try Linear Regression and DecisionTrees to predict insurance charges Mean absolute error (MAE) and root-mean-square error (RMSE) are the metrics used to evaluate regression models. You can read more about it here. Our baseline models give a score of more than 76%. Between the 2, DecisionTrees give a better MAE of 2780. Not bad..! Let’s see how can we make our model better. 3A. Feature Engineering We can improve our model score by manipulating some of the features in the dataset. After a couple of trials, I found that the following items improve accuracy: Grouping similar customers into clusters using KMeans.Clubbing northeast and northwest regions into ‘north’ and southeast and southwest into ‘south’ in Region column.Transforming ‘children’ into a categorical feature called ‘more_than_one_child’ which is ‘Yes’ if the number of children is > 1 Grouping similar customers into clusters using KMeans. Clubbing northeast and northwest regions into ‘north’ and southeast and southwest into ‘south’ in Region column. Transforming ‘children’ into a categorical feature called ‘more_than_one_child’ which is ‘Yes’ if the number of children is > 1 from sklearn.cluster import KMeansfeatures=['age', 'bmi', 'smoker', 'children', 'location_northeast', 'location_northwest', 'location_southeast', 'location_southwest']kmeans = KMeans(n_clusters=2)kmeans.fit(df[features])df['cust_type'] = kmeans.predict(df[features])df['location_north']=df.apply(lambda x: get_north(x['location_northeast'], x['location_northwest']), axis=1)df['location_south']=df.apply(lambda x: get_south(x['location_southwest'], x['location_southeast']), axis=1)df['more_than_1_child']=df.children.apply(lambda x:1 if x>1 else 0) 3B. Feature Transformation From our EDA, we know that the distribution of ‘charges’ (Y) is highly skewed and hence we will apply scikit-learn’s target transformer — QuantileTransformer to normalize this behavior. X=df[['age', 'bmi', 'smoker', 'more_than_1_child', 'cust_type', 'location_north', 'location_south']]#Split test and train dataX_train, X_test, y_train, y_test=train_test_split(X,y, test_size=0.2, random_state=42)model = DecisionTreeRegressor()regr_trans = TransformedTargetRegressor(regressor=model, transformer=QuantileTransformer(output_distribution='normal'))regr_trans.fit(X_train, y_train)yhat = regr_trans.predict(X_test)round(r2_score(y_test, yhat), 3), round(mean_absolute_error(y_test, yhat), 2), round(np.sqrt(mean_squared_error(y_test, yhat)),2)>>0.843, 2189.28, 4931.96 Woahh... a whopping 84%...and MAE has reduced to 2189! 4. Use of Ensemble and Boosting Algorithms Now we will use these features on ensemble-based RandomForest, GradientBoosting, LightGBM, and XGBoost. If you are a beginner and not aware of boosting and bagging methods, you can read more about them here. X=df[['age', 'bmi', 'smoker', 'more_than_1_child', 'cust_type', 'location_north', 'location_south']]model = RandomForestRegressor()#transforming target variable through quantile transformerttr = TransformedTargetRegressor(regressor=model, transformer=QuantileTransformer(output_distribution='normal'))ttr.fit(X_train, y_train)yhat = ttr.predict(X_test)r2_score(y_test, yhat), mean_absolute_error(y_test, yhat), np.sqrt(mean_squared_error(y_test, yhat))>>0.8802, 2078, 4312 Yes! Our RandomForest model does perform well — MAE of 2078👍. Now, we will try with some boosting algorithms such as Gradient Boosting, LightGBM, and XGBoost. All of them seem to perform well:) 5. Hyperparameter Tuning Let’s tweak some of the algorithm parameters such as tree depth, estimators, learning rate, etc, and check for model accuracy. Manually trying out different combinations of parameter values is very time-consuming. Scikit-learn’s GridSearchCV automates this process and calculates optimized values for these parameters. I have applied GridSearch to the above 3 algorithms. Below is the one for XGBoost: Once we have optimum values for our parameters, we will run all 3 models again with these values. This looks much better! We have been able to improve our accuracy — XGBoost gives a score of 88.6% with relatively fewer errors 👏👏 Distribution and Residual plots confirm that there is a good overlap between predicted and actual charges. However, there are a handful of predicted values that are way beyond the x-axis and this makes our RMSE is higher. This can be reduced by increasing our data points i.e. collecting more data. We are now ready to deploy this model into production and test it on unknown data. Well done👍 In a nutshell, the points that improved the accuracy of my model Creating simple new featuresTransforming target variableClustering common data pointsUse of boosting algorithmsHyperparameter tuning Creating simple new features Transforming target variable Clustering common data points Use of boosting algorithms Hyperparameter tuning You can access my notebook here. Not all of them may work for your model every time. Pick and choose the ones that work best for your scenario:)
[ { "code": null, "e": 415, "s": 172, "text": "In this post, we will see how to approach a regression problem and how we can increase the accuracy of a machine learning model by using concepts such as feature transformation, feature engineering, clustering, boosting algorithms, and so on." }, { "code": null, "e": 544, "s": 415, "text": "Data Science is an iterative process and only after repeated experiments can we get the best model/solution for our requirement." }, { "code": null, "e": 886, "s": 544, "text": "Let’s focus on each of the above phases through an example. I have a health insurance dataset(CSV file) with customer information on insurance charges, age, sex, BMI, etc. We have to predict insurance charges based on these parameters in the dataset. This is a regression problem as our target variable — Charges/insurance cost — is numeric." }, { "code": null, "e": 984, "s": 886, "text": "Let’s begin by loading the dataset and exploring the attributes (EDA — Exploratory Data Analysis)" }, { "code": null, "e": 1134, "s": 984, "text": "#Load csv into a dataframedf=pd.read_csv('insurance_data.csv')df.head(3)#Get the number of rows and columnsprint(f'Dataset size: {df.shape}')(1338,7)" }, { "code": null, "e": 1267, "s": 1134, "text": "Dataset has 1338 records and 6 features. Smoker, sex, and region are categorical variables while age, BMI, and children are numeric." }, { "code": null, "e": 1296, "s": 1267, "text": "Handling Null/Missing Values" }, { "code": null, "e": 1359, "s": 1296, "text": "Let’s examine the proportion of missing values in the dataset:" }, { "code": null, "e": 1418, "s": 1359, "text": "df.isnull().sum().sort_values(ascending=False)/df.shape[0]" }, { "code": null, "e": 1728, "s": 1418, "text": "Age and BMI have some null values — very few though. We will handle this missing data and then begin our data analysis. Sklearn’s SimpleImputer allows you to replace missing values based on mean/median/most frequent values in the respective columns. In this example, I am using the median to fill null values." }, { "code": null, "e": 1930, "s": 1728, "text": "#Instantiate SimpleImputer si=SimpleImputer(missing_values = np.nan, strategy=\"median\")si.fit(df[[’age’, 'bmi’]]) #Filling missing data with mediandf[[’age’, 'bmi’]] = si.transform(df[[’age’, 'bmi’]])" }, { "code": null, "e": 1949, "s": 1930, "text": "Data Visualization" }, { "code": null, "e": 2098, "s": 1949, "text": "Now that our data is clean, we will look at analyzing data through visualizations and maps. A simple seaborn pairplot can give us a lot of insights!" }, { "code": null, "e": 2137, "s": 2098, "text": "sns.pairplot(data=df, diag_kind='kde')" }, { "code": null, "e": 2155, "s": 2137, "text": "What do we see..?" }, { "code": null, "e": 2270, "s": 2155, "text": "Charges and children are skewed.Age shows a positive correlation with Charges.BMI follows a normal distribution! 😎" }, { "code": null, "e": 2303, "s": 2270, "text": "Charges and children are skewed." }, { "code": null, "e": 2350, "s": 2303, "text": "Age shows a positive correlation with Charges." }, { "code": null, "e": 2387, "s": 2350, "text": "BMI follows a normal distribution! 😎" }, { "code": null, "e": 2492, "s": 2387, "text": "Seaborn’s boxplot and countplot can be used to bring out the impact of categorical variables on charges." }, { "code": null, "e": 2531, "s": 2492, "text": "Observations based on the above plots:" }, { "code": null, "e": 2968, "s": 2531, "text": "Males and females are almost equal in number and on average median charges of males and females are also the same, but males have a higher range of charges.Insurance charges are relatively higher for smokers.Charges are highest for people with 2–3 childrenCustomers are almost equally distributed across the 4 regions and all of them have almost the same charges.Percentage of female smokers is less than the percentage of male smokers." }, { "code": null, "e": 3125, "s": 2968, "text": "Males and females are almost equal in number and on average median charges of males and females are also the same, but males have a higher range of charges." }, { "code": null, "e": 3178, "s": 3125, "text": "Insurance charges are relatively higher for smokers." }, { "code": null, "e": 3227, "s": 3178, "text": "Charges are highest for people with 2–3 children" }, { "code": null, "e": 3335, "s": 3227, "text": "Customers are almost equally distributed across the 4 regions and all of them have almost the same charges." }, { "code": null, "e": 3409, "s": 3335, "text": "Percentage of female smokers is less than the percentage of male smokers." }, { "code": null, "e": 3532, "s": 3409, "text": "Thus, we can conclude that ‘smoker’ has a considerable impact on the insurance charges, while gender has the least impact." }, { "code": null, "e": 3664, "s": 3532, "text": "Let’s create a heatmap to understand the strength of the correlation between charges and numeric features — age, BMI, and children." }, { "code": null, "e": 3762, "s": 3664, "text": "sns.heatmap(df[['age', 'bmi', 'children', 'charges']].corr(), cmap='Blues', annot=True)plt.show()" }, { "code": null, "e": 3832, "s": 3762, "text": "We see that age and BMI have an average +ve correlation with charges." }, { "code": null, "e": 3917, "s": 3832, "text": "We will now go over the steps of model preparation and model development one by one." }, { "code": null, "e": 3934, "s": 3917, "text": "Feature Encoding" }, { "code": null, "e": 3951, "s": 3934, "text": "Feature Encoding" }, { "code": null, "e": 4188, "s": 3951, "text": "In this step, we convert categorical variables — smoker, sex, and region — to numeric format(0, 1,2, 3, etc.) as most of the algorithms cannot handle non-numeric data. This process is called encoding and there are many ways to do this :" }, { "code": null, "e": 4948, "s": 4188, "text": "LabelEncoding — Represent categorical values as numbers (For example, a feature such as Region with values Italy, India, USA, UK can be represented as 1, 2, 3, 4)OrdinalEncoding — Used for representing rank-based categorical data values as numbers. (For example representing high, medium, low as 1,2,3)One-hot Encoding — Represent categorical data as binary values — 0s,1s only. I prefer to use one-hot encoding over label encoding if there aren’t many unique values in the categorical feature. In here, I have used pandas’ one hot encoding function (get_dummies) on Region and split it into 4 columns — location_NE, location_SE, location_NW, and location_SW. One can also use label encoding for this column, however, one hot encoding gave me a better result." }, { "code": null, "e": 5111, "s": 4948, "text": "LabelEncoding — Represent categorical values as numbers (For example, a feature such as Region with values Italy, India, USA, UK can be represented as 1, 2, 3, 4)" }, { "code": null, "e": 5252, "s": 5111, "text": "OrdinalEncoding — Used for representing rank-based categorical data values as numbers. (For example representing high, medium, low as 1,2,3)" }, { "code": null, "e": 5710, "s": 5252, "text": "One-hot Encoding — Represent categorical data as binary values — 0s,1s only. I prefer to use one-hot encoding over label encoding if there aren’t many unique values in the categorical feature. In here, I have used pandas’ one hot encoding function (get_dummies) on Region and split it into 4 columns — location_NE, location_SE, location_NW, and location_SW. One can also use label encoding for this column, however, one hot encoding gave me a better result." }, { "code": null, "e": 5992, "s": 5710, "text": "#One hot encodingregion=pd.get_dummies(df.region, prefix='location')df = pd.concat([df,region],axis=1)df.drop(columns='region', inplace=True)df.sex.replace(to_replace=['male','female'],value=[1,0], inplace=True)df.smoker.replace(to_replace=['yes', 'no'], value=[1,0], inplace=True)" }, { "code": null, "e": 6025, "s": 5992, "text": "2. Feature Selection and Scaling" }, { "code": null, "e": 6420, "s": 6025, "text": "Next, we will select features that affect ‘charges’ the most. I have selected all the features except gender as its effect on ‘charges’ is very less(concluded from the viz charts above). These features will form our ‘X’ variable while charges will be our ‘y’ variable. If there are many features, I suggest you use scikit-learn’s SelectKBest for feature selection to arrive at the top features." }, { "code": null, "e": 6706, "s": 6420, "text": "#Feature Selection y=df.charges.valuesX=df[['age', 'bmi', 'smoker', 'children', 'location_northeast', 'location_northwest', 'location_southeast', 'location_southwest']]#Split data into test and trainX_train, X_test, y_train, y_test=train_test_split(X,y, test_size=0.2, random_state=42)" }, { "code": null, "e": 6994, "s": 6706, "text": "Once we have selected our features, we need to ‘standardize’ the numeric ones — age, BMI, children. Standardization process converts data to smaller values in the range 0 to 1 so that all of them lie on the same scale and one doesn’t overpower the other. I have used StandardScaler here." }, { "code": null, "e": 7198, "s": 6994, "text": "#Scaling numeric features using sklearn StandardScalarnumeric=['age', 'bmi', 'children']sc=StandardScalar()X_train[numeric]=sc.fit_transform(X_train[numeric])X_test[numeric]=sc.transform(X_test[numeric])" }, { "code": null, "e": 7330, "s": 7198, "text": "Now, we are all set to create our first basic model😀 . We will try Linear Regression and DecisionTrees to predict insurance charges" }, { "code": null, "e": 7593, "s": 7330, "text": "Mean absolute error (MAE) and root-mean-square error (RMSE) are the metrics used to evaluate regression models. You can read more about it here. Our baseline models give a score of more than 76%. Between the 2, DecisionTrees give a better MAE of 2780. Not bad..!" }, { "code": null, "e": 7637, "s": 7593, "text": "Let’s see how can we make our model better." }, { "code": null, "e": 7661, "s": 7637, "text": "3A. Feature Engineering" }, { "code": null, "e": 7822, "s": 7661, "text": "We can improve our model score by manipulating some of the features in the dataset. After a couple of trials, I found that the following items improve accuracy:" }, { "code": null, "e": 8116, "s": 7822, "text": "Grouping similar customers into clusters using KMeans.Clubbing northeast and northwest regions into ‘north’ and southeast and southwest into ‘south’ in Region column.Transforming ‘children’ into a categorical feature called ‘more_than_one_child’ which is ‘Yes’ if the number of children is > 1" }, { "code": null, "e": 8171, "s": 8116, "text": "Grouping similar customers into clusters using KMeans." }, { "code": null, "e": 8284, "s": 8171, "text": "Clubbing northeast and northwest regions into ‘north’ and southeast and southwest into ‘south’ in Region column." }, { "code": null, "e": 8412, "s": 8284, "text": "Transforming ‘children’ into a categorical feature called ‘more_than_one_child’ which is ‘Yes’ if the number of children is > 1" }, { "code": null, "e": 8962, "s": 8412, "text": "from sklearn.cluster import KMeansfeatures=['age', 'bmi', 'smoker', 'children', 'location_northeast', 'location_northwest', 'location_southeast', 'location_southwest']kmeans = KMeans(n_clusters=2)kmeans.fit(df[features])df['cust_type'] = kmeans.predict(df[features])df['location_north']=df.apply(lambda x: get_north(x['location_northeast'], x['location_northwest']), axis=1)df['location_south']=df.apply(lambda x: get_south(x['location_southwest'], x['location_southeast']), axis=1)df['more_than_1_child']=df.children.apply(lambda x:1 if x>1 else 0)" }, { "code": null, "e": 8989, "s": 8962, "text": "3B. Feature Transformation" }, { "code": null, "e": 9175, "s": 8989, "text": "From our EDA, we know that the distribution of ‘charges’ (Y) is highly skewed and hence we will apply scikit-learn’s target transformer — QuantileTransformer to normalize this behavior." }, { "code": null, "e": 9757, "s": 9175, "text": "X=df[['age', 'bmi', 'smoker', 'more_than_1_child', 'cust_type', 'location_north', 'location_south']]#Split test and train dataX_train, X_test, y_train, y_test=train_test_split(X,y, test_size=0.2, random_state=42)model = DecisionTreeRegressor()regr_trans = TransformedTargetRegressor(regressor=model, transformer=QuantileTransformer(output_distribution='normal'))regr_trans.fit(X_train, y_train)yhat = regr_trans.predict(X_test)round(r2_score(y_test, yhat), 3), round(mean_absolute_error(y_test, yhat), 2), round(np.sqrt(mean_squared_error(y_test, yhat)),2)>>0.843, 2189.28, 4931.96" }, { "code": null, "e": 9812, "s": 9757, "text": "Woahh... a whopping 84%...and MAE has reduced to 2189!" }, { "code": null, "e": 9855, "s": 9812, "text": "4. Use of Ensemble and Boosting Algorithms" }, { "code": null, "e": 10063, "s": 9855, "text": "Now we will use these features on ensemble-based RandomForest, GradientBoosting, LightGBM, and XGBoost. If you are a beginner and not aware of boosting and bagging methods, you can read more about them here." }, { "code": null, "e": 10536, "s": 10063, "text": "X=df[['age', 'bmi', 'smoker', 'more_than_1_child', 'cust_type', 'location_north', 'location_south']]model = RandomForestRegressor()#transforming target variable through quantile transformerttr = TransformedTargetRegressor(regressor=model, transformer=QuantileTransformer(output_distribution='normal'))ttr.fit(X_train, y_train)yhat = ttr.predict(X_test)r2_score(y_test, yhat), mean_absolute_error(y_test, yhat), np.sqrt(mean_squared_error(y_test, yhat))>>0.8802, 2078, 4312" }, { "code": null, "e": 10695, "s": 10536, "text": "Yes! Our RandomForest model does perform well — MAE of 2078👍. Now, we will try with some boosting algorithms such as Gradient Boosting, LightGBM, and XGBoost." }, { "code": null, "e": 10730, "s": 10695, "text": "All of them seem to perform well:)" }, { "code": null, "e": 10755, "s": 10730, "text": "5. Hyperparameter Tuning" }, { "code": null, "e": 11157, "s": 10755, "text": "Let’s tweak some of the algorithm parameters such as tree depth, estimators, learning rate, etc, and check for model accuracy. Manually trying out different combinations of parameter values is very time-consuming. Scikit-learn’s GridSearchCV automates this process and calculates optimized values for these parameters. I have applied GridSearch to the above 3 algorithms. Below is the one for XGBoost:" }, { "code": null, "e": 11255, "s": 11157, "text": "Once we have optimum values for our parameters, we will run all 3 models again with these values." }, { "code": null, "e": 11386, "s": 11255, "text": "This looks much better! We have been able to improve our accuracy — XGBoost gives a score of 88.6% with relatively fewer errors 👏👏" }, { "code": null, "e": 11685, "s": 11386, "text": "Distribution and Residual plots confirm that there is a good overlap between predicted and actual charges. However, there are a handful of predicted values that are way beyond the x-axis and this makes our RMSE is higher. This can be reduced by increasing our data points i.e. collecting more data." }, { "code": null, "e": 11779, "s": 11685, "text": "We are now ready to deploy this model into production and test it on unknown data. Well done👍" }, { "code": null, "e": 11844, "s": 11779, "text": "In a nutshell, the points that improved the accuracy of my model" }, { "code": null, "e": 11977, "s": 11844, "text": "Creating simple new featuresTransforming target variableClustering common data pointsUse of boosting algorithmsHyperparameter tuning" }, { "code": null, "e": 12006, "s": 11977, "text": "Creating simple new features" }, { "code": null, "e": 12035, "s": 12006, "text": "Transforming target variable" }, { "code": null, "e": 12065, "s": 12035, "text": "Clustering common data points" }, { "code": null, "e": 12092, "s": 12065, "text": "Use of boosting algorithms" }, { "code": null, "e": 12114, "s": 12092, "text": "Hyperparameter tuning" } ]
What does getattr() function do in Python?
The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function. The syntax of getattr() method is − getattr(object, name[, default]) The getattr() method can take multiple parameters − The getattr() method returns − value of the named attribute of the given object default, if no named attribute is found AttributeError exception, if named attribute is not found and default is not defined class Male: age = 21 name = "Abel" x = Male() print('The age is:', getattr(x, "age")) print('The age is:', x.age) This gives the output ('The age is:', 21) ('The age is:', 21)
[ { "code": null, "e": 1207, "s": 1062, "text": "The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function." }, { "code": null, "e": 1243, "s": 1207, "text": "The syntax of getattr() method is −" }, { "code": null, "e": 1276, "s": 1243, "text": "getattr(object, name[, default])" }, { "code": null, "e": 1328, "s": 1276, "text": "The getattr() method can take multiple parameters −" }, { "code": null, "e": 1359, "s": 1328, "text": "The getattr() method returns −" }, { "code": null, "e": 1408, "s": 1359, "text": "value of the named attribute of the given object" }, { "code": null, "e": 1448, "s": 1408, "text": "default, if no named attribute is found" }, { "code": null, "e": 1533, "s": 1448, "text": "AttributeError exception, if named attribute is not found and default is not defined" }, { "code": null, "e": 1655, "s": 1533, "text": "class Male:\n age = 21\n name = \"Abel\"\nx = Male()\nprint('The age is:', getattr(x, \"age\"))\nprint('The age is:', x.age)" }, { "code": null, "e": 1677, "s": 1655, "text": "This gives the output" }, { "code": null, "e": 1719, "s": 1677, "text": "('The age is:', 21)\n('The age is:', 21)\n\n" } ]
Angular Material - Menu
The md-menu, an Angular directive, is a component to display addition options within the context of action performed. md-menu have two child elements. The first element is the trigger element and is used to open the menu. The second element is the md-menu-content which represents the content of the menu when menu is opened. The md-menu-content usually carries the menu items as md-menu-item. The following table lists out the parameters and description of the different attributes of md-menu. * md-position-mode The position mode in the form of x, y. Default value is target,target. Right now the x axis also suppports target-right. * md-offset An offset to apply to the dropdown after positioning x, y. Default value is 0,0. The following example shows the use of md-menu directive and also the uses of menus. am_menus.htm <html lang = "en"> <head> <link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <script language = "javascript"> angular .module('firstApplication', ['ngMaterial']) .controller('menuController', menuController); function menuController ($scope, $mdDialog) { var originatorEv; this.openMenu = function($mdOpenMenu, ev) { originatorEv = ev; $mdOpenMenu(ev); }; this.menuItemClick = function(index) { $mdDialog.show ( $mdDialog.alert() .title('TutorialsPoint.com') .textContent('Menu Item clicked, index: ' + index) .ok('OK') .targetEvent(originatorEv) ); originatorEv = null; }; } </script> </head> <body ng-app = "firstApplication"> <div id = "menuContainer" ng-controller = "menuController as ctrl" layout = "row" ng-cloak> <div layout = "column" flex = "33" flex-sm = "100" layout-align = "center center"> <p>Default Menu</p> <md-menu> <md-button aria-label = "Sample Menu" class = "md-icon-button" ng-click = "$mdOpenMenu($event)"> <md-icon md-menu-origin class = "material-icons">more_vert</md-icon> </md-button> <md-menu-content width = "6"> <md-menu-item ng-repeat = "item in [1, 2, 3]"> <md-button ng-click = "ctrl.menuItemClick($index)"> <div layout = "row"> <md-icon md-menu-align-target class = "material-icons"> add</md-icon> <p flex>Option {{item}}</p> </div> </md-button> </md-menu-item> </md-menu-content> </md-menu> </div> <div layout = "column" flex-sm = "100" flex = "33" layout-align = "center center"> <p>Left Aligned Menu</p> <md-menu md-position-mode = "target-right target" > <md-button aria-label = "Sample Menu" class = "md-icon-button" ng-click = "$mdOpenMenu($event)"> <md-icon md-menu-origin class = "material-icons">more_vert</md-icon> </md-button> <md-menu-content width = "4" > <md-menu-item ng-repeat = "item in [1, 2, 3]"> <md-button ng-click = "ctrl.menuItemClick($index)"> <div layout = "row"> <p flex>Option {{item}}</p> <md-icon md-menu-align-target class = "material-icons"> add</md-icon> </div> </md-button> </md-menu-item> </md-menu-content> </md-menu> </div> </div> </body> </html> Verify the result. Default Menu Option {{item}} Left Aligned Menu Option {{item}} 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2584, "s": 2190, "text": "The md-menu, an Angular directive, is a component to display addition options within the context of action performed. md-menu have two child elements. The first element is the trigger element and is used to open the menu. The second element is the md-menu-content which represents the content of the menu when menu is opened. The md-menu-content usually carries the menu items as md-menu-item." }, { "code": null, "e": 2685, "s": 2584, "text": "The following table lists out the parameters and description of the different attributes of md-menu." }, { "code": null, "e": 2704, "s": 2685, "text": "* md-position-mode" }, { "code": null, "e": 2825, "s": 2704, "text": "The position mode in the form of x, y. Default value is target,target. Right now the x axis also suppports target-right." }, { "code": null, "e": 2837, "s": 2825, "text": "* md-offset" }, { "code": null, "e": 2918, "s": 2837, "text": "An offset to apply to the dropdown after positioning x, y. Default value is 0,0." }, { "code": null, "e": 3003, "s": 2918, "text": "The following example shows the use of md-menu directive and also the uses of menus." }, { "code": null, "e": 3016, "s": 3003, "text": "am_menus.htm" }, { "code": null, "e": 7093, "s": 3016, "text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('menuController', menuController);\n\n function menuController ($scope, $mdDialog) {\n var originatorEv;\n \n this.openMenu = function($mdOpenMenu, ev) {\n originatorEv = ev;\n $mdOpenMenu(ev);\n };\n \n this.menuItemClick = function(index) {\n $mdDialog.show (\n $mdDialog.alert()\n .title('TutorialsPoint.com')\n .textContent('Menu Item clicked, index: ' + index)\n .ok('OK')\n .targetEvent(originatorEv)\n );\n originatorEv = null;\n };\n } \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"menuContainer\" ng-controller = \"menuController as ctrl\"\n layout = \"row\" ng-cloak>\n <div layout = \"column\" flex = \"33\" flex-sm = \"100\"\n layout-align = \"center center\"> \n <p>Default Menu</p>\n \n <md-menu>\n <md-button aria-label = \"Sample Menu\" class = \"md-icon-button\"\n ng-click = \"$mdOpenMenu($event)\">\n <md-icon md-menu-origin class = \"material-icons\">more_vert</md-icon>\n </md-button>\n \n <md-menu-content width = \"6\">\n <md-menu-item ng-repeat = \"item in [1, 2, 3]\">\n <md-button ng-click = \"ctrl.menuItemClick($index)\">\n \n <div layout = \"row\">\n <md-icon md-menu-align-target class = \"material-icons\">\n add</md-icon>\n <p flex>Option {{item}}</p>\n </div>\n \n </md-button>\n </md-menu-item>\n </md-menu-content>\n \n </md-menu>\n </div>\n \n <div layout = \"column\" flex-sm = \"100\" flex = \"33\" layout-align = \"center center\">\n <p>Left Aligned Menu</p>\n <md-menu md-position-mode = \"target-right target\" >\n \n <md-button aria-label = \"Sample Menu\" class = \"md-icon-button\"\n ng-click = \"$mdOpenMenu($event)\">\n <md-icon md-menu-origin class = \"material-icons\">more_vert</md-icon>\n </md-button>\n \n <md-menu-content width = \"4\" >\n <md-menu-item ng-repeat = \"item in [1, 2, 3]\">\n <md-button ng-click = \"ctrl.menuItemClick($index)\">\n \n <div layout = \"row\">\n <p flex>Option {{item}}</p> \n <md-icon md-menu-align-target class = \"material-icons\">\n add</md-icon>\t\t\t\t\t\n </div>\n \n </md-button>\n </md-menu-item>\n </md-menu-content>\n </md-menu>\n </div>\n\n </div>\n </body>\n</html>" }, { "code": null, "e": 7112, "s": 7093, "text": "Verify the result." }, { "code": null, "e": 7125, "s": 7112, "text": "Default Menu" }, { "code": null, "e": 7141, "s": 7125, "text": "Option {{item}}" }, { "code": null, "e": 7159, "s": 7141, "text": "Left Aligned Menu" }, { "code": null, "e": 7175, "s": 7159, "text": "Option {{item}}" }, { "code": null, "e": 7210, "s": 7175, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7224, "s": 7210, "text": " Anadi Sharma" }, { "code": null, "e": 7259, "s": 7224, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7273, "s": 7259, "text": " Anadi Sharma" }, { "code": null, "e": 7308, "s": 7273, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7328, "s": 7308, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 7363, "s": 7328, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7380, "s": 7363, "text": " Frahaan Hussain" }, { "code": null, "e": 7413, "s": 7380, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 7425, "s": 7413, "text": " Senol Atac" }, { "code": null, "e": 7460, "s": 7425, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7472, "s": 7460, "text": " Senol Atac" }, { "code": null, "e": 7479, "s": 7472, "text": " Print" }, { "code": null, "e": 7490, "s": 7479, "text": " Add Notes" } ]
Python | Removing strings from tuple - GeeksforGeeks
17 Apr, 2019 Sometimes we can come across the issue in which we receive data in form of tuple and we just want the numbers from it and wish to erase all the strings from them. This has a useful utility in Web-Development and Machine Learning as well. Let’s discuss certain ways in which this particular task can be achieved. Method #1 : Using list comprehension + type() The combination of above 2 functions can be used to solve this particular problem. The list comprehension does the task of reconstruction of the modified list and type function helps us to filter the strings. # Python3 code to demonstrate# Remove string from tuples# using list comprehension + type() # initializing listtest_list = [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + type()# Remove string from tuplesres = [tuple([j for j in i if type(j) != str]) for i in test_list] # print resultprint("The list after string removal is : " + str(res)) The original list : [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')] The list after string removal is : [(1, 2), (4, ), (45, )] Method #2 : Using list comprehension + isinstance() This is almost a similar method to perform this particular task but the change here is just to use the isinstance function to check for the string data type, and rest of the formulations remains mostly similar. # Python3 code to demonstrate# Remove string from tuples# using list comprehension + isinstance() # initializing listtest_list = [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + isinstance()# Remove string from tuplesres = [tuple(j for j in i if not isinstance(j, str)) for i in test_list] # print resultprint("The list after string removal is : " + str(res)) The original list : [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')] The list after string removal is : [(1, 2), (4, ), (45, )] Python list-programs Python tuple-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? How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python 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": 24390, "s": 24362, "text": "\n17 Apr, 2019" }, { "code": null, "e": 24702, "s": 24390, "text": "Sometimes we can come across the issue in which we receive data in form of tuple and we just want the numbers from it and wish to erase all the strings from them. This has a useful utility in Web-Development and Machine Learning as well. Let’s discuss certain ways in which this particular task can be achieved." }, { "code": null, "e": 24748, "s": 24702, "text": "Method #1 : Using list comprehension + type()" }, { "code": null, "e": 24957, "s": 24748, "text": "The combination of above 2 functions can be used to solve this particular problem. The list comprehension does the task of reconstruction of the modified list and type function helps us to filter the strings." }, { "code": "# Python3 code to demonstrate# Remove string from tuples# using list comprehension + type() # initializing listtest_list = [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + type()# Remove string from tuplesres = [tuple([j for j in i if type(j) != str]) for i in test_list] # print resultprint(\"The list after string removal is : \" + str(res))", "e": 25433, "s": 24957, "text": null }, { "code": null, "e": 25566, "s": 25433, "text": "The original list : [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')]\nThe list after string removal is : [(1, 2), (4, ), (45, )]\n" }, { "code": null, "e": 25620, "s": 25568, "text": "Method #2 : Using list comprehension + isinstance()" }, { "code": null, "e": 25831, "s": 25620, "text": "This is almost a similar method to perform this particular task but the change here is just to use the isinstance function to check for the string data type, and rest of the formulations remains mostly similar." }, { "code": "# Python3 code to demonstrate# Remove string from tuples# using list comprehension + isinstance() # initializing listtest_list = [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + isinstance()# Remove string from tuplesres = [tuple(j for j in i if not isinstance(j, str)) for i in test_list] # print resultprint(\"The list after string removal is : \" + str(res))", "e": 26331, "s": 25831, "text": null }, { "code": null, "e": 26464, "s": 26331, "text": "The original list : [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')]\nThe list after string removal is : [(1, 2), (4, ), (45, )]\n" }, { "code": null, "e": 26485, "s": 26464, "text": "Python list-programs" }, { "code": null, "e": 26507, "s": 26485, "text": "Python tuple-programs" }, { "code": null, "e": 26514, "s": 26507, "text": "Python" }, { "code": null, "e": 26530, "s": 26514, "text": "Python Programs" }, { "code": null, "e": 26628, "s": 26530, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26660, "s": 26628, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26702, "s": 26660, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26744, "s": 26702, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26800, "s": 26744, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26822, "s": 26800, "text": "Defaultdict in Python" }, { "code": null, "e": 26844, "s": 26822, "text": "Defaultdict in Python" }, { "code": null, "e": 26883, "s": 26844, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26929, "s": 26883, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26967, "s": 26929, "text": "Python | Convert a list to dictionary" } ]
Longest Palindrome in a String | Practice | GeeksforGeeks
Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of conflict, return the substring which occurs first ( with the least starting index). Example 1: Input: S = "aaaabbaa" Output: aabbaa Explanation: The longest Palindromic substring is "aabbaa". Example 2: Input: S = "abc" Output: a Explanation: "a", "b" and "c" are the longest palindromes with same length. The result is the one with the least starting index. Your Task: You don't need to read input or print anything. Your task is to complete the function longestPalin() which takes the string S as input and returns the longest palindromic substring of S. Expected Time Complexity: O(|S|2). Expected Auxiliary Space: O(1). Constraints: 1 ≤ |S| ≤ 103 0 jainmuskan5655 days ago public: vector<vector<int>> dp; bool isPalindrome(string &s, int i,int j){ if(dp[i][j]!= -1) return dp[i][j]; else if(i<j){ if(s[i]!= s[j]) return dp[i][j]= false; return dp[i][j]= isPalindrome(s,i+1,j-1); } // hidden case if i==j return dp[i][j]=true; } string longestPalin (string s) { int size=0, start=0; int n= s.size(); string ans=""; dp.resize(n,vector<int>(n,-1)); int maxsize=-1; for(int i=0;i<n;i++){ for(int j=i+size;j<n;j++){ if(isPalindrome(s,i,j)){ size= j-i; start= i; if(maxsize<size){ ans=s.substr(start, size+1); maxsize=size; } } } } return ans; }}; 0 dattatraygujar776 days ago int n=s.length(); boolean dp[][]=new boolean[n][n]; String ans=""; for(int g=0;g<n;g++) { for(int i=0,j=g;j<n;i++,j++) { if(g==0) { dp[i][j]=true; } else if(g==1) { if(s.charAt(i)==s.charAt(j)){ dp[i][j]=true; } else { dp[i][j]=false; } } else { if(s.charAt(i)==s.charAt(j) && dp[i+1][j-1]){ dp[i][j]=true; } } if(dp[i][j] && s.substring(i,j+1).length()>ans.length()) { ans=s.substring(i,j+1); } } } return ans; +1 vishalsavade1 week ago //0.01 time Easy method string longestPalin (string str) { // code here string res = ""; int maxlength = 1, start = 0, len = 0; for(int i = 0; i < str.length(); i++){ int low = i-1; int high = i+1; while(high < str.length() && str[i] == str[high]) high++; while(low >= 0 && str[i] == str[low]) low--; while(low >= 0 && high < str.length() && str[low] == str[high]){ low--; high++; } len = high-low-1; if(len > maxlength){ maxlength = len; start = low+1; } } for(int i = start; i <= start+maxlength-1; i++) res+=str[i]; return res; } -2 wishsharma0119991 week ago java 0 kaustubhdwivedi17292 weeks ago DP is ❤ string longestPalin (string s) { int n = s.size(); vector<vector<int> > dp(n, vector<int>(n, 0)); for(int i = 0; i < n; i++) dp[i][i] = 1; for(int i = 0; i < n-1; i++) if(s[i] == s[i+1]) dp[i][i+1] = 2; for(int k = 2; k < n; k++) for(int i = 0; i < n-k; i++) if(s[i] == s[i+k] and dp[i+1][i+k-1] != 0) dp[i][i+k] = dp[i+1][i+k-1] + 2; int maxLen = 0; string ans = ""; for(int i = 0; i < n; i++) for(int j = i; j < n; j++) if(dp[i][j] > maxLen){ maxLen = dp[i][j]; ans = s.substr(i, maxLen); } return ans; } 0 kartikkeyankant2 weeks ago C++ EASY TO UNDERSTAND , USING ODD EVEN APPROACH string longestPalin (string S) { // code here int s=S.size(); int ans=0; string answer=""; for(int i=0;i<s;i++){ int x=i,y=i+1; while(x>=0 && y<s && S[x]==S[y]){ if(ans<y-x+1){ ans=y-x+1; answer=S.substr(x,y-x+1); } x--; y++; } x=i,y=i; while(x>=0 && y<s && S[x]==S[y]){ if(ans<y-x+1){ ans=y-x+1; answer=S.substr(x,y-x+1); } x--; y++; } } return answer; } +1 aloksinghbais023 weeks ago C++ solution having time complexity as O(|S|^2) and space complexity as O(|S|^2) is as follows :- Execution Time :- 0.06 / 1.12 sec string longestPalin (string S) { int n = S.length(); bool dp[n][n]; int st = 0; int maxLen = 1; for(int gap = 0; gap < n; gap++){ for(int i = 0, j = gap; j < n; i++,j++){ if(gap == 0){ dp[i][j] = true; } else if(gap == 1){ if(S[i] == S[j]){ int currLen = gap + 1; if(currLen > maxLen){ st = i; maxLen = currLen; } dp[i][j] = true; } else dp[i][j] = false; } else{ if(S[i] == S[j]){ if(dp[i+1][j-1]){ int currLen = gap + 1; if(currLen > maxLen){ st = i; maxLen = currLen; } dp[i][j] = true; } else dp[i][j] = false; } else dp[i][j] = false; } } } return S.substr(st,maxLen); } 0 sunboykenneth3 weeks ago O(n) solution with Manacher algorithm: class Solution { private: string preProcessString (const string& S) { string newS = "@"; for (int i = 0; i < S.length(); i++) { newS += S[i]; newS += "@"; } return newS; } vector<int> calculateRadiusArray (const string &str) { int n = str.length(); if (n == 0) { return {}; } vector<int> radiusArr = vector<int>(n, 0); int curRightMostRadius = 0, curRightMostRadiusCenter = 0; for (int i = 1; i < n; i++) { int rightMostEnd = curRightMostRadiusCenter + curRightMostRadius; int existingPalinRadius = 0; if (i < rightMostEnd) { int mirroredPos = 2 * curRightMostRadiusCenter - i; existingPalinRadius = radiusArr[mirroredPos]; if (existingPalinRadius > rightMostEnd - i) { existingPalinRadius = rightMostEnd - i; } } else { existingPalinRadius = 0; } int left = i - existingPalinRadius - 1, right = i + existingPalinRadius + 1; while (left >= 0 && right < n && str[left] == str[right]) { left--; right++; existingPalinRadius++; } radiusArr[i] = existingPalinRadius; if (existingPalinRadius > curRightMostRadius) { curRightMostRadius = existingPalinRadius; curRightMostRadiusCenter = i; } } return radiusArr; } public: string longestPalin (string S) { int n = S.length(); if (n < 2) { return S; } string processedString = preProcessString(S); vector<int> radiusArr = calculateRadiusArray(processedString); int maxRadiusCenter = 0, maxRadius = 0; for (int i = 0; i < radiusArr.size(); i++) { if (radiusArr[i] > maxRadius) { maxRadius = radiusArr[i]; maxRadiusCenter = i; } } int palinStrLen = maxRadius, palinStrStartIndex = (maxRadiusCenter - maxRadius) / 2; return S.substr(palinStrStartIndex, palinStrLen); } }; +1 radhesh1853 weeks ago CPP : bool is_palindrome(string s) { string rev = s; reverse(rev.begin(), rev.end()); return s == rev; } // returns true if there is a palindrome of length x int good(int x, string s) { int n = s.length(); for(int L = 0; L + x <= n; L++) { if(is_palindrome(s.substr(L, x))) { return L; } } return -1; } void printSubStr(string str, int low, int high) { for (int i = low; i <= high; ++i) cout << str[i]; } string longestPalin (string s) { // code here int best_len = 0; string best_s = ""; int n = s.length(); for(int parity : {0, 1}) { int low = 1, high = n; if(low % 2 != parity) low++; if(high % 2 != parity) high--; while(low <= high) { int mid = (low + high) / 2; if(mid % 2 != parity) { mid++; } if(mid > high) { break; } int tmp = good(mid, s); if(tmp != -1) { if(mid > best_len) { best_len = mid; best_s = s.substr(tmp, mid); } low = mid + 2; } else { high = mid - 2; } } } return best_s; } +2 technologychamp3103 weeks ago int n = S.size(); int maxlength = 1 , start = 0; int low , high; for(int i = 0; i < n; i++) { int low = i-1; int high = i+1; while(high < n && S[i] == S[high]) high++; while(low >= 0 && S[i] == S[low]) low--; while(high < n && low >= 0 && S[low] == S[high]) { high++; low--; } int length = high - low -1; if(maxlength < length) { maxlength = length; start = low + 1; } } return S.substr(start , maxlength); 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": 571, "s": 238, "text": "Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of conflict, return the substring which occurs first ( with the least starting index)." }, { "code": null, "e": 583, "s": 571, "text": "\nExample 1:" }, { "code": null, "e": 681, "s": 583, "text": "Input:\nS = \"aaaabbaa\"\nOutput: aabbaa\nExplanation: The longest Palindromic\nsubstring is \"aabbaa\".\n" }, { "code": null, "e": 692, "s": 681, "text": "Example 2:" }, { "code": null, "e": 851, "s": 692, "text": "Input: \nS = \"abc\"\nOutput: a\nExplanation: \"a\", \"b\" and \"c\" are the \nlongest palindromes with same length.\nThe result is the one with the least\nstarting index.\n" }, { "code": null, "e": 1050, "s": 851, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function longestPalin() which takes the string S as input and returns the longest palindromic substring of S." }, { "code": null, "e": 1118, "s": 1050, "text": "\nExpected Time Complexity: O(|S|2).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1146, "s": 1118, "text": "\nConstraints:\n1 ≤ |S| ≤ 103" }, { "code": null, "e": 1148, "s": 1146, "text": "0" }, { "code": null, "e": 1172, "s": 1148, "text": "jainmuskan5655 days ago" }, { "code": null, "e": 1995, "s": 1172, "text": " public: vector<vector<int>> dp; bool isPalindrome(string &s, int i,int j){ if(dp[i][j]!= -1) return dp[i][j]; else if(i<j){ if(s[i]!= s[j]) return dp[i][j]= false; return dp[i][j]= isPalindrome(s,i+1,j-1); } // hidden case if i==j return dp[i][j]=true; } string longestPalin (string s) { int size=0, start=0; int n= s.size(); string ans=\"\"; dp.resize(n,vector<int>(n,-1)); int maxsize=-1; for(int i=0;i<n;i++){ for(int j=i+size;j<n;j++){ if(isPalindrome(s,i,j)){ size= j-i; start= i; if(maxsize<size){ ans=s.substr(start, size+1); maxsize=size; } } } } return ans; }};" }, { "code": null, "e": 1997, "s": 1995, "text": "0" }, { "code": null, "e": 2024, "s": 1997, "text": "dattatraygujar776 days ago" }, { "code": null, "e": 2956, "s": 2024, "text": " int n=s.length();\n boolean dp[][]=new boolean[n][n];\n String ans=\"\";\n for(int g=0;g<n;g++)\n {\n for(int i=0,j=g;j<n;i++,j++)\n {\n if(g==0)\n {\n dp[i][j]=true;\n }\n else if(g==1)\n {\n if(s.charAt(i)==s.charAt(j)){\n dp[i][j]=true;\n }\n else\n {\n dp[i][j]=false;\n }\n }\n else\n {\n if(s.charAt(i)==s.charAt(j) && dp[i+1][j-1]){\n dp[i][j]=true;\n } \n }\n if(dp[i][j] && s.substring(i,j+1).length()>ans.length())\n {\n ans=s.substring(i,j+1);\n }\n \n }\n }\n return ans;" }, { "code": null, "e": 2959, "s": 2956, "text": "+1" }, { "code": null, "e": 2982, "s": 2959, "text": "vishalsavade1 week ago" }, { "code": null, "e": 3854, "s": 2982, "text": "//0.01 time Easy method \nstring longestPalin (string str) {\n // code here\n string res = \"\";\n int maxlength = 1, start = 0, len = 0;\n for(int i = 0; i < str.length(); i++){\n int low = i-1;\n int high = i+1;\n \n while(high < str.length() && str[i] == str[high])\n high++;\n while(low >= 0 && str[i] == str[low])\n low--;\n \n while(low >= 0 && high < str.length() && str[low] == str[high]){\n low--;\n high++;\n }\n \n len = high-low-1;\n if(len > maxlength){\n maxlength = len;\n start = low+1;\n }\n }\n \n for(int i = start; i <= start+maxlength-1; i++)\n res+=str[i];\n \n return res;\n }" }, { "code": null, "e": 3857, "s": 3854, "text": "-2" }, { "code": null, "e": 3884, "s": 3857, "text": "wishsharma0119991 week ago" }, { "code": null, "e": 3889, "s": 3884, "text": "java" }, { "code": null, "e": 3893, "s": 3891, "text": "0" }, { "code": null, "e": 3924, "s": 3893, "text": "kaustubhdwivedi17292 weeks ago" }, { "code": null, "e": 3932, "s": 3924, "text": "DP is ❤" }, { "code": null, "e": 4788, "s": 3932, "text": "string longestPalin (string s) {\n \n int n = s.size();\n \n vector<vector<int> > dp(n, vector<int>(n, 0));\n \n for(int i = 0; i < n; i++)\n dp[i][i] = 1;\n \n for(int i = 0; i < n-1; i++)\n if(s[i] == s[i+1])\n dp[i][i+1] = 2;\n \n \n for(int k = 2; k < n; k++)\n for(int i = 0; i < n-k; i++)\n if(s[i] == s[i+k] and dp[i+1][i+k-1] != 0)\n dp[i][i+k] = dp[i+1][i+k-1] + 2;\n \n \n int maxLen = 0;\n string ans = \"\";\n \n for(int i = 0; i < n; i++)\n for(int j = i; j < n; j++)\n if(dp[i][j] > maxLen){\n maxLen = dp[i][j];\n ans = s.substr(i, maxLen);\n }\n \n return ans;\n \n }" }, { "code": null, "e": 4790, "s": 4788, "text": "0" }, { "code": null, "e": 4817, "s": 4790, "text": "kartikkeyankant2 weeks ago" }, { "code": null, "e": 4866, "s": 4817, "text": "C++ EASY TO UNDERSTAND , USING ODD EVEN APPROACH" }, { "code": null, "e": 5671, "s": 4866, "text": " string longestPalin (string S) {\n // code here\n int s=S.size();\n int ans=0;\n string answer=\"\";\n for(int i=0;i<s;i++){\n int x=i,y=i+1;\n while(x>=0 && y<s && S[x]==S[y]){\n if(ans<y-x+1){\n ans=y-x+1;\n answer=S.substr(x,y-x+1);\n }\n x--;\n y++;\n }\n \n\n x=i,y=i;\n while(x>=0 && y<s && S[x]==S[y]){\n if(ans<y-x+1){\n ans=y-x+1;\n answer=S.substr(x,y-x+1);\n }\n x--;\n y++;\n }\n }\n \n \n return answer;\n }" }, { "code": null, "e": 5674, "s": 5671, "text": "+1" }, { "code": null, "e": 5701, "s": 5674, "text": "aloksinghbais023 weeks ago" }, { "code": null, "e": 5800, "s": 5701, "text": "C++ solution having time complexity as O(|S|^2) and space complexity as O(|S|^2) is as follows :- " }, { "code": null, "e": 5836, "s": 5802, "text": "Execution Time :- 0.06 / 1.12 sec" }, { "code": null, "e": 7065, "s": 5838, "text": "string longestPalin (string S) { int n = S.length(); bool dp[n][n]; int st = 0; int maxLen = 1; for(int gap = 0; gap < n; gap++){ for(int i = 0, j = gap; j < n; i++,j++){ if(gap == 0){ dp[i][j] = true; } else if(gap == 1){ if(S[i] == S[j]){ int currLen = gap + 1; if(currLen > maxLen){ st = i; maxLen = currLen; } dp[i][j] = true; } else dp[i][j] = false; } else{ if(S[i] == S[j]){ if(dp[i+1][j-1]){ int currLen = gap + 1; if(currLen > maxLen){ st = i; maxLen = currLen; } dp[i][j] = true; } else dp[i][j] = false; } else dp[i][j] = false; } } } return S.substr(st,maxLen); }" }, { "code": null, "e": 7067, "s": 7065, "text": "0" }, { "code": null, "e": 7092, "s": 7067, "text": "sunboykenneth3 weeks ago" }, { "code": null, "e": 7131, "s": 7092, "text": "O(n) solution with Manacher algorithm:" }, { "code": null, "e": 9463, "s": 7133, "text": "class Solution {\n private:\n string preProcessString (const string& S) {\n string newS = \"@\";\n for (int i = 0; i < S.length(); i++) {\n newS += S[i];\n newS += \"@\";\n }\n return newS;\n }\n \n vector<int> calculateRadiusArray (const string &str) {\n int n = str.length();\n if (n == 0) {\n return {};\n }\n \n vector<int> radiusArr = vector<int>(n, 0);\n int curRightMostRadius = 0, curRightMostRadiusCenter = 0;\n for (int i = 1; i < n; i++) {\n int rightMostEnd = curRightMostRadiusCenter + curRightMostRadius;\n\n int existingPalinRadius = 0;\n if (i < rightMostEnd) {\n int mirroredPos = 2 * curRightMostRadiusCenter - i;\n existingPalinRadius = radiusArr[mirroredPos];\n if (existingPalinRadius > rightMostEnd - i) {\n existingPalinRadius = rightMostEnd - i;\n }\n } else {\n existingPalinRadius = 0;\n }\n \n int left = i - existingPalinRadius - 1, right = i + existingPalinRadius + 1;\n while (left >= 0 && right < n && str[left] == str[right]) {\n left--;\n right++;\n existingPalinRadius++;\n }\n \n radiusArr[i] = existingPalinRadius;\n \n if (existingPalinRadius > curRightMostRadius) {\n curRightMostRadius = existingPalinRadius;\n curRightMostRadiusCenter = i;\n }\n }\n \n return radiusArr;\n }\n \n \n public:\n string longestPalin (string S) {\n int n = S.length();\n if (n < 2) {\n return S;\n }\n \n string processedString = preProcessString(S);\n vector<int> radiusArr = calculateRadiusArray(processedString);\n \n int maxRadiusCenter = 0, maxRadius = 0;\n for (int i = 0; i < radiusArr.size(); i++) {\n if (radiusArr[i] > maxRadius) {\n maxRadius = radiusArr[i];\n maxRadiusCenter = i;\n }\n }\n \n int palinStrLen = maxRadius, palinStrStartIndex = (maxRadiusCenter - maxRadius) / 2;\n return S.substr(palinStrStartIndex, palinStrLen);\n }\n};" }, { "code": null, "e": 9466, "s": 9463, "text": "+1" }, { "code": null, "e": 9488, "s": 9466, "text": "radhesh1853 weeks ago" }, { "code": null, "e": 9494, "s": 9488, "text": "CPP :" }, { "code": null, "e": 10919, "s": 9494, "text": " bool is_palindrome(string s) {\n string rev = s;\n reverse(rev.begin(), rev.end());\n return s == rev;\n}\n// returns true if there is a palindrome of length x\nint good(int x, string s) {\n int n = s.length();\n for(int L = 0; L + x <= n; L++) {\n if(is_palindrome(s.substr(L, x))) {\n return L;\n }\n }\n return -1;\n}\n void printSubStr(string str, int low, int high)\n{\n for (int i = low; i <= high; ++i)\n cout << str[i];\n}\n string longestPalin (string s) {\n // code here\n int best_len = 0;\n string best_s = \"\";\n int n = s.length();\n for(int parity : {0, 1}) {\n int low = 1, high = n;\n if(low % 2 != parity) low++;\n if(high % 2 != parity) high--;\n while(low <= high) {\n int mid = (low + high) / 2;\n if(mid % 2 != parity) {\n mid++;\n }\n if(mid > high) {\n break;\n }\n int tmp = good(mid, s);\n if(tmp != -1) {\n if(mid > best_len) {\n best_len = mid;\n best_s = s.substr(tmp, mid);\n }\n low = mid + 2;\n }\n else {\n high = mid - 2;\n }\n }\n }\n return best_s;\n \n }" }, { "code": null, "e": 10922, "s": 10919, "text": "+2" }, { "code": null, "e": 10952, "s": 10922, "text": "technologychamp3103 weeks ago" }, { "code": null, "e": 11699, "s": 10952, "text": "\n int n = S.size();\n int maxlength = 1 , start = 0;\n int low , high;\n \n for(int i = 0; i < n; i++)\n {\n int low = i-1;\n int high = i+1;\n \n while(high < n && S[i] == S[high])\n high++;\n \n while(low >= 0 && S[i] == S[low])\n low--;\n \n while(high < n && low >= 0 && S[low] == S[high])\n {\n high++;\n low--;\n }\n \n int length = high - low -1;\n if(maxlength < length)\n {\n maxlength = length;\n start = low + 1;\n }\n }\n return S.substr(start , maxlength);" }, { "code": null, "e": 11845, "s": 11699, "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": 11881, "s": 11845, "text": " Login to access your submissions. " }, { "code": null, "e": 11891, "s": 11881, "text": "\nProblem\n" }, { "code": null, "e": 11901, "s": 11891, "text": "\nContest\n" }, { "code": null, "e": 11964, "s": 11901, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 12112, "s": 11964, "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": 12320, "s": 12112, "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": 12426, "s": 12320, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Tryit Editor v3.7
Tryit: Display the nabla symbol
[]
How to use Jupyter to conduct preliminary data analysis for health sciences: R/tidyverse edition | by Arindam Basu | Towards Data Science
In this tutorial, I will write about a workflow you can use with Jupyter notebooks/Jupyter labs to do data analysis. I will discuss the Setting up a web-based Jupyter environment to get your work done, and also How you can use R to work with Jupyter notebooks or Jupyter lab Here is how a Jupyter notebook looks like: Jupyter notebooks (and Jupyter lab) are “notebooks” that live on a web browser and has components where you can do data science-y stuff, statistical data analysis, write notes, papers, generate graphs all in the space of one page. Read more about Jupyter notebooks from their website here: https://jupyter.org/ On their website, you can learn: how to download Jupyter notebooks (free and open source, so free as in free beer and free as in freedom), how to install them on your specific operating system. You even get to test Jupyter notebooks on tryjupyter.org. How easy can it get? I’d recommend that after you have installed Jupyter Notebooks (or Jupyter Lab), or have accessed a hosted instance of Jupyter notebook or Jupyter lab, make sure you read the following two tutorials written in “Towards Data Science”: Bringing the best out of Jupyter notebooks for data science Jupyter lab: evolution of Jupyter Notebook You will develop a working knowledge of how to work with Jupyter notebooks, and how to use them. In this tutorial, I will show you how you can use Jupyter Notebooks/Jupyter Lab to conduct real world data analysis starting from scratch using R (tidyverse). I will write about using R (tidyverse and ggplot) to do data analysis. In a future post, I will show you how you can use Python (pandas, matplotlib, statsmodel, and seaborn) to conduct data analysis and create graphics. As these are open-source and free (free as in free beer and free as in free speech) tools. (click on the image below to listen an interview with Richard Stallman what that means, :-) ): So learning how to use these tools for your data analysis and writing will make it easy and intuitive for you to do and share your data analysis projects with everyone. A working knowledge of R A web browser and a computer that has Jupyter notebook or Jupyter Lab installed. However, if you do not have to install Jupyter notebook/Jupyter Lab on your computer to follow along. You can create free accounts on one of these websites to follow along as well. Practically any browser will work. If any browser does not work with these, please let me know in the comments. How to write in markdown If you have not used R before, now is a good time. R is a statistical programming environment (this means you can not only conduct statistical data analysis but you can also develop “routines” or procedures that you can share with others using R, which is a good thing). You can find out more about R from the following website (what is R, how to obtain and install R): R home page: https://www.r-project.org/ Download R from the following site: https://cran.r-project.org/ A series of pages to learn how you can adopt R in your work: https://cran.r-project.org/web/views/ In this tutorial, I will make use of “tidyverse” a suite of packages in R you can use for data science; here is the link: https://www.tidyverse.org/ I recommend that you make yourself familiar with the following online text written by Hadley Wickham and Garrett Grolmund for doing data science in R. It is free and easy to follow along: https://r4ds.had.co.nz/ These are the basic resources to get you started. Here, I will introduce some essential key components of R that you can use to follow along. In this tutorial, we will use R and tidyverse to read a data set, “clean and preprocess” the data set, and then find some meaning in the data set. We will create simple graphics using a package within R referred to as “ggplot2” (Grammar of Graphics Plotting Version 2, based on the book by Leland and Wilkinson, “Grammar of Graphics”). Let’s get started. We will use a jupyter lab instance for free hosted in Cocalc.com (URL: https://cocalc.com); if you want to use this and follow along, consider to create a free account there and start a jupyter lab server. When you visit cocalc.com, it looks as follows: After you sign-in and bring up a Jupyter lab environment, it should look like as follows: I will not get into the details of the Jupyterlab interface here as this has already been well documented in the link I shared above, please read the associated document, it’s really well written. Instead, let’s focus on the most interesting tasks on hand: The file extension is ‘.ipynb’: “interactive ipython notebook” We will need to set up a filename instead of “untitled.ipynb”, let’s call it ‘first_analysis.ipynb’. You can right-click on the filename in the second, large white panel and change the filename. Then we need to grab some data and write codes and text to get to work. But before we did so, we need to touch two more points: Let’s learn a little about R as such and tidyverse and tidy data, andlet’s cover a little about markdown syntax to write your text Let’s learn a little about R as such and tidyverse and tidy data, and let’s cover a little about markdown syntax to write your text I have provided some annotated codes in the following “greyed out” box that you can copy and paste in a code block in Jupyterlab and when you are ready to run, press “Shift+Enter” # Comments in R code blocks are written using 'hash' marks, and # you should use detailed comments on all your codesx <- 1 # '<- ' is an assignment operator. Here x is set to the value of 1# This is same as x = 1x == 1# Here, we evaluate whether x is equal to 1; # Everything in R is an object and you can find out about objects# using the function typeof()typeof(x) # should put 'double'# double tells you that x is a number as in 1.00# you can and should write functions to accomplish repetitive # tasks in R# The syntax of function is:my_function = function(x){ function statements }# You can call functions anywhere in R using the function name and # by writing the function parameters within parentheses# as in my_function(x)# An example of a function where two numbers x, and y are # multipliedmultiply_fn = function(x, y){ z = x * y return(z)}multiply_fn(2,3) # will produce 6# You can see that a function can call within itself another # function# Combination of data and functions are referred to as packages# You can call packages using library() function# You can install packages using install.packages() function# You can find help in R using help("topic") function# In our case we will use "tidyverse" package. # We will need to install this first if not already installed So at the end of this little exercise, after we have called the library “tidyverse”, this is how it looks like: As html is the lingua franca of the world wide web, it is also quite complex. So, John Gruber devised this language called markdown where you can write all basic elements of the text using simple decorations to your texts. You can write headings (I usually use two levels of headings), links, and insert codes. You will also be able to use tables and citation marks in the flavour of markdown that is used for jupyter notebooks, so you can pretty much write your entire paper or thesis here. In the box below I have provided a version of a short text written in markdown and the rendered version thereafter. This should get you going writing in jupyter notebooks as well, hopefully. This is what we have written in the text box in Jupyter notebook # PurposeThis above was a first level header where we put one hash mark before the header. If we wanted to put a second level header, we would add another hash mark. Here, for example the goal is to demonstrate the principles of writing in markdown and conducting data analyses entirely on a web browser after installing jupyter notebook and optionally jupyter lab on the computer or the server.## What we will do?We will do the following:- We will learn a little about R and markdown- We will go grab some data sets- After loading the data set in Jupyter, we will clean the data set- We will run some tables and visualisations## So is it possible to add tables?Yes, to add tables, do something like:| Task | Software ||------|----------|| Data analysis | Any statistical programme will do || Data analysis plus writing | An integrated solution will work || Examples of integrations | Rstudio, Jupyter, stata |## How do we add links?If you wanted to add links to say sometihng like Google, you would insert the following code: [Name the URL should point, say Google](http://www.google.com), and it would put an underlined URL or name to your text.## Where can I learn more about markdown and its various "flavours"?Try the following links:- [Markdown](https://daringfireball.net/projects/markdown/)- [Github flavoured markdown](https://github.github.com/gfm/)- [Academic markdown](http://scholarlymarkdown.com/) And this is how it looks like (partial, you can replicate it in a Jupyter lab or Jupyter Notebook) Now that we have: Learned a little about R and installed and loaded up tidyverse Learned how to write in markdown so that we can describe our results It’s time to grab some data off the web and do some analyses using these tools. Now, where will you get data? Data are everywhere, but some sites make it easier than others for you to grab and work with them. How to obtain data can be another post by itself, so I will not go into the details, but generally: You can search for data (we will use two such sites: Figshare and Google Data Explorer) You can use application programming interfaces (APIs) to get data off websites and play with them. Several sites set up toy data or real world data for you to play with (e.g., data and stories library) Government sites and health departments provide “truckloads” of data for you to analyse and make sense The key here is to learn how to make sense of that data. This is where data science comes into the picture. Specifically, you can: Download data for free Shape it up in ways that will make sense for you to understand their patterns and make them “tidy data” Run visualisations using available tools Preprocess data using different software (we will use R and tidyverse in this tutorial, but you can use Python, or other specialised tools such as OpenRefine, and spreadsheets) For the purpose of this exercise, let’s visit Figshare and search data for our work. Let’s say we are interested to identify data on health issues in workplaces and see what data we get off Figshare to get our work done. As this is a demo exercise, we will keep our data set small so that we can learn the most essential points about grabbing data off the web and analysing them. It’s actually quite intuitive to do that using tidyverse. When I log in to Figshare, this is how my dashboard looks like: We searched the data based with “work” and “health” and identified a raw data set from a study where the researchers studied the relationship between behavioural activation and depression and quality of life. When we searched, we made sure that we wanted to download only those data that were freely and openly shared (with a CC-0 licence), and we wanted data sets. The data were taken from the following publication: journals.plos.org In describing the study, the authors of the paper wrote in the abstract: Quality of life (QOL) is an important health-related concept. Identifying factors that affect QOL can help develop and improve health-promotion interventions. Previous studies suggest that behavioral activation fosters subjective QOL, including well-being. However, the mechanism by which behavioral activation improves QOL is not clear. Considering that QOL improves when depressive symptoms improve post-treatment and that behavioral activation is an effective treatment for depression, it is possible that behavioral activation affects QOL indirectly rather than directly. To clarify the mechanism of the influence of behavioral activation on QOL, it is necessary to examine the relationships between factors related to behavioral activation, depressive symptoms, and QOL. Therefore, we attempted to examine the relationship between these factors. Participants comprised 221 Japanese undergraduate students who completed questionnaires on behavioral activation, QOL, and depressive symptoms: the Japanese versions of the Behavioral Activation for Depression Scale-Short Form (BADS-SF), WHO Quality of Life-BREF (WHOQOL-26), and Center for Epidemiologic Studies Depression Scale (CES-D). The BADS-SF comprises two subscales, Activation and Avoidance, and the WHOQOL-26 measures overall QOL and four domains, Physical Health, Psychological Health, Social Relationships, and Environment. Mediation analyses were conducted with BADS-SF activation and avoidance as independent variables, CES-D as a mediator variable, and each WHO-QOL as an outcome variable. Results indicated that depression completely mediated the relationship between Avoidance and QOL, and partially mediated the relationship between Activation and QOL. In addition, analyses of each domain of QOL showed that Activation positively affected all aspects of QOL directly and indirectly, but Avoidance had a negative influence on only part of QOL mainly through depression. The present study provides behavioral activation strategies aimed at QOL enhancement. The full paper is in open source and you can download and read the paper from the following website: journals.plos.org You can directly download the data from here: https://ndownloader.figshare.com/files/9446491 Here’s how the data appear: Here, we will use the data set and will run an annotated jupyter notebook to show the different steps of: Obtaining the data Reading the data into R Cleaning the data set Asking questions Answering the questions If you want, you can reproduce their paper on the data set the authors provided but we will not do that in this tutorial. In this tutorial, we have already so far introduced the fact that using a web based tool, you can use Jupyter notebooks/Jupyter labs to conduct data analyses. I have introduced Cocalc, but there are other similar tools as well. Some examples: Microsoft Azure Notebooks a range of languages available all for free and you can use an R or a Python or other languages; for free, and you can sign up and start working right away Google Colaboratory: From Google, and free. You can work on Python notebooks Tryjupyter: Gives you for free notebooks in different languages and in different set ups. So, we can start and end our analyses in any of these as these notebooks are interoperable. You can also host notebooks on github and in binder and share your notebooks with the rest of the world. Step 1: Download the dataYou can see that this is an Excel spreadsheet file. You can either open it in a spreadsheet programme (such as Excel or in OpenOffice Calc), and export the file as a comma separated value file. Alternatively, we can read the file directly in Jupyter. We will do this here. In order to do this, we will need to use the package “readxl”. So we do as follows: # first load the packagelibrary(readxl)# If you find that your Jupyter instance does not have "readxl" # package in itself, then you will need to install it. # Easiest, install.packages("readxl") and then do # library(readxl) After loading, this is how it looks like: Well, nothing happened! Why? Because read_excel function read the contents of the excel file “S1_Dataset.xlsx” and stored it in an object named as mydata. We will now use this object mydata to examine what is inside this. Step 2: Wrangle the data and preprocess Now that we have read the data set, let’s delve into finding out what’s in there. A first thing is to find out the header information. We can do that in R using ```head()``` function. So here is how it looks: We also want to find out the list of variables in the data set, So we do: names(mydata) # produces the list of variables'Sex' 'Age' 'BADS-SF' 'BADS-SF_Activation' 'BADS-SF_Avoidance' 'CES-D' 'WHOQOL-26_Mean total score' 'WHOQOL-26_Phisical health' 'WHOQOL-26_Psychological health' 'WHOQOL-26_Social relationships' 'WHOQOL-26_Environment' 'WHOQOL-26_Overall QOL' As you can see that while this dataset contains 12 variables with “expressive” names. Some variables have names that contain “spaces” in it. We will rename these variables so that these are meaningful for us. Variables such as “Sex”, and “Age” are relatively straightforward to understand, but we may need to rename the other variables. You will find more information about these variable names from the main paper and the accompanying data description in Figshare. The following table maps the variable names with the concepts they stand for and a short description: | Variable Name | What it stands for ||---------------|--------------------|| Sex | 1 = Male, 2 = Female || Age | Age in years || BADS-SF | Behavioral Activation for Depression Scale-Short Form || BADS-SF_Activation | BADS for activation || BADS-SF_Avoidance | BADS for avoidance || CES-D | Center for Epidemiologic Studies Depression Scale || WHOQOL-26_Mean total score | Japanese version of the WHO Quality of Life-BREF mean total score || WHOQOL-26_Phisical health | WHOQol-26 physical health || WHOQOL-26_Psychological health | WHOQoL-26 psychological health || WHOQOL-26_Social relationships | WHOQoL-26 social relationships || WHOQOL-26_Environment | WHOQoL-26 Environment || WHOQOL-26_Overall QOL | WHOQoL-26 Overall | QoL in these variables are short forms of Quality of Life. You can learn more about WHO QoL from the relevant website here: https://www.who.int/substance_abuse/research_tools/whoqolbref/en/ We will not cover the details here as we are soldiering on to the next step. At this stage, you can see that: The variable names are kind of long so you may want to shorten them but keep them understandable as you keep working Many variables have spaces in their names so they need to be taken care of (we suggest that you use underscore to represent spaces) This is what we do: Several things to note: We will store the renamed variables in a new data set (otherwise our changes will not persist beyond what we have done in the code and immediately executed, so make sure to save it in a different named object)We use a symbol ‘%>%’; this symbol is referred to as ‘pipe’ and it read as “and then”. Here we chain a number of different operations or commands together using this. If you want to learn more about this and how to use it, please refer to Hadley Wickham’s excellent book on data science with R, where he writes, We will store the renamed variables in a new data set (otherwise our changes will not persist beyond what we have done in the code and immediately executed, so make sure to save it in a different named object) We use a symbol ‘%>%’; this symbol is referred to as ‘pipe’ and it read as “and then”. Here we chain a number of different operations or commands together using this. If you want to learn more about this and how to use it, please refer to Hadley Wickham’s excellent book on data science with R, where he writes, Behind the scenes, x %>% f(y) turns into f(x, y), and x %>% f(y) %>% g(z) turns into g(f(x, y), z) and so on. You can use the pipe to rewrite multiple operations in a way that you can read left-to-right, top-to-bottom. We’ll use piping frequently from now on because it considerably improves the readability of code Then we used the “rename()” function and in there, we did as follows: The “new variable name” was the FIRST element, followed by An “equal sign”, and the “old variable name” was the SECOND element, indicating that We store the old variable values in the new variable Note that at the end of this, once we executed it, we got a new data set with all values intact but with new variable names. If you do not want to transform the names of some variables, keep them as such (as we did for “Age” and “Sex”) The first thing we do when we get a brand new data set to play with is to “wrangle” the data. We examine the variables, we plot them, we recode them to suit our purpose, we ask questions and we try to answer them. Then, once we have discovered some patterns that we see we can delve in, we start modelling the data in various ways. In this tutorial, I will confine myself to writing about the first part, how do we do simple tables and graphs. Again, if you are working with R and tidyverse (which I recommend), your main text is Hadley Wickham’s book: R for Data Science. The book is available for free; you can work with free software on the web to learn and practice, so please give it a try. As you have seen, you can get data for free as well from different sites. I will not repeat in details everything in that book, but will point to five grammars that you will find helpful in working with data: Select. — Use this to select columns from the data set. Let’s say we want to work with only BADS and CES D variables for this population, we will have to select the columns we want to work with: Filter. — If we wanted to work with certain “individuals” in the data set, we would filter the rows based on some criteria we set on the columns. Say, we want to work with women (“Sex == 2”) and teenagers (“Age < 20”), see what we do: Note the simplicity: We use “==” equivalence operator to set the filtering conditions We separate different conditions using a “,” (comma) Arrange. — If we want to get a view of the data set by ascending or descending order, we use the verb “arrange()” to do so, as in: As you can see, the youngest person in the dataset is aged 2 years! You need to go back and correct or test if this was indeed the value. This is where data cleaning and preprocessing becomes important. What sense do we make of this? Mutate. — You want to create new variables and store them in the data set. You want to create these variables out of existing variables using other functions. Say, now that we know that a person’s age was inserted as 2 years and possibly a mistake, we do not want to lose that person’s information and we wanted to cut the age variable in 4 groups, what do we do? We use mutate verb, like so: So you see: Use mutate to recode one variable to another Use mutate to create new variables Mutate uses new functions Let’s count the age_rec variable and see what we get: As you see, if you let the computer to decide, it can create categories that we cannot much use. So, let’s recode and mutate a new age group and say save it to a new data set, here: Did you see what we did? We created a new data set (mydata4) and in there we created a new variable binarised age (“age_bin”), where we had teenagers and respondents who were 20 years and older (actually it should be ≥ 20) You can also assign labels of your choice (so we could put “Teenagers” and “Twenty plus” if we wanted. Mutate is a powerful verb that lets you recreate data sets and code variables. You should master this. Summarize and group_by. — Selecting, filtering, arranging the data set and mutating or changing the variables may sound like a lot of useful things to do, but you will also need to peek deeper into the data and learn how to find meaning from it. You will need to find aggregated summaries, and average values for those variables that are continuous, and tabulate those that are categorical. In this way, you can gain insights into the data. Let me introduce you to “summarise()” and “group_by()” functions. Let’s say you are interested to find out the average age of the respondents of this survey and then wanted to see if the males were on average older than the females. How would you do it? See: # What is the average age of the respondents?average_age = mydata4 %>% summarise(average_age = mean(Age, na.rm = T))average_age# Will return 19.36652 See that this is a single number that consolidates the entire data set for all individuals. That is fine, and you can get a whole list of such averages for the continuous variables you post. However, if we were to split the data set into different discrete groups (such as binarised age groups, or Sex for that matter), and then calculate the averages of the other variables, it would make for an interesting display to identify patterns. So, basically, after splitting the data set, we would apply some functions, in our case say mean, and then we combine the results back to present, that’d make for interesting display of results that are also meaningful. For a comprehensive introduction to this topic, read the following article (download it as PDF): So, let’s put this into action and see if: Are Males older than females in our data? Do Teenagers have lower average scores on health related quality of life (Mean WHOQoL)? So, what are your take away lessons? We first passed the data set, then We asked tidyverse to group by the categorical variable (first do this, because this is your “split”ting the data), and then We asked for summarising the variable we wanted. Gathering and spreading. — Let’s put some of these concepts into action and try to answer the question, how do quality of life scores differ between males and females for different age groups? Let’s find out the average scores first: This is fine, but this is quite complex to interpret. We have to first look at the first row and then find the scores for individual quality of life parameters for the male gender (Sex equals 1) and then read the next row and so on. It’d help us if we were to have one variable that would say be “quality_of_life” that would list qol, physical, psych, soc, env etc and we would read them down. That is, we would have to gather these various scores and put them under one variable, say “quality_of_life”, and we would put all the scores we see there under another variable next to it, we can call that variable as “all_means” (as these are essentially mean values). In tidyverse, we now introduce another verb called “gather” that would do exactly that: Use a “key” where you would gather the names of the variables that you want to group together. Here, for instance, “quality of life” Use a “value” where you would put their respective values. What names you give key and value is up to you. Give them meaningful names is all I care. So, here is the code for you to examine: See what’s happening? We have now “gathered” for all age groups and all sexes their quality of life scores (various parameters). But this is still quite complex as there is repetition for Sex and repetition for age groups. If we’d like to spread it out so that now we would have the values of “all_means” score spread out under the keys of Sex (1 and 2), we could have see them quite intuitively. Here’s the code again: So, now you can see you can read across each age group (grouped under each age group), each of the scores and can compare between males and females. This way you can make some interesting comparisons. One area where “spread” becomes particularly useful is when you crosstabulate variables, as in when you cross tabulate binarised age and Sex for instance in this data set. First, take a look at what happens when you run crosstab = mydata4 %>% count(age_bin, Sex) # crosstabs binarised age and Sex Fine, but we want a proper cross-tabulation where Sex appears on the column and binarised age in the rows. So, we use “spread” to achieve this, see Much better. Now you can see how binarised age groups are spread across the genders 1 and 2 (remember that 1 = male, 2 = female). Also, note that this is a data frame, which means you can use mutate() to add a column to find out the row wise percentages of teenagers in each gender. How can you do that? As you can see males are higher in the teenage groups, and lower (26%) in the 20 plus age groups. So, when you assess relationship between some of the scores and gender, keep in mind that age distribution can work as a confounding variable. In the first two steps, how to obtain data from a variety of sources (for free) and how to use freely available software such as Jupyter to write and work on the data to make it suitable for analyses. But preparing tables and summaries and cleaning the data is half the fun. Being able to create simple graphs to dive deeper into the data is satisfying. So in this third and final step today, we will learn how to create simple graphs in tidyverse. I suggest you use the “ggplot()” to create graphs. Ggplot() is a vast topic and there are books available on the web for you to read. Read the following resources to get started: Tidyverse ggplot docs R graphics Cookbook The data visualisation section of R for data science In addition to the above sites, I’d recommend you read the following paper to gain an insight into graph construction (principles at least), irrespective whether you use tidyverse or not: In order to plot graphs to visualise data, we will use ggplot() function in this tutorial and we will follow the general scheme: ggplot([data]) + geom_[geometry](mappings = aes(x = [variable], y = [variable], stats = "<choices>") + facet_<wrap | grid>() + coord_<choices>() + labs("title of the plot) + xlab("label for x axis") + ylab("label for y axis") For a complete understanding of how ggplot() works, please follow the links I have listed above. Here, as we are introducing and getting our feet “wet”, I will only cover the basics. Remember some rules: The function is ggplot(), and data is mandatory (this is why I have placed it in square brackets) Then there is a “+” sign, and the + sign must ALWAYS be at the end of a line, NEVER at the start The plus sign indicates a “layer”, from the “layered grammar of graphics” You must always specify the aesthetics (“aes”) values, otherwise the graph will not build Rest of the options are kind of optional (I say “kind of”, because you will learn as you go on using this) Let’s start with mydata4 and see how it appears now: Let’s graphically explore: What does the age distribution look like? What does it look like for males and females? What is the relationship between bads_sf and whoqol_mean? Is it similar for males and females? We can go on exploring, but answering these questions graphically will provide you with ideas that you can use for exploring your own questions in this data set and for future data sets that you may want to work with. What does the age distribution look like? First, study the code: mydata4 %>% ggplot() + geom_bar(aes(x = Age)) + ggtitle("A bar plot of age") + xlab("Age in years") + ylab("Counts") + ggsave("age_bar.png") mydata4 was the data set that contained all the variables we wanted to plot the pipe symbol sent the information about mydata4 to ggplot() function Then we started a new layer and added layers with + symbol We ask for a bar plot as the age was mostly numbers and hence represented with bars. We only had to specify an X axis and ggplot would figure out the raw counts. We titled the graph with ggtitle() and inserted the title in quote marks We labelled x and y axes using xlab(), and ylab() functions We saved the figure using ggsave() function This is how it looks like: Does the bar plot of age distribution look same for males and females? Now we should use the facet function to plot two different plots, or we can split the graph: First, see the code: mydata4 %>% ggplot() + geom_bar(aes(x = Age)) + facet_wrap(~Sex) + ggtitle("A bar plot of age by gender") + xlab("Age in years") + ylab("Counts") + ggsave("age_bar_sex.png") Note that we added to wrap the figure into two parts by adding the Sex variable so that it splits the Figure into two parts as in the figure below. What do you think? Does it look similar for males and females? This time, we are going to explore the association or relationship between two variables. What graph we will draw will depend on the nature of the variables we want to work with. The following table will provide you with some ideas: | X variable | Y variable | Type of graph | Geometry ||------------|------------|---------------|------------------|| Continuous | Continuous | Scatterplot | geom_point() || Continuous | Categorical| Boxplot | geom_boxplot() | | Categorical| Continuous | Boxplot | geom_boxplot() || Categorical| None | Barplot | geom_bar() || Continuous | None | Histogram | geom_histogram() | Because both bads_sf and whoqol_mean are continuous, we can draw a scatterplot. But what is going to explain what else? If we think that there may be a relationship between between whoqol_mean such that if bads_sf scores increase, so will whoqol_mean, we can test this using a scatterplot and draw linear regressions to plot their relationships (linear regression or modelling is beyond the scope for this tutorial, but we will only show the graph and not write more about it here). Here’s the code: mydata4 %>% ggplot() + geom_point(aes(x = bads_sf, y = whoqol_mean)) + ggtitle("Association between bads_sf and whoqol") + xlab("BADS-SF score") + ylab("WHOQoL Score") + ggsave("bads_who.png") Here’s the graph of association: Now we need to qualify it further and see if the association is similar for males and females. So, we add a regression line, and colour the points and the lines differently for males and females: Here’s the code first: mydata4 %>% mutate(gender = as.factor(Sex)) %>% ggplot() + geom_point(aes(x = bads_sf, y = whoqol_mean, colour = gender)) + geom_smooth(aes(x = bads_sf, y = whoqol_mean, colour = gender), method = "lm") + ggtitle("Association between bads_sf and whoqol") + xlab("BADS-SF score") + ylab("WHOQoL Score") + ggsave("bads_who_lm.png") Then the figure: So, what’s going on? We had to add a new variable, “gender”, from “Sex” so used the mutate function to convert it to a factor variable rather than a character variable it was. A factor variable is a categorical variable but explicitly has levels that are arranged according to alphabetical or numerical order. This was necessary for the subsequent steps where we wanted to test what would be the differences in the relationships. We wanted to test how the points would differ so, we coloured them differently using the gender variable. Note that we have placed the colour argument within the aesthetics of the mapping. Similarly, we wanted to use a smoothing function, and in our case, this was “linear model”, hence “lm” as a method of choice. But this has to be posted outside of the aesthetics parameters. Within the aesthetics of the smoothing lines, we would need to indicate that we want different coloured lines pertaining to the levels of the gender variable. So, what do you think you see in the relationship? Does it vary much between genders? We could go on exploring the data set more but we will need to stop here and take stock of what we have done so far. So this was a tutorial where we covered the following topics: Jupyter notebooks are free and open source tools that enable you to conduct data science-y work but also allow you to take full advantage of the potential of R and Python (and other languages) to conduct data analyses. You can conduct secondary data analyses and tidy data without practically using any other tools (such as spreadsheets) to clean and wrangle data. We identified a data set on the web that used CC-0 licence (creative commons licence where the data sets could be used to work on freely) and an accompanying article to investigate a data set. We learned how to use the tidyverse environment to examine, subset, filter, and graph data. I hope that this will get you inspired to work on more data sets. Remember that the more you practice, the better your skills will be. If you need more information and have questions, please post them in the comments section. I wanted it to be a quick introduction, so did not introduce some other concepts about tidy data and statistical procedures; this will be discussed in subsequent articles and you will find more information everywhere on the web. Happy analysing! Here is a link to the jupyter notebook for this analysis
[ { "code": null, "e": 307, "s": 171, "text": "In this tutorial, I will write about a workflow you can use with Jupyter notebooks/Jupyter labs to do data analysis. I will discuss the" }, { "code": null, "e": 382, "s": 307, "text": "Setting up a web-based Jupyter environment to get your work done, and also" }, { "code": null, "e": 446, "s": 382, "text": "How you can use R to work with Jupyter notebooks or Jupyter lab" }, { "code": null, "e": 489, "s": 446, "text": "Here is how a Jupyter notebook looks like:" }, { "code": null, "e": 800, "s": 489, "text": "Jupyter notebooks (and Jupyter lab) are “notebooks” that live on a web browser and has components where you can do data science-y stuff, statistical data analysis, write notes, papers, generate graphs all in the space of one page. Read more about Jupyter notebooks from their website here: https://jupyter.org/" }, { "code": null, "e": 833, "s": 800, "text": "On their website, you can learn:" }, { "code": null, "e": 939, "s": 833, "text": "how to download Jupyter notebooks (free and open source, so free as in free beer and free as in freedom)," }, { "code": null, "e": 994, "s": 939, "text": "how to install them on your specific operating system." }, { "code": null, "e": 1052, "s": 994, "text": "You even get to test Jupyter notebooks on tryjupyter.org." }, { "code": null, "e": 1306, "s": 1052, "text": "How easy can it get? I’d recommend that after you have installed Jupyter Notebooks (or Jupyter Lab), or have accessed a hosted instance of Jupyter notebook or Jupyter lab, make sure you read the following two tutorials written in “Towards Data Science”:" }, { "code": null, "e": 1366, "s": 1306, "text": "Bringing the best out of Jupyter notebooks for data science" }, { "code": null, "e": 1409, "s": 1366, "text": "Jupyter lab: evolution of Jupyter Notebook" }, { "code": null, "e": 1506, "s": 1409, "text": "You will develop a working knowledge of how to work with Jupyter notebooks, and how to use them." }, { "code": null, "e": 2071, "s": 1506, "text": "In this tutorial, I will show you how you can use Jupyter Notebooks/Jupyter Lab to conduct real world data analysis starting from scratch using R (tidyverse). I will write about using R (tidyverse and ggplot) to do data analysis. In a future post, I will show you how you can use Python (pandas, matplotlib, statsmodel, and seaborn) to conduct data analysis and create graphics. As these are open-source and free (free as in free beer and free as in free speech) tools. (click on the image below to listen an interview with Richard Stallman what that means, :-) ):" }, { "code": null, "e": 2240, "s": 2071, "text": "So learning how to use these tools for your data analysis and writing will make it easy and intuitive for you to do and share your data analysis projects with everyone." }, { "code": null, "e": 2265, "s": 2240, "text": "A working knowledge of R" }, { "code": null, "e": 2639, "s": 2265, "text": "A web browser and a computer that has Jupyter notebook or Jupyter Lab installed. However, if you do not have to install Jupyter notebook/Jupyter Lab on your computer to follow along. You can create free accounts on one of these websites to follow along as well. Practically any browser will work. If any browser does not work with these, please let me know in the comments." }, { "code": null, "e": 2664, "s": 2639, "text": "How to write in markdown" }, { "code": null, "e": 3034, "s": 2664, "text": "If you have not used R before, now is a good time. R is a statistical programming environment (this means you can not only conduct statistical data analysis but you can also develop “routines” or procedures that you can share with others using R, which is a good thing). You can find out more about R from the following website (what is R, how to obtain and install R):" }, { "code": null, "e": 3074, "s": 3034, "text": "R home page: https://www.r-project.org/" }, { "code": null, "e": 3138, "s": 3074, "text": "Download R from the following site: https://cran.r-project.org/" }, { "code": null, "e": 3237, "s": 3138, "text": "A series of pages to learn how you can adopt R in your work: https://cran.r-project.org/web/views/" }, { "code": null, "e": 3386, "s": 3237, "text": "In this tutorial, I will make use of “tidyverse” a suite of packages in R you can use for data science; here is the link: https://www.tidyverse.org/" }, { "code": null, "e": 3598, "s": 3386, "text": "I recommend that you make yourself familiar with the following online text written by Hadley Wickham and Garrett Grolmund for doing data science in R. It is free and easy to follow along: https://r4ds.had.co.nz/" }, { "code": null, "e": 4076, "s": 3598, "text": "These are the basic resources to get you started. Here, I will introduce some essential key components of R that you can use to follow along. In this tutorial, we will use R and tidyverse to read a data set, “clean and preprocess” the data set, and then find some meaning in the data set. We will create simple graphics using a package within R referred to as “ggplot2” (Grammar of Graphics Plotting Version 2, based on the book by Leland and Wilkinson, “Grammar of Graphics”)." }, { "code": null, "e": 4349, "s": 4076, "text": "Let’s get started. We will use a jupyter lab instance for free hosted in Cocalc.com (URL: https://cocalc.com); if you want to use this and follow along, consider to create a free account there and start a jupyter lab server. When you visit cocalc.com, it looks as follows:" }, { "code": null, "e": 4439, "s": 4349, "text": "After you sign-in and bring up a Jupyter lab environment, it should look like as follows:" }, { "code": null, "e": 4696, "s": 4439, "text": "I will not get into the details of the Jupyterlab interface here as this has already been well documented in the link I shared above, please read the associated document, it’s really well written. Instead, let’s focus on the most interesting tasks on hand:" }, { "code": null, "e": 4759, "s": 4696, "text": "The file extension is ‘.ipynb’: “interactive ipython notebook”" }, { "code": null, "e": 4954, "s": 4759, "text": "We will need to set up a filename instead of “untitled.ipynb”, let’s call it ‘first_analysis.ipynb’. You can right-click on the filename in the second, large white panel and change the filename." }, { "code": null, "e": 5026, "s": 4954, "text": "Then we need to grab some data and write codes and text to get to work." }, { "code": null, "e": 5082, "s": 5026, "text": "But before we did so, we need to touch two more points:" }, { "code": null, "e": 5213, "s": 5082, "text": "Let’s learn a little about R as such and tidyverse and tidy data, andlet’s cover a little about markdown syntax to write your text" }, { "code": null, "e": 5283, "s": 5213, "text": "Let’s learn a little about R as such and tidyverse and tidy data, and" }, { "code": null, "e": 5345, "s": 5283, "text": "let’s cover a little about markdown syntax to write your text" }, { "code": null, "e": 5525, "s": 5345, "text": "I have provided some annotated codes in the following “greyed out” box that you can copy and paste in a code block in Jupyterlab and when you are ready to run, press “Shift+Enter”" }, { "code": null, "e": 6833, "s": 5525, "text": "# Comments in R code blocks are written using 'hash' marks, and # you should use detailed comments on all your codesx <- 1 # '<- ' is an assignment operator. Here x is set to the value of 1# This is same as x = 1x == 1# Here, we evaluate whether x is equal to 1; # Everything in R is an object and you can find out about objects# using the function typeof()typeof(x) # should put 'double'# double tells you that x is a number as in 1.00# you can and should write functions to accomplish repetitive # tasks in R# The syntax of function is:my_function = function(x){ function statements }# You can call functions anywhere in R using the function name and # by writing the function parameters within parentheses# as in my_function(x)# An example of a function where two numbers x, and y are # multipliedmultiply_fn = function(x, y){ z = x * y return(z)}multiply_fn(2,3) # will produce 6# You can see that a function can call within itself another # function# Combination of data and functions are referred to as packages# You can call packages using library() function# You can install packages using install.packages() function# You can find help in R using help(\"topic\") function# In our case we will use \"tidyverse\" package. # We will need to install this first if not already installed" }, { "code": null, "e": 6945, "s": 6833, "text": "So at the end of this little exercise, after we have called the library “tidyverse”, this is how it looks like:" }, { "code": null, "e": 7628, "s": 6945, "text": "As html is the lingua franca of the world wide web, it is also quite complex. So, John Gruber devised this language called markdown where you can write all basic elements of the text using simple decorations to your texts. You can write headings (I usually use two levels of headings), links, and insert codes. You will also be able to use tables and citation marks in the flavour of markdown that is used for jupyter notebooks, so you can pretty much write your entire paper or thesis here. In the box below I have provided a version of a short text written in markdown and the rendered version thereafter. This should get you going writing in jupyter notebooks as well, hopefully." }, { "code": null, "e": 7693, "s": 7628, "text": "This is what we have written in the text box in Jupyter notebook" }, { "code": null, "e": 9105, "s": 7693, "text": "# PurposeThis above was a first level header where we put one hash mark before the header. If we wanted to put a second level header, we would add another hash mark. Here, for example the goal is to demonstrate the principles of writing in markdown and conducting data analyses entirely on a web browser after installing jupyter notebook and optionally jupyter lab on the computer or the server.## What we will do?We will do the following:- We will learn a little about R and markdown- We will go grab some data sets- After loading the data set in Jupyter, we will clean the data set- We will run some tables and visualisations## So is it possible to add tables?Yes, to add tables, do something like:| Task | Software ||------|----------|| Data analysis | Any statistical programme will do || Data analysis plus writing | An integrated solution will work || Examples of integrations | Rstudio, Jupyter, stata |## How do we add links?If you wanted to add links to say sometihng like Google, you would insert the following code: [Name the URL should point, say Google](http://www.google.com), and it would put an underlined URL or name to your text.## Where can I learn more about markdown and its various \"flavours\"?Try the following links:- [Markdown](https://daringfireball.net/projects/markdown/)- [Github flavoured markdown](https://github.github.com/gfm/)- [Academic markdown](http://scholarlymarkdown.com/)" }, { "code": null, "e": 9204, "s": 9105, "text": "And this is how it looks like (partial, you can replicate it in a Jupyter lab or Jupyter Notebook)" }, { "code": null, "e": 9222, "s": 9204, "text": "Now that we have:" }, { "code": null, "e": 9285, "s": 9222, "text": "Learned a little about R and installed and loaded up tidyverse" }, { "code": null, "e": 9354, "s": 9285, "text": "Learned how to write in markdown so that we can describe our results" }, { "code": null, "e": 9663, "s": 9354, "text": "It’s time to grab some data off the web and do some analyses using these tools. Now, where will you get data? Data are everywhere, but some sites make it easier than others for you to grab and work with them. How to obtain data can be another post by itself, so I will not go into the details, but generally:" }, { "code": null, "e": 9751, "s": 9663, "text": "You can search for data (we will use two such sites: Figshare and Google Data Explorer)" }, { "code": null, "e": 9850, "s": 9751, "text": "You can use application programming interfaces (APIs) to get data off websites and play with them." }, { "code": null, "e": 9953, "s": 9850, "text": "Several sites set up toy data or real world data for you to play with (e.g., data and stories library)" }, { "code": null, "e": 10056, "s": 9953, "text": "Government sites and health departments provide “truckloads” of data for you to analyse and make sense" }, { "code": null, "e": 10187, "s": 10056, "text": "The key here is to learn how to make sense of that data. This is where data science comes into the picture. Specifically, you can:" }, { "code": null, "e": 10210, "s": 10187, "text": "Download data for free" }, { "code": null, "e": 10314, "s": 10210, "text": "Shape it up in ways that will make sense for you to understand their patterns and make them “tidy data”" }, { "code": null, "e": 10355, "s": 10314, "text": "Run visualisations using available tools" }, { "code": null, "e": 10532, "s": 10355, "text": "Preprocess data using different software (we will use R and tidyverse in this tutorial, but you can use Python, or other specialised tools such as OpenRefine, and spreadsheets)" }, { "code": null, "e": 10970, "s": 10532, "text": "For the purpose of this exercise, let’s visit Figshare and search data for our work. Let’s say we are interested to identify data on health issues in workplaces and see what data we get off Figshare to get our work done. As this is a demo exercise, we will keep our data set small so that we can learn the most essential points about grabbing data off the web and analysing them. It’s actually quite intuitive to do that using tidyverse." }, { "code": null, "e": 11034, "s": 10970, "text": "When I log in to Figshare, this is how my dashboard looks like:" }, { "code": null, "e": 11400, "s": 11034, "text": "We searched the data based with “work” and “health” and identified a raw data set from a study where the researchers studied the relationship between behavioural activation and depression and quality of life. When we searched, we made sure that we wanted to download only those data that were freely and openly shared (with a CC-0 licence), and we wanted data sets." }, { "code": null, "e": 11452, "s": 11400, "text": "The data were taken from the following publication:" }, { "code": null, "e": 11470, "s": 11452, "text": "journals.plos.org" }, { "code": null, "e": 11543, "s": 11470, "text": "In describing the study, the authors of the paper wrote in the abstract:" }, { "code": null, "e": 13569, "s": 11543, "text": "Quality of life (QOL) is an important health-related concept. Identifying factors that affect QOL can help develop and improve health-promotion interventions. Previous studies suggest that behavioral activation fosters subjective QOL, including well-being. However, the mechanism by which behavioral activation improves QOL is not clear. Considering that QOL improves when depressive symptoms improve post-treatment and that behavioral activation is an effective treatment for depression, it is possible that behavioral activation affects QOL indirectly rather than directly. To clarify the mechanism of the influence of behavioral activation on QOL, it is necessary to examine the relationships between factors related to behavioral activation, depressive symptoms, and QOL. Therefore, we attempted to examine the relationship between these factors. Participants comprised 221 Japanese undergraduate students who completed questionnaires on behavioral activation, QOL, and depressive symptoms: the Japanese versions of the Behavioral Activation for Depression Scale-Short Form (BADS-SF), WHO Quality of Life-BREF (WHOQOL-26), and Center for Epidemiologic Studies Depression Scale (CES-D). The BADS-SF comprises two subscales, Activation and Avoidance, and the WHOQOL-26 measures overall QOL and four domains, Physical Health, Psychological Health, Social Relationships, and Environment. Mediation analyses were conducted with BADS-SF activation and avoidance as independent variables, CES-D as a mediator variable, and each WHO-QOL as an outcome variable. Results indicated that depression completely mediated the relationship between Avoidance and QOL, and partially mediated the relationship between Activation and QOL. In addition, analyses of each domain of QOL showed that Activation positively affected all aspects of QOL directly and indirectly, but Avoidance had a negative influence on only part of QOL mainly through depression. The present study provides behavioral activation strategies aimed at QOL enhancement." }, { "code": null, "e": 13670, "s": 13569, "text": "The full paper is in open source and you can download and read the paper from the following website:" }, { "code": null, "e": 13688, "s": 13670, "text": "journals.plos.org" }, { "code": null, "e": 13734, "s": 13688, "text": "You can directly download the data from here:" }, { "code": null, "e": 13781, "s": 13734, "text": "https://ndownloader.figshare.com/files/9446491" }, { "code": null, "e": 13809, "s": 13781, "text": "Here’s how the data appear:" }, { "code": null, "e": 13915, "s": 13809, "text": "Here, we will use the data set and will run an annotated jupyter notebook to show the different steps of:" }, { "code": null, "e": 13934, "s": 13915, "text": "Obtaining the data" }, { "code": null, "e": 13958, "s": 13934, "text": "Reading the data into R" }, { "code": null, "e": 13980, "s": 13958, "text": "Cleaning the data set" }, { "code": null, "e": 13997, "s": 13980, "text": "Asking questions" }, { "code": null, "e": 14021, "s": 13997, "text": "Answering the questions" }, { "code": null, "e": 14386, "s": 14021, "text": "If you want, you can reproduce their paper on the data set the authors provided but we will not do that in this tutorial. In this tutorial, we have already so far introduced the fact that using a web based tool, you can use Jupyter notebooks/Jupyter labs to conduct data analyses. I have introduced Cocalc, but there are other similar tools as well. Some examples:" }, { "code": null, "e": 14568, "s": 14386, "text": "Microsoft Azure Notebooks a range of languages available all for free and you can use an R or a Python or other languages; for free, and you can sign up and start working right away" }, { "code": null, "e": 14645, "s": 14568, "text": "Google Colaboratory: From Google, and free. You can work on Python notebooks" }, { "code": null, "e": 14735, "s": 14645, "text": "Tryjupyter: Gives you for free notebooks in different languages and in different set ups." }, { "code": null, "e": 14932, "s": 14735, "text": "So, we can start and end our analyses in any of these as these notebooks are interoperable. You can also host notebooks on github and in binder and share your notebooks with the rest of the world." }, { "code": null, "e": 15230, "s": 14932, "text": "Step 1: Download the dataYou can see that this is an Excel spreadsheet file. You can either open it in a spreadsheet programme (such as Excel or in OpenOffice Calc), and export the file as a comma separated value file. Alternatively, we can read the file directly in Jupyter. We will do this here." }, { "code": null, "e": 15314, "s": 15230, "text": "In order to do this, we will need to use the package “readxl”. So we do as follows:" }, { "code": null, "e": 15540, "s": 15314, "text": "# first load the packagelibrary(readxl)# If you find that your Jupyter instance does not have \"readxl\" # package in itself, then you will need to install it. # Easiest, install.packages(\"readxl\") and then do # library(readxl)" }, { "code": null, "e": 15582, "s": 15540, "text": "After loading, this is how it looks like:" }, { "code": null, "e": 15804, "s": 15582, "text": "Well, nothing happened! Why? Because read_excel function read the contents of the excel file “S1_Dataset.xlsx” and stored it in an object named as mydata. We will now use this object mydata to examine what is inside this." }, { "code": null, "e": 15844, "s": 15804, "text": "Step 2: Wrangle the data and preprocess" }, { "code": null, "e": 16053, "s": 15844, "text": "Now that we have read the data set, let’s delve into finding out what’s in there. A first thing is to find out the header information. We can do that in R using ```head()``` function. So here is how it looks:" }, { "code": null, "e": 16127, "s": 16053, "text": "We also want to find out the list of variables in the data set, So we do:" }, { "code": null, "e": 16415, "s": 16127, "text": "names(mydata) # produces the list of variables'Sex' 'Age' 'BADS-SF' 'BADS-SF_Activation' 'BADS-SF_Avoidance' 'CES-D' 'WHOQOL-26_Mean total score' 'WHOQOL-26_Phisical health' 'WHOQOL-26_Psychological health' 'WHOQOL-26_Social relationships' 'WHOQOL-26_Environment' 'WHOQOL-26_Overall QOL'" }, { "code": null, "e": 16881, "s": 16415, "text": "As you can see that while this dataset contains 12 variables with “expressive” names. Some variables have names that contain “spaces” in it. We will rename these variables so that these are meaningful for us. Variables such as “Sex”, and “Age” are relatively straightforward to understand, but we may need to rename the other variables. You will find more information about these variable names from the main paper and the accompanying data description in Figshare." }, { "code": null, "e": 16983, "s": 16881, "text": "The following table maps the variable names with the concepts they stand for and a short description:" }, { "code": null, "e": 17744, "s": 16983, "text": "| Variable Name | What it stands for ||---------------|--------------------|| Sex | 1 = Male, 2 = Female || Age | Age in years || BADS-SF | Behavioral Activation for Depression Scale-Short Form || BADS-SF_Activation | BADS for activation || BADS-SF_Avoidance | BADS for avoidance || CES-D | Center for Epidemiologic Studies Depression Scale || WHOQOL-26_Mean total score | Japanese version of the WHO Quality of Life-BREF mean total score || WHOQOL-26_Phisical health | WHOQol-26 physical health || WHOQOL-26_Psychological health | WHOQoL-26 psychological health || WHOQOL-26_Social relationships | WHOQoL-26 social relationships || WHOQOL-26_Environment | WHOQoL-26 Environment || WHOQOL-26_Overall QOL | WHOQoL-26 Overall |" }, { "code": null, "e": 17934, "s": 17744, "text": "QoL in these variables are short forms of Quality of Life. You can learn more about WHO QoL from the relevant website here: https://www.who.int/substance_abuse/research_tools/whoqolbref/en/" }, { "code": null, "e": 18044, "s": 17934, "text": "We will not cover the details here as we are soldiering on to the next step. At this stage, you can see that:" }, { "code": null, "e": 18161, "s": 18044, "text": "The variable names are kind of long so you may want to shorten them but keep them understandable as you keep working" }, { "code": null, "e": 18293, "s": 18161, "text": "Many variables have spaces in their names so they need to be taken care of (we suggest that you use underscore to represent spaces)" }, { "code": null, "e": 18313, "s": 18293, "text": "This is what we do:" }, { "code": null, "e": 18337, "s": 18313, "text": "Several things to note:" }, { "code": null, "e": 18858, "s": 18337, "text": "We will store the renamed variables in a new data set (otherwise our changes will not persist beyond what we have done in the code and immediately executed, so make sure to save it in a different named object)We use a symbol ‘%>%’; this symbol is referred to as ‘pipe’ and it read as “and then”. Here we chain a number of different operations or commands together using this. If you want to learn more about this and how to use it, please refer to Hadley Wickham’s excellent book on data science with R, where he writes," }, { "code": null, "e": 19068, "s": 18858, "text": "We will store the renamed variables in a new data set (otherwise our changes will not persist beyond what we have done in the code and immediately executed, so make sure to save it in a different named object)" }, { "code": null, "e": 19380, "s": 19068, "text": "We use a symbol ‘%>%’; this symbol is referred to as ‘pipe’ and it read as “and then”. Here we chain a number of different operations or commands together using this. If you want to learn more about this and how to use it, please refer to Hadley Wickham’s excellent book on data science with R, where he writes," }, { "code": null, "e": 19696, "s": 19380, "text": "Behind the scenes, x %>% f(y) turns into f(x, y), and x %>% f(y) %>% g(z) turns into g(f(x, y), z) and so on. You can use the pipe to rewrite multiple operations in a way that you can read left-to-right, top-to-bottom. We’ll use piping frequently from now on because it considerably improves the readability of code" }, { "code": null, "e": 19766, "s": 19696, "text": "Then we used the “rename()” function and in there, we did as follows:" }, { "code": null, "e": 19825, "s": 19766, "text": "The “new variable name” was the FIRST element, followed by" }, { "code": null, "e": 19910, "s": 19825, "text": "An “equal sign”, and the “old variable name” was the SECOND element, indicating that" }, { "code": null, "e": 19963, "s": 19910, "text": "We store the old variable values in the new variable" }, { "code": null, "e": 20199, "s": 19963, "text": "Note that at the end of this, once we executed it, we got a new data set with all values intact but with new variable names. If you do not want to transform the names of some variables, keep them as such (as we did for “Age” and “Sex”)" }, { "code": null, "e": 21104, "s": 20199, "text": "The first thing we do when we get a brand new data set to play with is to “wrangle” the data. We examine the variables, we plot them, we recode them to suit our purpose, we ask questions and we try to answer them. Then, once we have discovered some patterns that we see we can delve in, we start modelling the data in various ways. In this tutorial, I will confine myself to writing about the first part, how do we do simple tables and graphs. Again, if you are working with R and tidyverse (which I recommend), your main text is Hadley Wickham’s book: R for Data Science. The book is available for free; you can work with free software on the web to learn and practice, so please give it a try. As you have seen, you can get data for free as well from different sites. I will not repeat in details everything in that book, but will point to five grammars that you will find helpful in working with data:" }, { "code": null, "e": 21299, "s": 21104, "text": "Select. — Use this to select columns from the data set. Let’s say we want to work with only BADS and CES D variables for this population, we will have to select the columns we want to work with:" }, { "code": null, "e": 21534, "s": 21299, "text": "Filter. — If we wanted to work with certain “individuals” in the data set, we would filter the rows based on some criteria we set on the columns. Say, we want to work with women (“Sex == 2”) and teenagers (“Age < 20”), see what we do:" }, { "code": null, "e": 21555, "s": 21534, "text": "Note the simplicity:" }, { "code": null, "e": 21620, "s": 21555, "text": "We use “==” equivalence operator to set the filtering conditions" }, { "code": null, "e": 21673, "s": 21620, "text": "We separate different conditions using a “,” (comma)" }, { "code": null, "e": 21804, "s": 21673, "text": "Arrange. — If we want to get a view of the data set by ascending or descending order, we use the verb “arrange()” to do so, as in:" }, { "code": null, "e": 22038, "s": 21804, "text": "As you can see, the youngest person in the dataset is aged 2 years! You need to go back and correct or test if this was indeed the value. This is where data cleaning and preprocessing becomes important. What sense do we make of this?" }, { "code": null, "e": 22431, "s": 22038, "text": "Mutate. — You want to create new variables and store them in the data set. You want to create these variables out of existing variables using other functions. Say, now that we know that a person’s age was inserted as 2 years and possibly a mistake, we do not want to lose that person’s information and we wanted to cut the age variable in 4 groups, what do we do? We use mutate verb, like so:" }, { "code": null, "e": 22443, "s": 22431, "text": "So you see:" }, { "code": null, "e": 22488, "s": 22443, "text": "Use mutate to recode one variable to another" }, { "code": null, "e": 22523, "s": 22488, "text": "Use mutate to create new variables" }, { "code": null, "e": 22549, "s": 22523, "text": "Mutate uses new functions" }, { "code": null, "e": 22603, "s": 22549, "text": "Let’s count the age_rec variable and see what we get:" }, { "code": null, "e": 22785, "s": 22603, "text": "As you see, if you let the computer to decide, it can create categories that we cannot much use. So, let’s recode and mutate a new age group and say save it to a new data set, here:" }, { "code": null, "e": 22810, "s": 22785, "text": "Did you see what we did?" }, { "code": null, "e": 23008, "s": 22810, "text": "We created a new data set (mydata4) and in there we created a new variable binarised age (“age_bin”), where we had teenagers and respondents who were 20 years and older (actually it should be ≥ 20)" }, { "code": null, "e": 23111, "s": 23008, "text": "You can also assign labels of your choice (so we could put “Teenagers” and “Twenty plus” if we wanted." }, { "code": null, "e": 23214, "s": 23111, "text": "Mutate is a powerful verb that lets you recreate data sets and code variables. You should master this." }, { "code": null, "e": 23721, "s": 23214, "text": "Summarize and group_by. — Selecting, filtering, arranging the data set and mutating or changing the variables may sound like a lot of useful things to do, but you will also need to peek deeper into the data and learn how to find meaning from it. You will need to find aggregated summaries, and average values for those variables that are continuous, and tabulate those that are categorical. In this way, you can gain insights into the data. Let me introduce you to “summarise()” and “group_by()” functions." }, { "code": null, "e": 23914, "s": 23721, "text": "Let’s say you are interested to find out the average age of the respondents of this survey and then wanted to see if the males were on average older than the females. How would you do it? See:" }, { "code": null, "e": 24064, "s": 23914, "text": "# What is the average age of the respondents?average_age = mydata4 %>% summarise(average_age = mean(Age, na.rm = T))average_age# Will return 19.36652" }, { "code": null, "e": 24255, "s": 24064, "text": "See that this is a single number that consolidates the entire data set for all individuals. That is fine, and you can get a whole list of such averages for the continuous variables you post." }, { "code": null, "e": 24820, "s": 24255, "text": "However, if we were to split the data set into different discrete groups (such as binarised age groups, or Sex for that matter), and then calculate the averages of the other variables, it would make for an interesting display to identify patterns. So, basically, after splitting the data set, we would apply some functions, in our case say mean, and then we combine the results back to present, that’d make for interesting display of results that are also meaningful. For a comprehensive introduction to this topic, read the following article (download it as PDF):" }, { "code": null, "e": 24863, "s": 24820, "text": "So, let’s put this into action and see if:" }, { "code": null, "e": 24905, "s": 24863, "text": "Are Males older than females in our data?" }, { "code": null, "e": 24993, "s": 24905, "text": "Do Teenagers have lower average scores on health related quality of life (Mean WHOQoL)?" }, { "code": null, "e": 25030, "s": 24993, "text": "So, what are your take away lessons?" }, { "code": null, "e": 25065, "s": 25030, "text": "We first passed the data set, then" }, { "code": null, "e": 25190, "s": 25065, "text": "We asked tidyverse to group by the categorical variable (first do this, because this is your “split”ting the data), and then" }, { "code": null, "e": 25239, "s": 25190, "text": "We asked for summarising the variable we wanted." }, { "code": null, "e": 25432, "s": 25239, "text": "Gathering and spreading. — Let’s put some of these concepts into action and try to answer the question, how do quality of life scores differ between males and females for different age groups?" }, { "code": null, "e": 25473, "s": 25432, "text": "Let’s find out the average scores first:" }, { "code": null, "e": 26226, "s": 25473, "text": "This is fine, but this is quite complex to interpret. We have to first look at the first row and then find the scores for individual quality of life parameters for the male gender (Sex equals 1) and then read the next row and so on. It’d help us if we were to have one variable that would say be “quality_of_life” that would list qol, physical, psych, soc, env etc and we would read them down. That is, we would have to gather these various scores and put them under one variable, say “quality_of_life”, and we would put all the scores we see there under another variable next to it, we can call that variable as “all_means” (as these are essentially mean values). In tidyverse, we now introduce another verb called “gather” that would do exactly that:" }, { "code": null, "e": 26359, "s": 26226, "text": "Use a “key” where you would gather the names of the variables that you want to group together. Here, for instance, “quality of life”" }, { "code": null, "e": 26508, "s": 26359, "text": "Use a “value” where you would put their respective values. What names you give key and value is up to you. Give them meaningful names is all I care." }, { "code": null, "e": 26549, "s": 26508, "text": "So, here is the code for you to examine:" }, { "code": null, "e": 26969, "s": 26549, "text": "See what’s happening? We have now “gathered” for all age groups and all sexes their quality of life scores (various parameters). But this is still quite complex as there is repetition for Sex and repetition for age groups. If we’d like to spread it out so that now we would have the values of “all_means” score spread out under the keys of Sex (1 and 2), we could have see them quite intuitively. Here’s the code again:" }, { "code": null, "e": 27390, "s": 26969, "text": "So, now you can see you can read across each age group (grouped under each age group), each of the scores and can compare between males and females. This way you can make some interesting comparisons. One area where “spread” becomes particularly useful is when you crosstabulate variables, as in when you cross tabulate binarised age and Sex for instance in this data set. First, take a look at what happens when you run" }, { "code": null, "e": 27479, "s": 27390, "text": "crosstab = mydata4 %>% count(age_bin, Sex) # crosstabs binarised age and Sex" }, { "code": null, "e": 27627, "s": 27479, "text": "Fine, but we want a proper cross-tabulation where Sex appears on the column and binarised age in the rows. So, we use “spread” to achieve this, see" }, { "code": null, "e": 27931, "s": 27627, "text": "Much better. Now you can see how binarised age groups are spread across the genders 1 and 2 (remember that 1 = male, 2 = female). Also, note that this is a data frame, which means you can use mutate() to add a column to find out the row wise percentages of teenagers in each gender. How can you do that?" }, { "code": null, "e": 28172, "s": 27931, "text": "As you can see males are higher in the teenage groups, and lower (26%) in the 20 plus age groups. So, when you assess relationship between some of the scores and gender, keep in mind that age distribution can work as a confounding variable." }, { "code": null, "e": 28621, "s": 28172, "text": "In the first two steps, how to obtain data from a variety of sources (for free) and how to use freely available software such as Jupyter to write and work on the data to make it suitable for analyses. But preparing tables and summaries and cleaning the data is half the fun. Being able to create simple graphs to dive deeper into the data is satisfying. So in this third and final step today, we will learn how to create simple graphs in tidyverse." }, { "code": null, "e": 28800, "s": 28621, "text": "I suggest you use the “ggplot()” to create graphs. Ggplot() is a vast topic and there are books available on the web for you to read. Read the following resources to get started:" }, { "code": null, "e": 28822, "s": 28800, "text": "Tidyverse ggplot docs" }, { "code": null, "e": 28842, "s": 28822, "text": "R graphics Cookbook" }, { "code": null, "e": 28895, "s": 28842, "text": "The data visualisation section of R for data science" }, { "code": null, "e": 29083, "s": 28895, "text": "In addition to the above sites, I’d recommend you read the following paper to gain an insight into graph construction (principles at least), irrespective whether you use tidyverse or not:" }, { "code": null, "e": 29212, "s": 29083, "text": "In order to plot graphs to visualise data, we will use ggplot() function in this tutorial and we will follow the general scheme:" }, { "code": null, "e": 29516, "s": 29212, "text": "ggplot([data]) + geom_[geometry](mappings = aes(x = [variable], y = [variable], stats = \"<choices>\") + facet_<wrap | grid>() + coord_<choices>() + labs(\"title of the plot) + xlab(\"label for x axis\") + ylab(\"label for y axis\")" }, { "code": null, "e": 29720, "s": 29516, "text": "For a complete understanding of how ggplot() works, please follow the links I have listed above. Here, as we are introducing and getting our feet “wet”, I will only cover the basics. Remember some rules:" }, { "code": null, "e": 29818, "s": 29720, "text": "The function is ggplot(), and data is mandatory (this is why I have placed it in square brackets)" }, { "code": null, "e": 29915, "s": 29818, "text": "Then there is a “+” sign, and the + sign must ALWAYS be at the end of a line, NEVER at the start" }, { "code": null, "e": 29989, "s": 29915, "text": "The plus sign indicates a “layer”, from the “layered grammar of graphics”" }, { "code": null, "e": 30079, "s": 29989, "text": "You must always specify the aesthetics (“aes”) values, otherwise the graph will not build" }, { "code": null, "e": 30186, "s": 30079, "text": "Rest of the options are kind of optional (I say “kind of”, because you will learn as you go on using this)" }, { "code": null, "e": 30239, "s": 30186, "text": "Let’s start with mydata4 and see how it appears now:" }, { "code": null, "e": 30266, "s": 30239, "text": "Let’s graphically explore:" }, { "code": null, "e": 30308, "s": 30266, "text": "What does the age distribution look like?" }, { "code": null, "e": 30354, "s": 30308, "text": "What does it look like for males and females?" }, { "code": null, "e": 30449, "s": 30354, "text": "What is the relationship between bads_sf and whoqol_mean? Is it similar for males and females?" }, { "code": null, "e": 30667, "s": 30449, "text": "We can go on exploring, but answering these questions graphically will provide you with ideas that you can use for exploring your own questions in this data set and for future data sets that you may want to work with." }, { "code": null, "e": 30709, "s": 30667, "text": "What does the age distribution look like?" }, { "code": null, "e": 30732, "s": 30709, "text": "First, study the code:" }, { "code": null, "e": 30879, "s": 30732, "text": "mydata4 %>% ggplot() + geom_bar(aes(x = Age)) + ggtitle(\"A bar plot of age\") + xlab(\"Age in years\") + ylab(\"Counts\") + ggsave(\"age_bar.png\")" }, { "code": null, "e": 30955, "s": 30879, "text": "mydata4 was the data set that contained all the variables we wanted to plot" }, { "code": null, "e": 31027, "s": 30955, "text": "the pipe symbol sent the information about mydata4 to ggplot() function" }, { "code": null, "e": 31086, "s": 31027, "text": "Then we started a new layer and added layers with + symbol" }, { "code": null, "e": 31248, "s": 31086, "text": "We ask for a bar plot as the age was mostly numbers and hence represented with bars. We only had to specify an X axis and ggplot would figure out the raw counts." }, { "code": null, "e": 31321, "s": 31248, "text": "We titled the graph with ggtitle() and inserted the title in quote marks" }, { "code": null, "e": 31381, "s": 31321, "text": "We labelled x and y axes using xlab(), and ylab() functions" }, { "code": null, "e": 31425, "s": 31381, "text": "We saved the figure using ggsave() function" }, { "code": null, "e": 31452, "s": 31425, "text": "This is how it looks like:" }, { "code": null, "e": 31523, "s": 31452, "text": "Does the bar plot of age distribution look same for males and females?" }, { "code": null, "e": 31616, "s": 31523, "text": "Now we should use the facet function to plot two different plots, or we can split the graph:" }, { "code": null, "e": 31637, "s": 31616, "text": "First, see the code:" }, { "code": null, "e": 31818, "s": 31637, "text": "mydata4 %>% ggplot() + geom_bar(aes(x = Age)) + facet_wrap(~Sex) + ggtitle(\"A bar plot of age by gender\") + xlab(\"Age in years\") + ylab(\"Counts\") + ggsave(\"age_bar_sex.png\")" }, { "code": null, "e": 32029, "s": 31818, "text": "Note that we added to wrap the figure into two parts by adding the Sex variable so that it splits the Figure into two parts as in the figure below. What do you think? Does it look similar for males and females?" }, { "code": null, "e": 32262, "s": 32029, "text": "This time, we are going to explore the association or relationship between two variables. What graph we will draw will depend on the nature of the variables we want to work with. The following table will provide you with some ideas:" }, { "code": null, "e": 32698, "s": 32262, "text": "| X variable | Y variable | Type of graph | Geometry ||------------|------------|---------------|------------------|| Continuous | Continuous | Scatterplot | geom_point() || Continuous | Categorical| Boxplot | geom_boxplot() | | Categorical| Continuous | Boxplot | geom_boxplot() || Categorical| None | Barplot | geom_bar() || Continuous | None | Histogram | geom_histogram() |" }, { "code": null, "e": 33181, "s": 32698, "text": "Because both bads_sf and whoqol_mean are continuous, we can draw a scatterplot. But what is going to explain what else? If we think that there may be a relationship between between whoqol_mean such that if bads_sf scores increase, so will whoqol_mean, we can test this using a scatterplot and draw linear regressions to plot their relationships (linear regression or modelling is beyond the scope for this tutorial, but we will only show the graph and not write more about it here)." }, { "code": null, "e": 33198, "s": 33181, "text": "Here’s the code:" }, { "code": null, "e": 33397, "s": 33198, "text": "mydata4 %>% ggplot() + geom_point(aes(x = bads_sf, y = whoqol_mean)) + ggtitle(\"Association between bads_sf and whoqol\") + xlab(\"BADS-SF score\") + ylab(\"WHOQoL Score\") + ggsave(\"bads_who.png\")" }, { "code": null, "e": 33430, "s": 33397, "text": "Here’s the graph of association:" }, { "code": null, "e": 33626, "s": 33430, "text": "Now we need to qualify it further and see if the association is similar for males and females. So, we add a regression line, and colour the points and the lines differently for males and females:" }, { "code": null, "e": 33649, "s": 33626, "text": "Here’s the code first:" }, { "code": null, "e": 33987, "s": 33649, "text": "mydata4 %>% mutate(gender = as.factor(Sex)) %>% ggplot() + geom_point(aes(x = bads_sf, y = whoqol_mean, colour = gender)) + geom_smooth(aes(x = bads_sf, y = whoqol_mean, colour = gender), method = \"lm\") + ggtitle(\"Association between bads_sf and whoqol\") + xlab(\"BADS-SF score\") + ylab(\"WHOQoL Score\") + ggsave(\"bads_who_lm.png\")" }, { "code": null, "e": 34004, "s": 33987, "text": "Then the figure:" }, { "code": null, "e": 34025, "s": 34004, "text": "So, what’s going on?" }, { "code": null, "e": 34434, "s": 34025, "text": "We had to add a new variable, “gender”, from “Sex” so used the mutate function to convert it to a factor variable rather than a character variable it was. A factor variable is a categorical variable but explicitly has levels that are arranged according to alphabetical or numerical order. This was necessary for the subsequent steps where we wanted to test what would be the differences in the relationships." }, { "code": null, "e": 34623, "s": 34434, "text": "We wanted to test how the points would differ so, we coloured them differently using the gender variable. Note that we have placed the colour argument within the aesthetics of the mapping." }, { "code": null, "e": 34972, "s": 34623, "text": "Similarly, we wanted to use a smoothing function, and in our case, this was “linear model”, hence “lm” as a method of choice. But this has to be posted outside of the aesthetics parameters. Within the aesthetics of the smoothing lines, we would need to indicate that we want different coloured lines pertaining to the levels of the gender variable." }, { "code": null, "e": 35175, "s": 34972, "text": "So, what do you think you see in the relationship? Does it vary much between genders? We could go on exploring the data set more but we will need to stop here and take stock of what we have done so far." }, { "code": null, "e": 35237, "s": 35175, "text": "So this was a tutorial where we covered the following topics:" }, { "code": null, "e": 35456, "s": 35237, "text": "Jupyter notebooks are free and open source tools that enable you to conduct data science-y work but also allow you to take full advantage of the potential of R and Python (and other languages) to conduct data analyses." }, { "code": null, "e": 35602, "s": 35456, "text": "You can conduct secondary data analyses and tidy data without practically using any other tools (such as spreadsheets) to clean and wrangle data." }, { "code": null, "e": 35795, "s": 35602, "text": "We identified a data set on the web that used CC-0 licence (creative commons licence where the data sets could be used to work on freely) and an accompanying article to investigate a data set." }, { "code": null, "e": 35887, "s": 35795, "text": "We learned how to use the tidyverse environment to examine, subset, filter, and graph data." }, { "code": null, "e": 36359, "s": 35887, "text": "I hope that this will get you inspired to work on more data sets. Remember that the more you practice, the better your skills will be. If you need more information and have questions, please post them in the comments section. I wanted it to be a quick introduction, so did not introduce some other concepts about tidy data and statistical procedures; this will be discussed in subsequent articles and you will find more information everywhere on the web. Happy analysing!" } ]
Java Program to Guess a Random Number in a Range - GeeksforGeeks
04 Dec, 2020 Write a program that generates a random number and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display Too high, try again. If the user’s guess is lower than the random number, the program should display Too low, try again. The program should use a loop that repeats until the user correctly guesses the random number. Input: 15 (a random value that is not known before) Output: Guess a number between 1 and 100: 1 Too low, try again Guess a number between 1 and 100: 10 Too low, try again Guess a number between 1 and 100: 25 Too high, try again Guess a number between 1 and 100: 20 Too high, try again Guess a number between 1 and 100: 15 Yes, you guessed the number. Example Java // Java Program to guess a Random Number Generation import java.util.Random;import java.util.Scanner; public class GFG { public static void main(String[] args) { // stores actual and guess number int answer, guess; // maximum value is 100 final int MAX = 100; // takes input using scanner Scanner in = new Scanner(System.in); // Random instance Random rand = new Random(); boolean correct = false; // correct answer answer = rand.nextInt(MAX) + 1; // loop until the guess is correct while (!correct) { System.out.println( "Guess a number between 1 and 100: "); // guess value guess = in.nextInt(); // if guess is greater than actual if (guess > answer) { System.out.println("Too high, try again"); } // if guess is less than actual else if (guess < answer) { System.out.println("Too low, try again"); } // guess is equal to actual value else { System.out.println( "Yes, you guessed the number."); correct = true; } } System.exit(0); }} Output Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25262, "s": 25234, "text": "\n04 Dec, 2020" }, { "code": null, "e": 25653, "s": 25262, "text": "Write a program that generates a random number and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display Too high, try again. If the user’s guess is lower than the random number, the program should display Too low, try again. The program should use a loop that repeats until the user correctly guesses the random number." }, { "code": null, "e": 26009, "s": 25653, "text": "Input: 15 (a random value that is not known before)\nOutput: Guess a number between 1 and 100: \n1\nToo low, try again\nGuess a number between 1 and 100: \n10\nToo low, try again\nGuess a number between 1 and 100: \n25\nToo high, try again\nGuess a number between 1 and 100: \n20\nToo high, try again\nGuess a number between 1 and 100: \n15\nYes, you guessed the number." }, { "code": null, "e": 26017, "s": 26009, "text": "Example" }, { "code": null, "e": 26022, "s": 26017, "text": "Java" }, { "code": "// Java Program to guess a Random Number Generation import java.util.Random;import java.util.Scanner; public class GFG { public static void main(String[] args) { // stores actual and guess number int answer, guess; // maximum value is 100 final int MAX = 100; // takes input using scanner Scanner in = new Scanner(System.in); // Random instance Random rand = new Random(); boolean correct = false; // correct answer answer = rand.nextInt(MAX) + 1; // loop until the guess is correct while (!correct) { System.out.println( \"Guess a number between 1 and 100: \"); // guess value guess = in.nextInt(); // if guess is greater than actual if (guess > answer) { System.out.println(\"Too high, try again\"); } // if guess is less than actual else if (guess < answer) { System.out.println(\"Too low, try again\"); } // guess is equal to actual value else { System.out.println( \"Yes, you guessed the number.\"); correct = true; } } System.exit(0); }}", "e": 27330, "s": 26022, "text": null }, { "code": null, "e": 27337, "s": 27330, "text": "Output" }, { "code": null, "e": 27344, "s": 27337, "text": "Picked" }, { "code": null, "e": 27368, "s": 27344, "text": "Technical Scripter 2020" }, { "code": null, "e": 27373, "s": 27368, "text": "Java" }, { "code": null, "e": 27387, "s": 27373, "text": "Java Programs" }, { "code": null, "e": 27406, "s": 27387, "text": "Technical Scripter" }, { "code": null, "e": 27411, "s": 27406, "text": "Java" }, { "code": null, "e": 27509, "s": 27411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27524, "s": 27509, "text": "Stream In Java" }, { "code": null, "e": 27545, "s": 27524, "text": "Constructors in Java" }, { "code": null, "e": 27564, "s": 27545, "text": "Exceptions in Java" }, { "code": null, "e": 27594, "s": 27564, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27640, "s": 27594, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27666, "s": 27640, "text": "Java Programming Examples" }, { "code": null, "e": 27700, "s": 27666, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27747, "s": 27700, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 27779, "s": 27747, "text": "How to Iterate HashMap in Java?" } ]
PyQt5 QDockWidget – Setting Layout Direction - GeeksforGeeks
29 Jan, 2022 In this article we will see how we can set the layout direction to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). Layout specifies how the children get arranged, by setting layout direction we can specify the order of the arrangement. In order to do this we will use setLayoutDirection method with the dock widget object.Syntax : dock.setLayoutDirection(direct)Argument : It takes direction object as argumentReturn : It returns None Below is the implementation Python3 # importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating dock widget dock = QDockWidget(self) # setting title to the dock widget dock.setWindowTitle(" GfG ") # push button push = QPushButton("Press", self) # setting widget to the dock dock.setWidget(push) # setting layout direction dock.setLayoutDirection(Qt.RightToLeft) # creating a label label = QLabel("GfG", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # setting geometry tot he dock widget dock.setGeometry(100, 0, 200, 30) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : sagartomar9927 Python PyQt-QDockWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25931, "s": 25903, "text": "\n29 Jan, 2022" }, { "code": null, "e": 26361, "s": 25931, "text": "In this article we will see how we can set the layout direction to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). Layout specifies how the children get arranged, by setting layout direction we can specify the order of the arrangement. " }, { "code": null, "e": 26562, "s": 26361, "text": "In order to do this we will use setLayoutDirection method with the dock widget object.Syntax : dock.setLayoutDirection(direct)Argument : It takes direction object as argumentReturn : It returns None " }, { "code": null, "e": 26592, "s": 26562, "text": "Below is the implementation " }, { "code": null, "e": 26600, "s": 26592, "text": "Python3" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating dock widget dock = QDockWidget(self) # setting title to the dock widget dock.setWindowTitle(\" GfG \") # push button push = QPushButton(\"Press\", self) # setting widget to the dock dock.setWidget(push) # setting layout direction dock.setLayoutDirection(Qt.RightToLeft) # creating a label label = QLabel(\"GfG\", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # setting geometry tot he dock widget dock.setGeometry(100, 0, 200, 30) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27928, "s": 26600, "text": null }, { "code": null, "e": 27939, "s": 27928, "text": "Output : " }, { "code": null, "e": 27956, "s": 27941, "text": "sagartomar9927" }, { "code": null, "e": 27980, "s": 27956, "text": "Python PyQt-QDockWidget" }, { "code": null, "e": 27991, "s": 27980, "text": "Python-gui" }, { "code": null, "e": 28003, "s": 27991, "text": "Python-PyQt" }, { "code": null, "e": 28010, "s": 28003, "text": "Python" }, { "code": null, "e": 28108, "s": 28010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28126, "s": 28108, "text": "Python Dictionary" }, { "code": null, "e": 28161, "s": 28126, "text": "Read a file line by line in Python" }, { "code": null, "e": 28193, "s": 28161, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28215, "s": 28193, "text": "Enumerate() in Python" }, { "code": null, "e": 28257, "s": 28215, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28287, "s": 28257, "text": "Iterate over a list in Python" }, { "code": null, "e": 28313, "s": 28287, "text": "Python String | replace()" }, { "code": null, "e": 28342, "s": 28313, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28386, "s": 28342, "text": "Reading and Writing to text files in Python" } ]
C# Program to Get Complete Path of Current Directory - GeeksforGeeks
21 Apr, 2022 Given a directory, now our task is to find the path of the given directory or current directory. So to this task, we use the GetCurrentDirectory() method of the Directory class. This method will return the complete path of the current directory. The result given by this method will not end with a backslash (\). Syntax: public static string GetCurrentDirectory(); Return: It will return a string that represents the path of the current directory. Exception: It will throw the following exceptions: UnauthorizedAccessException: This exception occurs when the caller does not have the required permission. NotSupportedException: This exception occurs when the operating system is Windows CE. It does not have the functionality of the current directory. Example: C# // C# program to find the path of// the current directoryusing System;using System.IO; class GFG{ static void Main(){ // Finding the complete path of the current directory // Using GetCurrentDirectory() method Console.WriteLine("Current directory path: " + Directory.GetCurrentDirectory());}} Output: Current directory path: C:\Users\Sravan\ConsoleApplication12 simmytarika5 Picked C# C# Programs 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 Convert String to Character Array in C# Program to Print a New Line in C# Getting a Month Name Using Month Number in C# Socket Programming in C# C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
[ { "code": null, "e": 25547, "s": 25519, "text": "\n21 Apr, 2022" }, { "code": null, "e": 25860, "s": 25547, "text": "Given a directory, now our task is to find the path of the given directory or current directory. So to this task, we use the GetCurrentDirectory() method of the Directory class. This method will return the complete path of the current directory. The result given by this method will not end with a backslash (\\)." }, { "code": null, "e": 25868, "s": 25860, "text": "Syntax:" }, { "code": null, "e": 25912, "s": 25868, "text": "public static string GetCurrentDirectory();" }, { "code": null, "e": 25996, "s": 25912, "text": "Return: It will return a string that represents the path of the current directory. " }, { "code": null, "e": 26047, "s": 25996, "text": "Exception: It will throw the following exceptions:" }, { "code": null, "e": 26153, "s": 26047, "text": "UnauthorizedAccessException: This exception occurs when the caller does not have the required permission." }, { "code": null, "e": 26300, "s": 26153, "text": "NotSupportedException: This exception occurs when the operating system is Windows CE. It does not have the functionality of the current directory." }, { "code": null, "e": 26309, "s": 26300, "text": "Example:" }, { "code": null, "e": 26312, "s": 26309, "text": "C#" }, { "code": "// C# program to find the path of// the current directoryusing System;using System.IO; class GFG{ static void Main(){ // Finding the complete path of the current directory // Using GetCurrentDirectory() method Console.WriteLine(\"Current directory path: \" + Directory.GetCurrentDirectory());}}", "e": 26640, "s": 26312, "text": null }, { "code": null, "e": 26648, "s": 26640, "text": "Output:" }, { "code": null, "e": 26709, "s": 26648, "text": "Current directory path: C:\\Users\\Sravan\\ConsoleApplication12" }, { "code": null, "e": 26722, "s": 26709, "text": "simmytarika5" }, { "code": null, "e": 26729, "s": 26722, "text": "Picked" }, { "code": null, "e": 26732, "s": 26729, "text": "C#" }, { "code": null, "e": 26744, "s": 26732, "text": "C# Programs" }, { "code": null, "e": 26842, "s": 26744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26865, "s": 26842, "text": "Extension Method in C#" }, { "code": null, "e": 26893, "s": 26865, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26910, "s": 26893, "text": "C# | Inheritance" }, { "code": null, "e": 26932, "s": 26910, "text": "Partial Classes in C#" }, { "code": null, "e": 26961, "s": 26932, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27001, "s": 26961, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27035, "s": 27001, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 27081, "s": 27035, "text": "Getting a Month Name Using Month Number in C#" }, { "code": null, "e": 27106, "s": 27081, "text": "Socket Programming in C#" } ]
Ternary Plots in Plotly - GeeksforGeeks
01 Oct, 2020 A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. A ternary plot is also known as a ternary graph, triangle plot, simplex plot which is a barycentric plot on three variables which sum to a constant. It graphically depicts the ratios of the three variables as positions in an equilateral triangle. It can be created using two-class i.e. express class and graph_objects class. In plotly, express is an easy-to-use,high-level interface that helps to operates a variety of types of data and produce simple style figures. It provides scatter_ternary() method to create ternary plots. Syntax: scatter_ternary( a=None, b=None, c=None, color=None,labels={},width=None, height=None) Parameters: a: Values from this column or array_like are used to position marks along the a axis in ternary coordinates. b: Values from this column or array_like are used to position marks along the b axis in ternary coordinates. c: Values from this column or array_like are used to position marks along the c axis in ternary coordinates. color: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks. width: The figure width in pixels. height: The figure height in pixels. Example: Python3 import plotly.express as px df = px.data.iris()fig = px.scatter_ternary(df, a="sepal_length", b="sepal_width", c="petal_length", color="species", size_max=20)fig.show() Output: Let’s see one example of a ternary scatter plot with plotly graph objects to make it clear. It can be created using the Scatterternary() method. Example: Python3 import plotly.express as pximport plotly.graph_objects as go df = px.data.iris()fig = go.Figure(go.Scatterternary({ 'mode': 'markers', 'a': df['sepal_length'], 'b': df['sepal_width'], 'c': df['petal_length'], 'marker': { 'color': 'green', 'size': 14, 'line': {'width': 2} }})) fig.show() Output: Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 25313, "s": 25285, "text": "\n01 Oct, 2020" }, { "code": null, "e": 25617, "s": 25313, "text": "A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library." }, { "code": null, "e": 25942, "s": 25617, "text": "A ternary plot is also known as a ternary graph, triangle plot, simplex plot which is a barycentric plot on three variables which sum to a constant. It graphically depicts the ratios of the three variables as positions in an equilateral triangle. It can be created using two-class i.e. express class and graph_objects class." }, { "code": null, "e": 26146, "s": 25942, "text": "In plotly, express is an easy-to-use,high-level interface that helps to operates a variety of types of data and produce simple style figures. It provides scatter_ternary() method to create ternary plots." }, { "code": null, "e": 26241, "s": 26146, "text": "Syntax: scatter_ternary( a=None, b=None, c=None, color=None,labels={},width=None, height=None)" }, { "code": null, "e": 26253, "s": 26241, "text": "Parameters:" }, { "code": null, "e": 26362, "s": 26253, "text": "a: Values from this column or array_like are used to position marks along the a axis in ternary coordinates." }, { "code": null, "e": 26471, "s": 26362, "text": "b: Values from this column or array_like are used to position marks along the b axis in ternary coordinates." }, { "code": null, "e": 26580, "s": 26471, "text": "c: Values from this column or array_like are used to position marks along the c axis in ternary coordinates." }, { "code": null, "e": 26743, "s": 26580, "text": "color: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks." }, { "code": null, "e": 26778, "s": 26743, "text": "width: The figure width in pixels." }, { "code": null, "e": 26815, "s": 26778, "text": "height: The figure height in pixels." }, { "code": null, "e": 26824, "s": 26815, "text": "Example:" }, { "code": null, "e": 26832, "s": 26824, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.iris()fig = px.scatter_ternary(df, a=\"sepal_length\", b=\"sepal_width\", c=\"petal_length\", color=\"species\", size_max=20)fig.show()", "e": 27052, "s": 26832, "text": null }, { "code": null, "e": 27060, "s": 27052, "text": "Output:" }, { "code": null, "e": 27205, "s": 27060, "text": "Let’s see one example of a ternary scatter plot with plotly graph objects to make it clear. It can be created using the Scatterternary() method." }, { "code": null, "e": 27214, "s": 27205, "text": "Example:" }, { "code": null, "e": 27222, "s": 27214, "text": "Python3" }, { "code": "import plotly.express as pximport plotly.graph_objects as go df = px.data.iris()fig = go.Figure(go.Scatterternary({ 'mode': 'markers', 'a': df['sepal_length'], 'b': df['sepal_width'], 'c': df['petal_length'], 'marker': { 'color': 'green', 'size': 14, 'line': {'width': 2} }})) fig.show()", "e": 27553, "s": 27222, "text": null }, { "code": null, "e": 27561, "s": 27553, "text": "Output:" }, { "code": null, "e": 27575, "s": 27561, "text": "Python-Plotly" }, { "code": null, "e": 27582, "s": 27575, "text": "Python" }, { "code": null, "e": 27680, "s": 27582, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27708, "s": 27680, "text": "Read JSON file using Python" }, { "code": null, "e": 27758, "s": 27708, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27780, "s": 27758, "text": "Python map() function" }, { "code": null, "e": 27824, "s": 27780, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 27842, "s": 27824, "text": "Python Dictionary" }, { "code": null, "e": 27865, "s": 27842, "text": "Taking input in Python" }, { "code": null, "e": 27900, "s": 27865, "text": "Read a file line by line in Python" }, { "code": null, "e": 27932, "s": 27900, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27954, "s": 27932, "text": "Enumerate() in Python" } ]
Count of all cycles without any inner cycle in a given Graph - GeeksforGeeks
26 May, 2021 Given an undirected graph consisting of N vertices numbered [0, N-1] and E edges, the task is to count the number of cycles such that any subset of vertices of a cycle does not form another cycle.Examples: Input: N = 2, E = 2, edges = [{0, 1}, {1, 0}] Output: 1 Explanation: Only one cycle exists between the two vertices. Input: N = 6, E = 9, edges = [{0, 1}, {1, 2}, {0, 2}, {3, 0}, {3, 2}, {4, 1}, {4, 2}, {5, 1}, {5, 0}] Output: 4 Explanation: The possible cycles are shown in the diagram below: Cycles such as 5 -> 0 -> 2 -> 1 -> 5 are not considered as it comprises of inner cycles {5 -> 0 -> 1} and {0 -> 1 -> 2} Approach: Since V vertices require V edges to form 1 cycle, the number of required cycles can be expressed using the formula: (Edges - Vertices) + 1 Illustration: N = 6, E = 9, edges = [{0, 1}, {1, 2}, {0, 2}, {3, 0}, {3, 2}, {4, 1}, {4, 2}, {5, 1}, {5, 0}] Number of Cycles = 9 – 6 + 1 = 4 The 4 cycles in the graph are: {5, 0, 1}, {0, 1, 2}, {3, 0, 2} and {1, 2, 4} This formula also covers the case when a single vertex may have a self-loop. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation for the// above approach. #include <bits/stdc++.h>using namespace std; // Function to return the// count of required cyclesint numberOfCycles(int N, int E, int edges[][2]){ vector<int> graph[N]; for (int i = 0; i < E; i++) { graph[edges[i][0]] .push_back(edges[i][1]); graph[edges[i][1]] .push_back(edges[i][0]); } // Return the number of cycles return (E - N) + 1;} // Driver Codeint main(){ int N = 6; int E = 9; int edges[][2] = { { 0, 1 }, { 1, 2 }, { 2, 0 }, { 5, 1 }, { 5, 0 }, { 3, 0 }, { 3, 2 }, { 4, 2 }, { 4, 1 } }; int k = numberOfCycles(N, E, edges); cout << k << endl; return 0;} // Java implementation for the// above approach.import java.util.*; class GFG{ // Function to return the// count of required cyclesstatic int numberOfCycles(int N, int E, int edges[][]){ @SuppressWarnings("unchecked") Vector<Integer> []graph = new Vector[N]; for(int i = 0; i < N; i++) graph[i] = new Vector<Integer>(); for(int i = 0; i < E; i++) { graph[edges[i][0]].add(edges[i][1]); graph[edges[i][1]].add(edges[i][0]); } // Return the number of cycles return (E - N) + 1;} // Driver Codepublic static void main(String[] args){ int N = 6; int E = 9; int edges[][] = { { 0, 1 }, { 1, 2 }, { 2, 0 }, { 5, 1 }, { 5, 0 }, { 3, 0 }, { 3, 2 }, { 4, 2 }, { 4, 1 } }; int k = numberOfCycles(N, E, edges); System.out.print(k + "\n");}} // This code is contributed by Amit Katiyar # Python3 implementation for the# above approach. # Function to return the# count of required cyclesdef numberOfCycles(N, E, edges): graph=[[] for i in range(N)] for i in range(E): graph[edges[i][0]].append(edges[i][1]); graph[edges[i][1]].append(edges[i][0]); # Return the number of cycles return (E - N) + 1; # Driver Codeif __name__=='__main__': N = 6; E = 9; edges = [ [ 0, 1 ], [ 1, 2 ], [ 2, 0 ], [ 5, 1 ], [ 5, 0 ], [ 3, 0 ], [ 3, 2 ], [ 4, 2 ], [ 4, 1 ] ]; k = numberOfCycles(N, E,edges); print(k) # This code is contributed by rutvik_56 // C# implementation for the// above approach.using System;using System.Collections.Generic;class GFG{ // Function to return the// count of required cyclesstatic int numberOfCycles(int N, int E, int [,]edges){ List<int> []graph = new List<int>[N]; for(int i = 0; i < N; i++) graph[i] = new List<int>(); for(int i = 0; i < E; i++) { graph[edges[i, 0]].Add(edges[i, 1]); graph[edges[i, 1]].Add(edges[i, 0]); } // Return the number of cycles return (E - N) + 1;} // Driver Codepublic static void Main(String[] args){ int N = 6; int E = 9; int [,]edges = { { 0, 1 }, { 1, 2 }, { 2, 0 }, { 5, 1 }, { 5, 0 }, { 3, 0 }, { 3, 2 }, { 4, 2 }, { 4, 1 } }; int k = numberOfCycles(N, E, edges); Console.Write(k + "\n");}} // This code is contributed by Rohit_ranjan <script> // JavaScript implementation for the// above approach. // Function to return the// count of required cyclesfunction numberOfCycles(N, E, edges){ var graph = Array.from(Array(N), ()=> Array()); for (var i = 0; i < E; i++) { graph[edges[i][0]] .push(edges[i][1]); graph[edges[i][1]] .push(edges[i][0]); } // Return the number of cycles return (E - N) + 1;} // Driver Codevar N = 6;var E = 9;var edges = [ [ 0, 1 ], [ 1, 2 ], [ 2, 0 ], [ 5, 1 ], [ 5, 0 ], [ 3, 0 ], [ 3, 2 ], [ 4, 2 ], [ 4, 1 ] ]; var k = numberOfCycles(N, E, edges);document.write( k); </script> 4 Time Complexity: O(E) Auxiliary Space: O(N) amit143katiyar Rohit_ranjan rutvik_56 itsok graph-cycle Data Structures Graph Data Structures Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Start Learning DSA? Introduction to Tree Data Structure Program to implement Singly Linked List in C++ using class Hash Functions and list/types of Hash functions Insertion in a B+ tree Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
[ { "code": null, "e": 26273, "s": 26245, "text": "\n26 May, 2021" }, { "code": null, "e": 26481, "s": 26273, "text": "Given an undirected graph consisting of N vertices numbered [0, N-1] and E edges, the task is to count the number of cycles such that any subset of vertices of a cycle does not form another cycle.Examples: " }, { "code": null, "e": 26600, "s": 26481, "text": "Input: N = 2, E = 2, edges = [{0, 1}, {1, 0}] Output: 1 Explanation: Only one cycle exists between the two vertices. " }, { "code": null, "e": 26779, "s": 26600, "text": "Input: N = 6, E = 9, edges = [{0, 1}, {1, 2}, {0, 2}, {3, 0}, {3, 2}, {4, 1}, {4, 2}, {5, 1}, {5, 0}] Output: 4 Explanation: The possible cycles are shown in the diagram below: " }, { "code": null, "e": 26901, "s": 26779, "text": "Cycles such as 5 -> 0 -> 2 -> 1 -> 5 are not considered as it comprises of inner cycles {5 -> 0 -> 1} and {0 -> 1 -> 2} " }, { "code": null, "e": 27029, "s": 26901, "text": "Approach: Since V vertices require V edges to form 1 cycle, the number of required cycles can be expressed using the formula: " }, { "code": null, "e": 27052, "s": 27029, "text": "(Edges - Vertices) + 1" }, { "code": null, "e": 27068, "s": 27052, "text": "Illustration: " }, { "code": null, "e": 27275, "s": 27068, "text": "N = 6, E = 9, edges = [{0, 1}, {1, 2}, {0, 2}, {3, 0}, {3, 2}, {4, 1}, {4, 2}, {5, 1}, {5, 0}] Number of Cycles = 9 – 6 + 1 = 4 The 4 cycles in the graph are: {5, 0, 1}, {0, 1, 2}, {3, 0, 2} and {1, 2, 4} " }, { "code": null, "e": 27405, "s": 27275, "text": "This formula also covers the case when a single vertex may have a self-loop. Below is the implementation of the above approach: " }, { "code": null, "e": 27409, "s": 27405, "text": "C++" }, { "code": null, "e": 27414, "s": 27409, "text": "Java" }, { "code": null, "e": 27422, "s": 27414, "text": "Python3" }, { "code": null, "e": 27425, "s": 27422, "text": "C#" }, { "code": null, "e": 27436, "s": 27425, "text": "Javascript" }, { "code": "// C++ implementation for the// above approach. #include <bits/stdc++.h>using namespace std; // Function to return the// count of required cyclesint numberOfCycles(int N, int E, int edges[][2]){ vector<int> graph[N]; for (int i = 0; i < E; i++) { graph[edges[i][0]] .push_back(edges[i][1]); graph[edges[i][1]] .push_back(edges[i][0]); } // Return the number of cycles return (E - N) + 1;} // Driver Codeint main(){ int N = 6; int E = 9; int edges[][2] = { { 0, 1 }, { 1, 2 }, { 2, 0 }, { 5, 1 }, { 5, 0 }, { 3, 0 }, { 3, 2 }, { 4, 2 }, { 4, 1 } }; int k = numberOfCycles(N, E, edges); cout << k << endl; return 0;}", "e": 28342, "s": 27436, "text": null }, { "code": "// Java implementation for the// above approach.import java.util.*; class GFG{ // Function to return the// count of required cyclesstatic int numberOfCycles(int N, int E, int edges[][]){ @SuppressWarnings(\"unchecked\") Vector<Integer> []graph = new Vector[N]; for(int i = 0; i < N; i++) graph[i] = new Vector<Integer>(); for(int i = 0; i < E; i++) { graph[edges[i][0]].add(edges[i][1]); graph[edges[i][1]].add(edges[i][0]); } // Return the number of cycles return (E - N) + 1;} // Driver Codepublic static void main(String[] args){ int N = 6; int E = 9; int edges[][] = { { 0, 1 }, { 1, 2 }, { 2, 0 }, { 5, 1 }, { 5, 0 }, { 3, 0 }, { 3, 2 }, { 4, 2 }, { 4, 1 } }; int k = numberOfCycles(N, E, edges); System.out.print(k + \"\\n\");}} // This code is contributed by Amit Katiyar", "e": 29403, "s": 28342, "text": null }, { "code": "# Python3 implementation for the# above approach. # Function to return the# count of required cyclesdef numberOfCycles(N, E, edges): graph=[[] for i in range(N)] for i in range(E): graph[edges[i][0]].append(edges[i][1]); graph[edges[i][1]].append(edges[i][0]); # Return the number of cycles return (E - N) + 1; # Driver Codeif __name__=='__main__': N = 6; E = 9; edges = [ [ 0, 1 ], [ 1, 2 ], [ 2, 0 ], [ 5, 1 ], [ 5, 0 ], [ 3, 0 ], [ 3, 2 ], [ 4, 2 ], [ 4, 1 ] ]; k = numberOfCycles(N, E,edges); print(k) # This code is contributed by rutvik_56", "e": 30199, "s": 29403, "text": null }, { "code": "// C# implementation for the// above approach.using System;using System.Collections.Generic;class GFG{ // Function to return the// count of required cyclesstatic int numberOfCycles(int N, int E, int [,]edges){ List<int> []graph = new List<int>[N]; for(int i = 0; i < N; i++) graph[i] = new List<int>(); for(int i = 0; i < E; i++) { graph[edges[i, 0]].Add(edges[i, 1]); graph[edges[i, 1]].Add(edges[i, 0]); } // Return the number of cycles return (E - N) + 1;} // Driver Codepublic static void Main(String[] args){ int N = 6; int E = 9; int [,]edges = { { 0, 1 }, { 1, 2 }, { 2, 0 }, { 5, 1 }, { 5, 0 }, { 3, 0 }, { 3, 2 }, { 4, 2 }, { 4, 1 } }; int k = numberOfCycles(N, E, edges); Console.Write(k + \"\\n\");}} // This code is contributed by Rohit_ranjan", "e": 31149, "s": 30199, "text": null }, { "code": "<script> // JavaScript implementation for the// above approach. // Function to return the// count of required cyclesfunction numberOfCycles(N, E, edges){ var graph = Array.from(Array(N), ()=> Array()); for (var i = 0; i < E; i++) { graph[edges[i][0]] .push(edges[i][1]); graph[edges[i][1]] .push(edges[i][0]); } // Return the number of cycles return (E - N) + 1;} // Driver Codevar N = 6;var E = 9;var edges = [ [ 0, 1 ], [ 1, 2 ], [ 2, 0 ], [ 5, 1 ], [ 5, 0 ], [ 3, 0 ], [ 3, 2 ], [ 4, 2 ], [ 4, 1 ] ]; var k = numberOfCycles(N, E, edges);document.write( k); </script>", "e": 31956, "s": 31149, "text": null }, { "code": null, "e": 31958, "s": 31956, "text": "4" }, { "code": null, "e": 32005, "s": 31960, "text": "Time Complexity: O(E) Auxiliary Space: O(N) " }, { "code": null, "e": 32020, "s": 32005, "text": "amit143katiyar" }, { "code": null, "e": 32033, "s": 32020, "text": "Rohit_ranjan" }, { "code": null, "e": 32043, "s": 32033, "text": "rutvik_56" }, { "code": null, "e": 32049, "s": 32043, "text": "itsok" }, { "code": null, "e": 32061, "s": 32049, "text": "graph-cycle" }, { "code": null, "e": 32077, "s": 32061, "text": "Data Structures" }, { "code": null, "e": 32083, "s": 32077, "text": "Graph" }, { "code": null, "e": 32099, "s": 32083, "text": "Data Structures" }, { "code": null, "e": 32105, "s": 32099, "text": "Graph" }, { "code": null, "e": 32203, "s": 32105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32230, "s": 32203, "text": "How to Start Learning DSA?" }, { "code": null, "e": 32266, "s": 32230, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 32325, "s": 32266, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 32373, "s": 32325, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 32396, "s": 32373, "text": "Insertion in a B+ tree" }, { "code": null, "e": 32436, "s": 32396, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 32474, "s": 32436, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 32525, "s": 32474, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 32583, "s": 32525, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
JavaScript string.valueOf() Method - GeeksforGeeks
07 Oct, 2021 Below is the example of the string.valueOf() Method. Example: javascript <script> var a = new String("GeeksforGeeks"); document.write(a.valueOf());</script> Output: GeeksforGeeks The string.valueOf() is an inbuilt method in JavaScript which is used to return the value of the given string.Syntax: string.valueOf() Parameters: It does not accept any parameter.Return Values: It returns a string which represent the value of the given string object.JavaScript code to show the working of string.valueOf() method: Program 1: javascript <script> // Taking a string as input and printing it // with the help of string.valueOf() function var a = new String("GeeksforGeeks"); document.write(a.valueOf());</script> Output: GeeksforGeeks Program 2: javascript <script> // Taking a string as input and printing it // with the help of string.valueOf() function var a = new String("Geeks"); var b = new String("for"); var c = new String("Geeks"); document.write(a.valueOf(),b.valueOf(),c.valueOf());</script> Output: GeeksforGeeks Supported Browser: Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 4 and above Opera 3 and above Safari 1 and above ysachin2314 JavaScript-Methods javascript-string JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array 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 append HTML code to a div using JavaScript ? 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": 25717, "s": 25689, "text": "\n07 Oct, 2021" }, { "code": null, "e": 25772, "s": 25717, "text": "Below is the example of the string.valueOf() Method. " }, { "code": null, "e": 25783, "s": 25772, "text": "Example: " }, { "code": null, "e": 25794, "s": 25783, "text": "javascript" }, { "code": "<script> var a = new String(\"GeeksforGeeks\"); document.write(a.valueOf());</script>", "e": 25884, "s": 25794, "text": null }, { "code": null, "e": 25894, "s": 25884, "text": "Output: " }, { "code": null, "e": 25908, "s": 25894, "text": "GeeksforGeeks" }, { "code": null, "e": 26028, "s": 25908, "text": "The string.valueOf() is an inbuilt method in JavaScript which is used to return the value of the given string.Syntax: " }, { "code": null, "e": 26045, "s": 26028, "text": "string.valueOf()" }, { "code": null, "e": 26255, "s": 26045, "text": "Parameters: It does not accept any parameter.Return Values: It returns a string which represent the value of the given string object.JavaScript code to show the working of string.valueOf() method: Program 1: " }, { "code": null, "e": 26266, "s": 26255, "text": "javascript" }, { "code": "<script> // Taking a string as input and printing it // with the help of string.valueOf() function var a = new String(\"GeeksforGeeks\"); document.write(a.valueOf());</script>", "e": 26452, "s": 26266, "text": null }, { "code": null, "e": 26462, "s": 26452, "text": "Output: " }, { "code": null, "e": 26476, "s": 26462, "text": "GeeksforGeeks" }, { "code": null, "e": 26489, "s": 26476, "text": "Program 2: " }, { "code": null, "e": 26500, "s": 26489, "text": "javascript" }, { "code": "<script> // Taking a string as input and printing it // with the help of string.valueOf() function var a = new String(\"Geeks\"); var b = new String(\"for\"); var c = new String(\"Geeks\"); document.write(a.valueOf(),b.valueOf(),c.valueOf());</script>", "e": 26764, "s": 26500, "text": null }, { "code": null, "e": 26774, "s": 26764, "text": "Output: " }, { "code": null, "e": 26788, "s": 26774, "text": "GeeksforGeeks" }, { "code": null, "e": 26809, "s": 26790, "text": "Supported Browser:" }, { "code": null, "e": 26828, "s": 26809, "text": "Chrome 1 and above" }, { "code": null, "e": 26846, "s": 26828, "text": "Edge 12 and above" }, { "code": null, "e": 26866, "s": 26846, "text": "Firefox 1 and above" }, { "code": null, "e": 26896, "s": 26866, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 26914, "s": 26896, "text": "Opera 3 and above" }, { "code": null, "e": 26933, "s": 26914, "text": "Safari 1 and above" }, { "code": null, "e": 26945, "s": 26933, "text": "ysachin2314" }, { "code": null, "e": 26964, "s": 26945, "text": "JavaScript-Methods" }, { "code": null, "e": 26982, "s": 26964, "text": "javascript-string" }, { "code": null, "e": 26993, "s": 26982, "text": "JavaScript" }, { "code": null, "e": 27010, "s": 26993, "text": "Web Technologies" }, { "code": null, "e": 27108, "s": 27010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27148, "s": 27108, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27193, "s": 27148, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27254, "s": 27193, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27326, "s": 27254, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27378, "s": 27326, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27418, "s": 27378, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27451, "s": 27418, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27496, "s": 27451, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27539, "s": 27496, "text": "How to fetch data from an API in ReactJS ?" } ]
Algorithms | Greedy Algorithms | Question 3 - GeeksforGeeks
28 Jun, 2021 A networking company uses a compression technique to encode the message before transmitting over the network. Suppose the message contains the following characters with their frequency: character Frequency a 5 b 9 c 12 d 13 e 16 f 45 Note : Each character in input message takes 1 byte. If the compression technique used is Huffman Coding, how many bits will be saved in the message?(A) 224(B) 800(C) 576(D) 324Answer: (C)Explanation: Total number of characters in the message = 100. Each character takes 1 byte. So total number of bits needed = 800. After Huffman Coding, the characters can be represented with: f: 0 c: 100 d: 101 a: 1100 b: 1101 e: 111 Total number of bits needed = 224 Hence, number of bits saved = 800 - 224 = 576 See here for complete explanation and algorithm. Quiz of this Question Algorithms-Greedy Algorithms Greedy Algorithms Algorithms Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithms | Graph Minimum Spanning Tree | Question 6 Algorithms | Sorting | Question 6 Algorithms | Recursion | Question 2 Algorithms | Sorting | Question 9 Algorithms | Sorting | Question 4 Algorithms | Analysis of Algorithms | Question 19 Algorithms | Sorting | Question 3 Algorithms | Sorting | Question 12 Algorithms | Sorting | Question 13 Algorithms | Backtracking | Question 1
[ { "code": null, "e": 26059, "s": 26031, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26245, "s": 26059, "text": "A networking company uses a compression technique to encode the message before transmitting over the network. Suppose the message contains the following characters with their frequency:" }, { "code": "character Frequency a 5 b 9 c 12 d 13 e 16 f 45", "e": 26374, "s": 26245, "text": null }, { "code": null, "e": 26427, "s": 26374, "text": "Note : Each character in input message takes 1 byte." }, { "code": null, "e": 26575, "s": 26427, "text": "If the compression technique used is Huffman Coding, how many bits will be saved in the message?(A) 224(B) 800(C) 576(D) 324Answer: (C)Explanation:" }, { "code": null, "e": 26927, "s": 26575, "text": "Total number of characters in the message = 100. \nEach character takes 1 byte. So total number of bits needed = 800.\n\nAfter Huffman Coding, the characters can be represented with:\nf: 0\nc: 100\nd: 101\na: 1100\nb: 1101\ne: 111\nTotal number of bits needed = 224\nHence, number of bits saved = 800 - 224 = 576\nSee here for complete explanation and algorithm.\n" }, { "code": null, "e": 26949, "s": 26927, "text": "Quiz of this Question" }, { "code": null, "e": 26978, "s": 26949, "text": "Algorithms-Greedy Algorithms" }, { "code": null, "e": 26996, "s": 26978, "text": "Greedy Algorithms" }, { "code": null, "e": 27012, "s": 26996, "text": "Algorithms Quiz" }, { "code": null, "e": 27110, "s": 27012, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27164, "s": 27110, "text": "Algorithms | Graph Minimum Spanning Tree | Question 6" }, { "code": null, "e": 27198, "s": 27164, "text": "Algorithms | Sorting | Question 6" }, { "code": null, "e": 27234, "s": 27198, "text": "Algorithms | Recursion | Question 2" }, { "code": null, "e": 27268, "s": 27234, "text": "Algorithms | Sorting | Question 9" }, { "code": null, "e": 27302, "s": 27268, "text": "Algorithms | Sorting | Question 4" }, { "code": null, "e": 27352, "s": 27302, "text": "Algorithms | Analysis of Algorithms | Question 19" }, { "code": null, "e": 27386, "s": 27352, "text": "Algorithms | Sorting | Question 3" }, { "code": null, "e": 27421, "s": 27386, "text": "Algorithms | Sorting | Question 12" }, { "code": null, "e": 27456, "s": 27421, "text": "Algorithms | Sorting | Question 13" } ]
How to Fix java.lang.ClassCastException in TreeSet? - GeeksforGeeks
04 Jan, 2021 TreeSet class in Java implements the Set interface that uses a tree for storing elements which contain unique objects stored in the ascending order. You may come across an exception called java.lang.ClassCastException while working with TreeSet objects. Basically, TreeSet elements are ordered using natural ordering or by using the Comparator defined in the constructor. If both don’t happen i.e natural ordering not occurring and also did not provide any comparator then java throws an exception which is java.lang.ClassCastException. Example Java // Java program to demonstrate ClassCastException by TreeSet import java.util.TreeSet; // class which is going to assign// student marksclass Student { int marks; // constructor public Student(int marks) { this.marks = marks; } // override toString() method // for display purpose public String toString() { return "Student marks = " + this.marks; }} // Driver classclass GFG { public static void main(String[] args) { // Declaring Tree Set TreeSet<Student> treeSet = new TreeSet<Student>(); // this line will throw java.lang.ClassCastException treeSet.add(new Student(1)); // Displaying the contents of in treeSet System.out.println(treeSet); }} Output Exception in thread “main” java.lang.ClassCastException: class Student cannot be cast to class java.lang.Comparable (Student is in unnamed module of loader ‘app’; java.lang.Comparable is in module java.base of loader ‘bootstrap’) at java.base/java.util.TreeMap.compare(TreeMap.java:1291) at java.base/java.util.TreeMap.put(TreeMap.java:536) at java.base/java.util.TreeSet.add(TreeSet.java:255) at GFG.main(File.java:31) We can resolve this exception in two ways: By implementing the Comparable interfaceBy defining custom Comparator class By implementing the Comparable interface By defining custom Comparator class Approach 1(Implementing Comparable Interface) Java Comparable interface is implemented by a class by which used to compare and sort the objects according to the natural ordering. Natural ordering is possible using compareTo() function. String objects and wrapper class objects are sorted according to the built-in compareTo() function. If compareTo function returns positive or negative or zero, then the current object is greater, lesser, and equal to the provided object respectively. Example 1: Java // Java program to sort student data// according to marks// using Comparable interface import java.util.TreeSet; // class which is going to assign// student marksclass Student implements Comparable<Student> { int id; String name; int marks; // constructor public Student(int id, String name, int marks) { // assigning values this.id = id; this.name = name; this.marks = marks; } // compareTo method to sort in // ascending order public int compareTo(Student obj) { return this.marks - obj.marks; } // override toString() method // for display purpose public String toString() { return "Id: " + this.id + " Name: " + this.name + " Marks: " + this.marks; }} // Driver classclass GFG { public static void main(String[] args) { // Declaring Tree Set TreeSet<Student> treeSet = new TreeSet<Student>(); treeSet.add(new Student(1, "Suresh", 87)); treeSet.add(new Student(2, "Ramesh", 78)); treeSet.add(new Student(3, "Lokesh", 95)); // Displaying the contents of in treeSet System.out.println(treeSet); }} [Id: 2 Name: Ramesh Marks: 78, Id: 1 Name: Suresh Marks: 87, Id: 3 Name: Lokesh Marks: 95] Approach 2(Using Custom Comparator class) A comparator is an interface that has to implemented by the class by which we can sort the objects of the user-defined class. It has 2 main methods that are used widely, compare(T o1, T o2) and equals(Object obj) which returns an int and boolean respectively. Let us implement the same example using a comparator. Java // Java program to sort student data// according to marks using custom class// which implements Comparator // comparator interface present in// java.util packageimport java.util.*;// class which is going to assign// student marksclass Student { int id; String name; int marks; // constructor public Student(int id, String name, int marks) { // assigning values this.id = id; this.name = name; this.marks = marks; } // method to return // current marks of student public int getMarks() { return this.marks; } // override toString() method // for display purpose public String toString() { return "Id: " + this.id + " Name: " + this.name + " Marks: " + this.marks; }} // StuComparator class will compare// objects ans sorts in// ascending orderclass StuComparator implements Comparator<Student> { // defining compare method public int compare(Student obj1, Student obj2) { return obj1.getMarks() - obj2.getMarks(); }} // Driver classclass GFG { public static void main(String[] args) { // Declaring Tree Set TreeSet<Student> treeSet = new TreeSet<Student>(new StuComparator()); treeSet.add(new Student(1, "Suresh", 87)); treeSet.add(new Student(2, "Ramesh", 78)); treeSet.add(new Student(3, "Lokesh", 95)); // Displaying the contents of in treeSet System.out.println(treeSet); }} [Id: 2 Name: Ramesh Marks: 78, Id: 1 Name: Suresh Marks: 87, Id: 3 Name: Lokesh Marks: 95] java-treeset Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n04 Jan, 2021" }, { "code": null, "e": 25762, "s": 25225, "text": "TreeSet class in Java implements the Set interface that uses a tree for storing elements which contain unique objects stored in the ascending order. You may come across an exception called java.lang.ClassCastException while working with TreeSet objects. Basically, TreeSet elements are ordered using natural ordering or by using the Comparator defined in the constructor. If both don’t happen i.e natural ordering not occurring and also did not provide any comparator then java throws an exception which is java.lang.ClassCastException." }, { "code": null, "e": 25770, "s": 25762, "text": "Example" }, { "code": null, "e": 25775, "s": 25770, "text": "Java" }, { "code": "// Java program to demonstrate ClassCastException by TreeSet import java.util.TreeSet; // class which is going to assign// student marksclass Student { int marks; // constructor public Student(int marks) { this.marks = marks; } // override toString() method // for display purpose public String toString() { return \"Student marks = \" + this.marks; }} // Driver classclass GFG { public static void main(String[] args) { // Declaring Tree Set TreeSet<Student> treeSet = new TreeSet<Student>(); // this line will throw java.lang.ClassCastException treeSet.add(new Student(1)); // Displaying the contents of in treeSet System.out.println(treeSet); }}", "e": 26519, "s": 25775, "text": null }, { "code": null, "e": 26526, "s": 26519, "text": "Output" }, { "code": null, "e": 26756, "s": 26526, "text": "Exception in thread “main” java.lang.ClassCastException: class Student cannot be cast to class java.lang.Comparable (Student is in unnamed module of loader ‘app’; java.lang.Comparable is in module java.base of loader ‘bootstrap’)" }, { "code": null, "e": 26814, "s": 26756, "text": "at java.base/java.util.TreeMap.compare(TreeMap.java:1291)" }, { "code": null, "e": 26867, "s": 26814, "text": "at java.base/java.util.TreeMap.put(TreeMap.java:536)" }, { "code": null, "e": 26920, "s": 26867, "text": "at java.base/java.util.TreeSet.add(TreeSet.java:255)" }, { "code": null, "e": 26946, "s": 26920, "text": "at GFG.main(File.java:31)" }, { "code": null, "e": 26989, "s": 26946, "text": "We can resolve this exception in two ways:" }, { "code": null, "e": 27065, "s": 26989, "text": "By implementing the Comparable interfaceBy defining custom Comparator class" }, { "code": null, "e": 27106, "s": 27065, "text": "By implementing the Comparable interface" }, { "code": null, "e": 27142, "s": 27106, "text": "By defining custom Comparator class" }, { "code": null, "e": 27188, "s": 27142, "text": "Approach 1(Implementing Comparable Interface)" }, { "code": null, "e": 27478, "s": 27188, "text": "Java Comparable interface is implemented by a class by which used to compare and sort the objects according to the natural ordering. Natural ordering is possible using compareTo() function. String objects and wrapper class objects are sorted according to the built-in compareTo() function." }, { "code": null, "e": 27629, "s": 27478, "text": "If compareTo function returns positive or negative or zero, then the current object is greater, lesser, and equal to the provided object respectively." }, { "code": null, "e": 27642, "s": 27629, "text": "Example 1: " }, { "code": null, "e": 27647, "s": 27642, "text": "Java" }, { "code": "// Java program to sort student data// according to marks// using Comparable interface import java.util.TreeSet; // class which is going to assign// student marksclass Student implements Comparable<Student> { int id; String name; int marks; // constructor public Student(int id, String name, int marks) { // assigning values this.id = id; this.name = name; this.marks = marks; } // compareTo method to sort in // ascending order public int compareTo(Student obj) { return this.marks - obj.marks; } // override toString() method // for display purpose public String toString() { return \"Id: \" + this.id + \" Name: \" + this.name + \" Marks: \" + this.marks; }} // Driver classclass GFG { public static void main(String[] args) { // Declaring Tree Set TreeSet<Student> treeSet = new TreeSet<Student>(); treeSet.add(new Student(1, \"Suresh\", 87)); treeSet.add(new Student(2, \"Ramesh\", 78)); treeSet.add(new Student(3, \"Lokesh\", 95)); // Displaying the contents of in treeSet System.out.println(treeSet); }}", "e": 28827, "s": 27647, "text": null }, { "code": null, "e": 28918, "s": 28827, "text": "[Id: 2 Name: Ramesh Marks: 78, Id: 1 Name: Suresh Marks: 87, Id: 3 Name: Lokesh Marks: 95]" }, { "code": null, "e": 28961, "s": 28918, "text": " Approach 2(Using Custom Comparator class)" }, { "code": null, "e": 29275, "s": 28961, "text": "A comparator is an interface that has to implemented by the class by which we can sort the objects of the user-defined class. It has 2 main methods that are used widely, compare(T o1, T o2) and equals(Object obj) which returns an int and boolean respectively. Let us implement the same example using a comparator." }, { "code": null, "e": 29280, "s": 29275, "text": "Java" }, { "code": "// Java program to sort student data// according to marks using custom class// which implements Comparator // comparator interface present in// java.util packageimport java.util.*;// class which is going to assign// student marksclass Student { int id; String name; int marks; // constructor public Student(int id, String name, int marks) { // assigning values this.id = id; this.name = name; this.marks = marks; } // method to return // current marks of student public int getMarks() { return this.marks; } // override toString() method // for display purpose public String toString() { return \"Id: \" + this.id + \" Name: \" + this.name + \" Marks: \" + this.marks; }} // StuComparator class will compare// objects ans sorts in// ascending orderclass StuComparator implements Comparator<Student> { // defining compare method public int compare(Student obj1, Student obj2) { return obj1.getMarks() - obj2.getMarks(); }} // Driver classclass GFG { public static void main(String[] args) { // Declaring Tree Set TreeSet<Student> treeSet = new TreeSet<Student>(new StuComparator()); treeSet.add(new Student(1, \"Suresh\", 87)); treeSet.add(new Student(2, \"Ramesh\", 78)); treeSet.add(new Student(3, \"Lokesh\", 95)); // Displaying the contents of in treeSet System.out.println(treeSet); }}", "e": 30758, "s": 29280, "text": null }, { "code": null, "e": 30849, "s": 30758, "text": "[Id: 2 Name: Ramesh Marks: 78, Id: 1 Name: Suresh Marks: 87, Id: 3 Name: Lokesh Marks: 95]" }, { "code": null, "e": 30862, "s": 30849, "text": "java-treeset" }, { "code": null, "e": 30869, "s": 30862, "text": "Picked" }, { "code": null, "e": 30893, "s": 30869, "text": "Technical Scripter 2020" }, { "code": null, "e": 30898, "s": 30893, "text": "Java" }, { "code": null, "e": 30912, "s": 30898, "text": "Java Programs" }, { "code": null, "e": 30931, "s": 30912, "text": "Technical Scripter" }, { "code": null, "e": 30936, "s": 30931, "text": "Java" }, { "code": null, "e": 31034, "s": 30936, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31049, "s": 31034, "text": "Stream In Java" }, { "code": null, "e": 31070, "s": 31049, "text": "Constructors in Java" }, { "code": null, "e": 31089, "s": 31070, "text": "Exceptions in Java" }, { "code": null, "e": 31119, "s": 31089, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31165, "s": 31119, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 31191, "s": 31165, "text": "Java Programming Examples" }, { "code": null, "e": 31225, "s": 31191, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 31272, "s": 31225, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 31304, "s": 31272, "text": "How to Iterate HashMap in Java?" } ]
How to LEFT ANTI join under some matching condition in Pandas - GeeksforGeeks
19 Dec, 2021 LEFT ANTI Join is the opposite of semi-join. excluding the intersection, it returns the left table. It only returns the columns from the left table and not the right. On the created dataframes we perform left join and subset using isin() function to check if the part on which the datasets are merged is in the subset of the merged dataset. Syntax: DataFrame.isin(values) Parameters: values: iterable, Series, DataFrame or dict Returns: DataFrame Example: In the below code, we used the indicator to find the rows which are ‘Left_only’ and subset the merged dataset, and assign it to df. finally, we retrieve the part which is only in our first data frame df1. the output is antijoin of the two data frames. Python3 # importing packagesimport pandas as pd # anti-join# creating dataframes using pd.DataFrame() method.df1 = pd.DataFrame({ "city": ["new york", "chicago", "orlando", 'mumbai'], "temperature": [21, 14, 35, 30], "humidity": [65, 68, 75, 75],})df2 = pd.DataFrame({ "city": ["chicago", "new york", "orlando"], "humidity": [67, 60, 70]}) # carrying out anti join using merge methoddf3 = df1.merge(df2, on='city', how='left', indicator=True) df = df3.loc[df3['_merge'] == 'left_only', 'city'] d = df1[df1['city'].isin(df)] print(d) Output: city temperature humidity 3 mumbai 30 75 We can use the ‘~’ operator on the semi-join. It results in anti-join. Semi-join: Similar to inner join, semi-join returns the intersection but it only returns the columns from the left table and not the right. it has no duplicate values. Syntax: [~df1[‘column_name’].isin(df2[‘column_name’])] where, df1 is the first dataframe df2 is the second dataframe column_name is the matching column in both the dataframes Example: In this example, we merge df1 and df2 on ‘city’ by default it is ‘inner join’, after merging, We exclude the part of df1 which is in df3 and print out the resultant dataframe. Python3 # codeimport pandas as pd # inverse of semi-join:# creating dataframes using pd.DataFrame() method.df1 = pd.DataFrame({ "city": ["new york", "chicago", "orlando", 'mumbai'], "temperature": [21, 14, 35, 30], "humidity": [65, 68, 75, 75],})df2 = pd.DataFrame({ "city": ["chicago", "new york", "orlando"], "humidity": [67, 60, 70]}) # carrying out anti join using merge methoddf3 = df1.merge(df2, on='city') df = df1[~df1['city'].isin(df3['city'])] print(df) Output: city temperature humidity 3 mumbai 30 75 Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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": "\n19 Dec, 2021" }, { "code": null, "e": 25704, "s": 25537, "text": "LEFT ANTI Join is the opposite of semi-join. excluding the intersection, it returns the left table. It only returns the columns from the left table and not the right." }, { "code": null, "e": 25878, "s": 25704, "text": "On the created dataframes we perform left join and subset using isin() function to check if the part on which the datasets are merged is in the subset of the merged dataset." }, { "code": null, "e": 25886, "s": 25878, "text": "Syntax:" }, { "code": null, "e": 25909, "s": 25886, "text": "DataFrame.isin(values)" }, { "code": null, "e": 25922, "s": 25909, "text": "Parameters: " }, { "code": null, "e": 25966, "s": 25922, "text": "values: iterable, Series, DataFrame or dict" }, { "code": null, "e": 25976, "s": 25966, "text": "Returns: " }, { "code": null, "e": 25986, "s": 25976, "text": "DataFrame" }, { "code": null, "e": 25995, "s": 25986, "text": "Example:" }, { "code": null, "e": 26247, "s": 25995, "text": "In the below code, we used the indicator to find the rows which are ‘Left_only’ and subset the merged dataset, and assign it to df. finally, we retrieve the part which is only in our first data frame df1. the output is antijoin of the two data frames." }, { "code": null, "e": 26255, "s": 26247, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # anti-join# creating dataframes using pd.DataFrame() method.df1 = pd.DataFrame({ \"city\": [\"new york\", \"chicago\", \"orlando\", 'mumbai'], \"temperature\": [21, 14, 35, 30], \"humidity\": [65, 68, 75, 75],})df2 = pd.DataFrame({ \"city\": [\"chicago\", \"new york\", \"orlando\"], \"humidity\": [67, 60, 70]}) # carrying out anti join using merge methoddf3 = df1.merge(df2, on='city', how='left', indicator=True) df = df3.loc[df3['_merge'] == 'left_only', 'city'] d = df1[df1['city'].isin(df)] print(d)", "e": 26800, "s": 26255, "text": null }, { "code": null, "e": 26808, "s": 26800, "text": "Output:" }, { "code": null, "e": 26874, "s": 26808, "text": " city temperature humidity\n3 mumbai 30 75" }, { "code": null, "e": 26946, "s": 26874, "text": "We can use the ‘~’ operator on the semi-join. It results in anti-join. " }, { "code": null, "e": 27115, "s": 26946, "text": "Semi-join: Similar to inner join, semi-join returns the intersection but it only returns the columns from the left table and not the right. it has no duplicate values. " }, { "code": null, "e": 27123, "s": 27115, "text": "Syntax:" }, { "code": null, "e": 27170, "s": 27123, "text": "[~df1[‘column_name’].isin(df2[‘column_name’])]" }, { "code": null, "e": 27178, "s": 27170, "text": "where, " }, { "code": null, "e": 27205, "s": 27178, "text": "df1 is the first dataframe" }, { "code": null, "e": 27233, "s": 27205, "text": "df2 is the second dataframe" }, { "code": null, "e": 27291, "s": 27233, "text": "column_name is the matching column in both the dataframes" }, { "code": null, "e": 27300, "s": 27291, "text": "Example:" }, { "code": null, "e": 27478, "s": 27300, "text": "In this example, we merge df1 and df2 on ‘city’ by default it is ‘inner join’, after merging, We exclude the part of df1 which is in df3 and print out the resultant dataframe. " }, { "code": null, "e": 27486, "s": 27478, "text": "Python3" }, { "code": "# codeimport pandas as pd # inverse of semi-join:# creating dataframes using pd.DataFrame() method.df1 = pd.DataFrame({ \"city\": [\"new york\", \"chicago\", \"orlando\", 'mumbai'], \"temperature\": [21, 14, 35, 30], \"humidity\": [65, 68, 75, 75],})df2 = pd.DataFrame({ \"city\": [\"chicago\", \"new york\", \"orlando\"], \"humidity\": [67, 60, 70]}) # carrying out anti join using merge methoddf3 = df1.merge(df2, on='city') df = df1[~df1['city'].isin(df3['city'])] print(df)", "e": 27961, "s": 27486, "text": null }, { "code": null, "e": 27969, "s": 27961, "text": "Output:" }, { "code": null, "e": 28035, "s": 27969, "text": " city temperature humidity\n3 mumbai 30 75" }, { "code": null, "e": 28042, "s": 28035, "text": "Picked" }, { "code": null, "e": 28066, "s": 28042, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28080, "s": 28066, "text": "Python-pandas" }, { "code": null, "e": 28087, "s": 28080, "text": "Python" }, { "code": null, "e": 28185, "s": 28087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28217, "s": 28185, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28259, "s": 28217, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28301, "s": 28259, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28328, "s": 28301, "text": "Python Classes and Objects" }, { "code": null, "e": 28384, "s": 28328, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28406, "s": 28384, "text": "Defaultdict in Python" }, { "code": null, "e": 28445, "s": 28406, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28476, "s": 28445, "text": "Python | os.path.join() method" }, { "code": null, "e": 28505, "s": 28476, "text": "Create a directory in Python" } ]
How to Exit a Python script? - GeeksforGeeks
03 Jan, 2021 Exiting a Python script refers to the process of termination of an active python process. In a more practical way, it is generally a call to a function (or destructor) exit routines of the program. This process is done implicitly every time a python script completes execution (or runs out of executable code), but could also be invoked by using certain functions. In this article we will take a look at exiting a python program, performing a task before exiting the program, and exiting the program while displaying a custom (error) message. There exist several ways of exiting a python application. The following article has explained some of them in great detail. A thorough read of it would educate the users on when to use which method, and which one is the most suitable for their particular use case. In general, their functionality is more or less the same which is to exit the python program. Some functions do that properly (calling cleanup routines, flushing buffers, closing file objects, etc.) and others do it brutally (without the aforementioned steps). It is often better to use in-built methods because they are just required to be called where ever needed. Example: Python3 print("this is the first statement") exit() print("this is the second statement") Output: this is the first statement Sometimes it is required to perform certain tasks before the python script is terminated. For that, it is required to detect when the script is about to exit. atexit is a module that is used for performing this very task. The module is used for defining functions to register and unregister cleanup functions. Cleanup functions are called after the code has executed. The default cleanup functions are used for cleaning residue created by the code execution, but we would be using it to execute our custom code. In the following code we would be defining (and registering) a function that would be called upon the termination of the program. First, the atexit module is imported. Then exit_handler() function is defined. This function contains a print statement. Later this function is registered by passing the function object to the atexit.register() function. In the end, there is a call to print function for displaying GFG! in the output. In the output the first line is the output of the last print statement in the code. The second line contains the output of exit_handler function that is called upon the code execution (as a cleanup function). Not all kinds of exits are handled by the atexit module. Example: Python3 import atexit def exit_handler(): print('My application is ending!') atexit.register(exit_handler) print('GFG!') Output: GFG My application is ending! Sometimes we are interested just in the execution or termination of the program rather than any errors encountered therein. This is possible if we are able to catch any exceptions or errors that are encountered during the execution. This is made possible by utilizing the except: clause found inside a generic try-except block. We would be making use of the fact that a bare except can catch not only exceptions but even certain interrupts and errors encountered during the execution of the try block. A bare except clause is generally not advisable in practical code. The reason is that it conceals several types of errors produced during the code as well. This behavior may make debugging the code a little hectic. Therefore, it should be used with caution and only when the code in try clause isn’t error prone (which isn’t a plausible assumption in most cases). Example: Python3 def main(): asdfgh print("HELLO WORLD!") if __name__ == "__main__": try: main() except: print("Gotcha!") Output: Gotcha! Generally, when a python program encounters an error it displays it on the console screen. But sometimes we are interested in exiting the application while displaying some text denoting a possible error which might have occurred. This process could also be used to exit the program and display some text at the end. In the following code we will be exiting the python program after displaying some text. Here a string or an integer could be provided as an argument to the exit() function. If the argument is a string (denoting an error msg etc), then it will be outputted after program execution. If it is an integer then it should be an POSIX exit code. Example: Python3 print("Hello world!") exit("__PUT_ERROR_MSG_HERE__") Output: Hello world! __PUT_ERROR_MSG_HERE__ Picked python-basics 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? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n03 Jan, 2021" }, { "code": null, "e": 26080, "s": 25537, "text": "Exiting a Python script refers to the process of termination of an active python process. In a more practical way, it is generally a call to a function (or destructor) exit routines of the program. This process is done implicitly every time a python script completes execution (or runs out of executable code), but could also be invoked by using certain functions. In this article we will take a look at exiting a python program, performing a task before exiting the program, and exiting the program while displaying a custom (error) message." }, { "code": null, "e": 26712, "s": 26080, "text": "There exist several ways of exiting a python application. The following article has explained some of them in great detail. A thorough read of it would educate the users on when to use which method, and which one is the most suitable for their particular use case. In general, their functionality is more or less the same which is to exit the python program. Some functions do that properly (calling cleanup routines, flushing buffers, closing file objects, etc.) and others do it brutally (without the aforementioned steps). It is often better to use in-built methods because they are just required to be called where ever needed." }, { "code": null, "e": 26721, "s": 26712, "text": "Example:" }, { "code": null, "e": 26729, "s": 26721, "text": "Python3" }, { "code": "print(\"this is the first statement\") exit() print(\"this is the second statement\")", "e": 26813, "s": 26729, "text": null }, { "code": null, "e": 26821, "s": 26813, "text": "Output:" }, { "code": null, "e": 26849, "s": 26821, "text": "this is the first statement" }, { "code": null, "e": 27364, "s": 26849, "text": "Sometimes it is required to perform certain tasks before the python script is terminated. For that, it is required to detect when the script is about to exit. atexit is a module that is used for performing this very task. The module is used for defining functions to register and unregister cleanup functions. Cleanup functions are called after the code has executed. The default cleanup functions are used for cleaning residue created by the code execution, but we would be using it to execute our custom code. " }, { "code": null, "e": 28007, "s": 27364, "text": "In the following code we would be defining (and registering) a function that would be called upon the termination of the program. First, the atexit module is imported. Then exit_handler() function is defined. This function contains a print statement. Later this function is registered by passing the function object to the atexit.register() function. In the end, there is a call to print function for displaying GFG! in the output. In the output the first line is the output of the last print statement in the code. The second line contains the output of exit_handler function that is called upon the code execution (as a cleanup function). " }, { "code": null, "e": 28066, "s": 28007, "text": "Not all kinds of exits are handled by the atexit module. " }, { "code": null, "e": 28075, "s": 28066, "text": "Example:" }, { "code": null, "e": 28083, "s": 28075, "text": "Python3" }, { "code": "import atexit def exit_handler(): print('My application is ending!') atexit.register(exit_handler) print('GFG!')", "e": 28206, "s": 28083, "text": null }, { "code": null, "e": 28214, "s": 28206, "text": "Output:" }, { "code": null, "e": 28244, "s": 28214, "text": "GFG\nMy application is ending!" }, { "code": null, "e": 28748, "s": 28244, "text": "Sometimes we are interested just in the execution or termination of the program rather than any errors encountered therein. This is possible if we are able to catch any exceptions or errors that are encountered during the execution. This is made possible by utilizing the except: clause found inside a generic try-except block. We would be making use of the fact that a bare except can catch not only exceptions but even certain interrupts and errors encountered during the execution of the try block. " }, { "code": null, "e": 29113, "s": 28748, "text": "A bare except clause is generally not advisable in practical code. The reason is that it conceals several types of errors produced during the code as well. This behavior may make debugging the code a little hectic. Therefore, it should be used with caution and only when the code in try clause isn’t error prone (which isn’t a plausible assumption in most cases). " }, { "code": null, "e": 29122, "s": 29113, "text": "Example:" }, { "code": null, "e": 29130, "s": 29122, "text": "Python3" }, { "code": "def main(): asdfgh print(\"HELLO WORLD!\") if __name__ == \"__main__\": try: main() except: print(\"Gotcha!\")", "e": 29266, "s": 29130, "text": null }, { "code": null, "e": 29274, "s": 29266, "text": "Output:" }, { "code": null, "e": 29282, "s": 29274, "text": "Gotcha!" }, { "code": null, "e": 29687, "s": 29282, "text": "Generally, when a python program encounters an error it displays it on the console screen. But sometimes we are interested in exiting the application while displaying some text denoting a possible error which might have occurred. This process could also be used to exit the program and display some text at the end. In the following code we will be exiting the python program after displaying some text." }, { "code": null, "e": 29941, "s": 29687, "text": "Here a string or an integer could be provided as an argument to the exit() function. If the argument is a string (denoting an error msg etc), then it will be outputted after program execution. If it is an integer then it should be an POSIX exit code. " }, { "code": null, "e": 29950, "s": 29941, "text": "Example:" }, { "code": null, "e": 29958, "s": 29950, "text": "Python3" }, { "code": "print(\"Hello world!\") exit(\"__PUT_ERROR_MSG_HERE__\")", "e": 30012, "s": 29958, "text": null }, { "code": null, "e": 30020, "s": 30012, "text": "Output:" }, { "code": null, "e": 30056, "s": 30020, "text": "Hello world!\n__PUT_ERROR_MSG_HERE__" }, { "code": null, "e": 30063, "s": 30056, "text": "Picked" }, { "code": null, "e": 30077, "s": 30063, "text": "python-basics" }, { "code": null, "e": 30084, "s": 30077, "text": "Python" }, { "code": null, "e": 30182, "s": 30084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30214, "s": 30182, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30256, "s": 30214, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30298, "s": 30256, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30354, "s": 30298, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30381, "s": 30354, "text": "Python Classes and Objects" }, { "code": null, "e": 30420, "s": 30381, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30451, "s": 30420, "text": "Python | os.path.join() method" }, { "code": null, "e": 30480, "s": 30451, "text": "Create a directory in Python" }, { "code": null, "e": 30502, "s": 30480, "text": "Defaultdict in Python" } ]
HTML abbr Tag - GeeksforGeeks
24 Mar, 2022 The <abbr> tag(Abbreviation) in HTML is used to define the abbreviation or short form of an element. The <abbr> and <acronym> tags are used as shortened versions and used to represent a series of letters. The abbreviation is used to provide useful information to the browsers, translation systems, and search-engines.Syntax: <abbr title=""> Short form </abbr> Attribute: This tag accepts an optional attribute as mentioned above and described below: title: It is used to specify extra information about the element. When the mouse moves over the element then it shows the information. Example: html <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>This is <abbr> Tag</h2> <abbr title="GeeksforGeeks">GFG</abbr></body> </html> Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubhamyadav4 HTML-Tags HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 31646, "s": 31618, "text": "\n24 Mar, 2022" }, { "code": null, "e": 31972, "s": 31646, "text": "The <abbr> tag(Abbreviation) in HTML is used to define the abbreviation or short form of an element. The <abbr> and <acronym> tags are used as shortened versions and used to represent a series of letters. The abbreviation is used to provide useful information to the browsers, translation systems, and search-engines.Syntax: " }, { "code": null, "e": 32007, "s": 31972, "text": "<abbr title=\"\"> Short form </abbr>" }, { "code": null, "e": 32097, "s": 32007, "text": "Attribute: This tag accepts an optional attribute as mentioned above and described below:" }, { "code": null, "e": 32232, "s": 32097, "text": "title: It is used to specify extra information about the element. When the mouse moves over the element then it shows the information." }, { "code": null, "e": 32242, "s": 32232, "text": "Example: " }, { "code": null, "e": 32247, "s": 32242, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>This is <abbr> Tag</h2> <abbr title=\"GeeksforGeeks\">GFG</abbr></body> </html>", "e": 32392, "s": 32247, "text": null }, { "code": null, "e": 32402, "s": 32392, "text": "Output: " }, { "code": null, "e": 32422, "s": 32402, "text": "Supported Browser: " }, { "code": null, "e": 32436, "s": 32422, "text": "Google Chrome" }, { "code": null, "e": 32454, "s": 32436, "text": "Internet Explorer" }, { "code": null, "e": 32462, "s": 32454, "text": "Firefox" }, { "code": null, "e": 32468, "s": 32462, "text": "Opera" }, { "code": null, "e": 32475, "s": 32468, "text": "Safari" }, { "code": null, "e": 32612, "s": 32475, "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": 32626, "s": 32612, "text": "shubhamyadav4" }, { "code": null, "e": 32636, "s": 32626, "text": "HTML-Tags" }, { "code": null, "e": 32641, "s": 32636, "text": "HTML" }, { "code": null, "e": 32658, "s": 32641, "text": "Web Technologies" }, { "code": null, "e": 32663, "s": 32658, "text": "HTML" }, { "code": null, "e": 32761, "s": 32663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32823, "s": 32761, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32873, "s": 32823, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32921, "s": 32873, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32981, "s": 32921, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33034, "s": 32981, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 33074, "s": 33034, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33107, "s": 33074, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33152, "s": 33107, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33195, "s": 33152, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | time.clock_gettime() method - GeeksforGeeks
17 Sep, 2019 time.clock_gettime() method of Time module is used to get the time of the specified clock clk_id. Basically, clk_id is a integer value which represents the id of the clock. Following are the constants available on UNIX platforms that can be used as value of clk_id parameter: Note: time.clock_gettime() method is only available on UNIX-like systems. Syntax: time.clock_gettime(clk_id) Parameter:clk_id: A clk_id constant or an integer value representing clk_id of the clock. Return type: This method returns a float value which represents the time (in seconds) of the specified clock clk_id. Code #1: Use of time.clock_gettime() method # Python program to explain time.clock_gettime() method # importing time moduleimport time # clk_id for System-wide real-time clockclk_id1 = time.CLOCK_REALTIME # clk_id for monotonic clockclk_id2 = time.CLOCK_MONOTONIC # clk_id for monotonic (Raw hardware# based time) clockclk_id3 = time.CLOCK_MONOTONIC # clk_id for Thread-specific CPU-time clockclk_id4 = time.CLOCK_THREAD_CPUTIME_ID # clk_id for High-resolution# per-process timer from the CPUclk_id5 = time.CLOCK_PROCESS_CPUTIME_ID # Get the time (in seconds) of the above # specified clock clk_ids# using time.clock_gettime() methodt1 = time.clock_gettime(clk_id1)t2 = time.clock_gettime(clk_id2)t3 = time.clock_gettime(clk_id3)t4 = time.clock_gettime(clk_id4)t5 = time.clock_gettime(clk_id5) # Print the time (in seconds) of # different clock clk_idsprint("Value of system-wide real-time clock time:", t1)print("Value of monotonic clock time:", t2)print("Value of monotonic (raw-hardware based) clock time:", t3)print("Value of thread-specific CPU time clock:", t4)print("Value of per-process timer from the CPU:", t5) Value of system-wide real-time clock time: 1568586677.79805 Value of monotonic clock time: 11754.867643594 Value of monotonic (raw-hardware based) clock time: 11754.867644148 Value of thread-specific CPU time clock: 0.03590527 Value of per-process timer from the CPU: 0.035907437 Code #2: Using an integer value as parameter of time.clock_gettime() method # Python program to explain time.clock_gettime() method # importing time moduleimport time # value of clk_id for time.CLOCK_REALTIME# clock id constant which represents# System-wide real-time clock is 0clk_id1 = 0 # value of clk_id for time.CLOCK_MONOTONIC# clock id constant which represents# a monotonic clock is 2clk_id2 = 2 # Get the time (in seconds)# for the specified clock clk_ids# using time.clock_gettime() methodt1 = time.clock_gettime(clk_id1)t2 = time.clock_gettime(clk_id2) # Print the time in secondsprint("Value of system-wide real-time clock time:", t1)print("Value of monotonic clock time:", t2) Value of system-wide real-time clock time: 1568587204.9810832 Value of monotonic clock time: 12282.050676627 Reference: https://docs.python.org/3/library/time.html#time.clock_gettime python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Sep, 2019" }, { "code": null, "e": 25710, "s": 25537, "text": "time.clock_gettime() method of Time module is used to get the time of the specified clock clk_id. Basically, clk_id is a integer value which represents the id of the clock." }, { "code": null, "e": 25813, "s": 25710, "text": "Following are the constants available on UNIX platforms that can be used as value of clk_id parameter:" }, { "code": null, "e": 25887, "s": 25813, "text": "Note: time.clock_gettime() method is only available on UNIX-like systems." }, { "code": null, "e": 25922, "s": 25887, "text": "Syntax: time.clock_gettime(clk_id)" }, { "code": null, "e": 26012, "s": 25922, "text": "Parameter:clk_id: A clk_id constant or an integer value representing clk_id of the clock." }, { "code": null, "e": 26129, "s": 26012, "text": "Return type: This method returns a float value which represents the time (in seconds) of the specified clock clk_id." }, { "code": null, "e": 26173, "s": 26129, "text": "Code #1: Use of time.clock_gettime() method" }, { "code": "# Python program to explain time.clock_gettime() method # importing time moduleimport time # clk_id for System-wide real-time clockclk_id1 = time.CLOCK_REALTIME # clk_id for monotonic clockclk_id2 = time.CLOCK_MONOTONIC # clk_id for monotonic (Raw hardware# based time) clockclk_id3 = time.CLOCK_MONOTONIC # clk_id for Thread-specific CPU-time clockclk_id4 = time.CLOCK_THREAD_CPUTIME_ID # clk_id for High-resolution# per-process timer from the CPUclk_id5 = time.CLOCK_PROCESS_CPUTIME_ID # Get the time (in seconds) of the above # specified clock clk_ids# using time.clock_gettime() methodt1 = time.clock_gettime(clk_id1)t2 = time.clock_gettime(clk_id2)t3 = time.clock_gettime(clk_id3)t4 = time.clock_gettime(clk_id4)t5 = time.clock_gettime(clk_id5) # Print the time (in seconds) of # different clock clk_idsprint(\"Value of system-wide real-time clock time:\", t1)print(\"Value of monotonic clock time:\", t2)print(\"Value of monotonic (raw-hardware based) clock time:\", t3)print(\"Value of thread-specific CPU time clock:\", t4)print(\"Value of per-process timer from the CPU:\", t5) ", "e": 27268, "s": 26173, "text": null }, { "code": null, "e": 27549, "s": 27268, "text": "Value of system-wide real-time clock time: 1568586677.79805\nValue of monotonic clock time: 11754.867643594\nValue of monotonic (raw-hardware based) clock time: 11754.867644148\nValue of thread-specific CPU time clock: 0.03590527\nValue of per-process timer from the CPU: 0.035907437\n" }, { "code": null, "e": 27625, "s": 27549, "text": "Code #2: Using an integer value as parameter of time.clock_gettime() method" }, { "code": "# Python program to explain time.clock_gettime() method # importing time moduleimport time # value of clk_id for time.CLOCK_REALTIME# clock id constant which represents# System-wide real-time clock is 0clk_id1 = 0 # value of clk_id for time.CLOCK_MONOTONIC# clock id constant which represents# a monotonic clock is 2clk_id2 = 2 # Get the time (in seconds)# for the specified clock clk_ids# using time.clock_gettime() methodt1 = time.clock_gettime(clk_id1)t2 = time.clock_gettime(clk_id2) # Print the time in secondsprint(\"Value of system-wide real-time clock time:\", t1)print(\"Value of monotonic clock time:\", t2)", "e": 28248, "s": 27625, "text": null }, { "code": null, "e": 28358, "s": 28248, "text": "Value of system-wide real-time clock time: 1568587204.9810832\nValue of monotonic clock time: 12282.050676627\n" }, { "code": null, "e": 28432, "s": 28358, "text": "Reference: https://docs.python.org/3/library/time.html#time.clock_gettime" }, { "code": null, "e": 28447, "s": 28432, "text": "python-utility" }, { "code": null, "e": 28454, "s": 28447, "text": "Python" }, { "code": null, "e": 28552, "s": 28454, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28584, "s": 28552, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28626, "s": 28584, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28668, "s": 28626, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28724, "s": 28668, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28751, "s": 28724, "text": "Python Classes and Objects" }, { "code": null, "e": 28790, "s": 28751, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28821, "s": 28790, "text": "Python | os.path.join() method" }, { "code": null, "e": 28850, "s": 28821, "text": "Create a directory in Python" }, { "code": null, "e": 28872, "s": 28850, "text": "Defaultdict in Python" } ]
LocalDateTime toString() method in Java with Examples - GeeksforGeeks
30 Nov, 2018 The toString() method of LocalDateTime class is used to get the String representation of this LocalDateTime. This method is derived from the Object Class and behaves in the similar way. Syntax: public String toString() Parameter: This method takes no parameters. Returns: This method returns a String value which is the String representation of this LocalDateTime. Below programs illustrate the LocalDateTime.toString() method: Program 1: // Program to illustrate the toString() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime dt = LocalDateTime.now(); // Get the String representation of this LocalDateTime // using toString() method System.out.println(dt.toString()); }} 2018-11-30T10:16:26.939 Program 2: // Program to illustrate the toString() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime dt = LocalDateTime .parse("2018-11-03T12:45:30"); // Get the String representation of this LocalDateTime // using toString() method System.out.println(dt.toString()); }} 2018-11-03T12:45:30 Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#toString() Java-Functions Java-LocalDateTime Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Multithreading in Java
[ { "code": null, "e": 25475, "s": 25447, "text": "\n30 Nov, 2018" }, { "code": null, "e": 25661, "s": 25475, "text": "The toString() method of LocalDateTime class is used to get the String representation of this LocalDateTime. This method is derived from the Object Class and behaves in the similar way." }, { "code": null, "e": 25669, "s": 25661, "text": "Syntax:" }, { "code": null, "e": 25694, "s": 25669, "text": "public String toString()" }, { "code": null, "e": 25738, "s": 25694, "text": "Parameter: This method takes no parameters." }, { "code": null, "e": 25840, "s": 25738, "text": "Returns: This method returns a String value which is the String representation of this LocalDateTime." }, { "code": null, "e": 25903, "s": 25840, "text": "Below programs illustrate the LocalDateTime.toString() method:" }, { "code": null, "e": 25914, "s": 25903, "text": "Program 1:" }, { "code": "// Program to illustrate the toString() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime dt = LocalDateTime.now(); // Get the String representation of this LocalDateTime // using toString() method System.out.println(dt.toString()); }}", "e": 26304, "s": 25914, "text": null }, { "code": null, "e": 26329, "s": 26304, "text": "2018-11-30T10:16:26.939\n" }, { "code": null, "e": 26340, "s": 26329, "text": "Program 2:" }, { "code": "// Program to illustrate the toString() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime dt = LocalDateTime .parse(\"2018-11-03T12:45:30\"); // Get the String representation of this LocalDateTime // using toString() method System.out.println(dt.toString()); }}", "e": 26782, "s": 26340, "text": null }, { "code": null, "e": 26803, "s": 26782, "text": "2018-11-03T12:45:30\n" }, { "code": null, "e": 26897, "s": 26803, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#toString()" }, { "code": null, "e": 26912, "s": 26897, "text": "Java-Functions" }, { "code": null, "e": 26931, "s": 26912, "text": "Java-LocalDateTime" }, { "code": null, "e": 26949, "s": 26931, "text": "Java-time package" }, { "code": null, "e": 26954, "s": 26949, "text": "Java" }, { "code": null, "e": 26959, "s": 26954, "text": "Java" }, { "code": null, "e": 27057, "s": 26959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27087, "s": 27057, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27102, "s": 27087, "text": "Stream In Java" }, { "code": null, "e": 27121, "s": 27102, "text": "Interfaces in Java" }, { "code": null, "e": 27139, "s": 27121, "text": "ArrayList in Java" }, { "code": null, "e": 27171, "s": 27139, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27191, "s": 27171, "text": "Stack Class in Java" }, { "code": null, "e": 27215, "s": 27191, "text": "Singleton Class in Java" }, { "code": null, "e": 27247, "s": 27215, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27259, "s": 27247, "text": "Set in Java" } ]
How to load more feature using jQuery ? - GeeksforGeeks
30 Sep, 2021 Bootstrap provides a lot of useful features that we generally integrate into our websites. One of them is the “Load More” feature which we can see on every second website we visit. The load more feature is used to load more or show more content available on the webpage to the visitor. Initially, half of the content is hidden, only some part of it is visible to the visitor. And when the Load More Button is clicked, the remaining content appears. This feature also gives the website a clean look. This is a pretty cool feature you must try on your website. Approach: The Load More feature of bootstrap can be integrated on the website by including a particular script (given below) and few javascript libraries, in the code. This script divides all the elements corresponding to a particular class, into parts withsize according to the slice function and displays the different parts one after another on clicking the load more button on the screen. And when the size becomes zero i.e. no more elements are left, it displays the text “No more to view”. Let’s see the step-by-step implementation of how to integrate the Load More feature into the website step by step. Step 1: You just need to include the following script on your website to make the “load more” button work. Here, .block is the class of the items in the HTML code, on which we will be applying the Load More feature and #load is the id of the Load more button. <script > $(document).ready(function() { $(".block").slice(0, 2).show(); if ($(".block:hidden").length != 0) { $("#load").show(); } $("#load").on("click", function(e) { e.preventDefault(); $(".block:hidden").slice(0, 2).slideDown(); if ($(".block:hidden").length == 0) { $("#load").text("No More to view").fadOut("slow"); } }); }) </script> Step 2: Also need to include the following javascript libraries in your HTML file as scripts. <script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js”></script> Example: HTML <!DOCTYPE html><html> <head> <title> Load more function Example:2 </title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> </script> <style> h1 { color: #3C8E3D; } .block { display: none; font-size: 20px; } #load { font-size: 20px; color: green; } </style></head> <body> <h1 align="center"> <b> GeeksforGeeks <br> <u>Load more function</u> </b> </h1> <div class="container"> <div class="block"> An array is a collection of items stored at contiguous memory locations.The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). </div> <div class="block"> The base value is index 0 and the difference between the two indexes is the offset. For simplicity, we can think of an array as a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on. </div> <div class="block"> In C language, array has a fixed size meaning once the size is given to it, it cannot be changed i.e. you can’t shrink it neither can you expand it. The reason was that for expanding, if we change the size we can’t be sure ( it’s not possible every time) that we get the next memory location to us as free. </div> <div class="block"> <br> Types of indexing in an array: <br> 0 (zero-based indexing) <br> 1 (one-based indexing) <br> n (n-based indexing) </div> </div> <div id="load"> <b> Load More </b></div> <script> $(document).ready(function () { $(".block").slice(0, 1).show(); if ($(".block:hidden").length != 0) { $("#load").show(); } $("#load").on("click", function (e) { e.preventDefault(); $(".block:hidden").slice(0, 1).slideDown(); if ($(".block:hidden").length == 0) { $("#load").text("No More to view") .fadOut("slow"); } }); }) </script></body> </html> Output: Explanation: In this example, only one paragraph was visible in the output initially, and with every click to load more button, one more successive paragraph appears, this is because in the slice function we mentioned (0,1) this time. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Properties CSS-Questions HTML-Questions jQuery-Methods jQuery-Questions Picked CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 26730, "s": 26702, "text": "\n30 Sep, 2021" }, { "code": null, "e": 27290, "s": 26730, "text": "Bootstrap provides a lot of useful features that we generally integrate into our websites. One of them is the “Load More” feature which we can see on every second website we visit. The load more feature is used to load more or show more content available on the webpage to the visitor. Initially, half of the content is hidden, only some part of it is visible to the visitor. And when the Load More Button is clicked, the remaining content appears. This feature also gives the website a clean look. This is a pretty cool feature you must try on your website. " }, { "code": null, "e": 27788, "s": 27290, "text": "Approach: The Load More feature of bootstrap can be integrated on the website by including a particular script (given below) and few javascript libraries, in the code. This script divides all the elements corresponding to a particular class, into parts withsize according to the slice function and displays the different parts one after another on clicking the load more button on the screen. And when the size becomes zero i.e. no more elements are left, it displays the text “No more to view”. " }, { "code": null, "e": 27904, "s": 27788, "text": " Let’s see the step-by-step implementation of how to integrate the Load More feature into the website step by step." }, { "code": null, "e": 28164, "s": 27904, "text": "Step 1: You just need to include the following script on your website to make the “load more” button work. Here, .block is the class of the items in the HTML code, on which we will be applying the Load More feature and #load is the id of the Load more button." }, { "code": null, "e": 28631, "s": 28164, "text": "<script >\n $(document).ready(function() {\n $(\".block\").slice(0, 2).show();\n if ($(\".block:hidden\").length != 0) {\n $(\"#load\").show();\n }\n $(\"#load\").on(\"click\", function(e) {\n e.preventDefault();\n $(\".block:hidden\").slice(0, 2).slideDown();\n if ($(\".block:hidden\").length == 0) {\n $(\"#load\").text(\"No More to view\").fadOut(\"slow\");\n }\n });\n }) \n</script> " }, { "code": null, "e": 28727, "s": 28633, "text": "Step 2: Also need to include the following javascript libraries in your HTML file as scripts." }, { "code": null, "e": 28912, "s": 28727, "text": "<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js”></script>" }, { "code": null, "e": 28921, "s": 28912, "text": "Example:" }, { "code": null, "e": 28926, "s": 28921, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> Load more function Example:2 </title> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\"> </script> <style> h1 { color: #3C8E3D; } .block { display: none; font-size: 20px; } #load { font-size: 20px; color: green; } </style></head> <body> <h1 align=\"center\"> <b> GeeksforGeeks <br> <u>Load more function</u> </b> </h1> <div class=\"container\"> <div class=\"block\"> An array is a collection of items stored at contiguous memory locations.The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). </div> <div class=\"block\"> The base value is index 0 and the difference between the two indexes is the offset. For simplicity, we can think of an array as a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on. </div> <div class=\"block\"> In C language, array has a fixed size meaning once the size is given to it, it cannot be changed i.e. you can’t shrink it neither can you expand it. The reason was that for expanding, if we change the size we can’t be sure ( it’s not possible every time) that we get the next memory location to us as free. </div> <div class=\"block\"> <br> Types of indexing in an array: <br> 0 (zero-based indexing) <br> 1 (one-based indexing) <br> n (n-based indexing) </div> </div> <div id=\"load\"> <b> Load More </b></div> <script> $(document).ready(function () { $(\".block\").slice(0, 1).show(); if ($(\".block:hidden\").length != 0) { $(\"#load\").show(); } $(\"#load\").on(\"click\", function (e) { e.preventDefault(); $(\".block:hidden\").slice(0, 1).slideDown(); if ($(\".block:hidden\").length == 0) { $(\"#load\").text(\"No More to view\") .fadOut(\"slow\"); } }); }) </script></body> </html>", "e": 31835, "s": 28926, "text": null }, { "code": null, "e": 31843, "s": 31835, "text": "Output:" }, { "code": null, "e": 32078, "s": 31843, "text": "Explanation: In this example, only one paragraph was visible in the output initially, and with every click to load more button, one more successive paragraph appears, this is because in the slice function we mentioned (0,1) this time." }, { "code": null, "e": 32215, "s": 32078, "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": 32230, "s": 32215, "text": "CSS-Properties" }, { "code": null, "e": 32244, "s": 32230, "text": "CSS-Questions" }, { "code": null, "e": 32259, "s": 32244, "text": "HTML-Questions" }, { "code": null, "e": 32274, "s": 32259, "text": "jQuery-Methods" }, { "code": null, "e": 32291, "s": 32274, "text": "jQuery-Questions" }, { "code": null, "e": 32298, "s": 32291, "text": "Picked" }, { "code": null, "e": 32302, "s": 32298, "text": "CSS" }, { "code": null, "e": 32307, "s": 32302, "text": "HTML" }, { "code": null, "e": 32314, "s": 32307, "text": "JQuery" }, { "code": null, "e": 32331, "s": 32314, "text": "Web Technologies" }, { "code": null, "e": 32336, "s": 32331, "text": "HTML" }, { "code": null, "e": 32434, "s": 32336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32471, "s": 32434, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32510, "s": 32471, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32539, "s": 32510, "text": "Form validation using jQuery" }, { "code": null, "e": 32581, "s": 32539, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 32616, "s": 32581, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 32676, "s": 32616, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32729, "s": 32676, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32790, "s": 32729, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32840, "s": 32790, "text": "How to Insert Form Data into Database using PHP ?" } ]
Angular Material 7 - Badge
The <mat-badge>, an Angular Directive, is used to create a badges which is a small status descriptor for UI elements. A badge typically carries a number or other short set of characters, that appears in proximity to another UI element. In this chapter, we will showcase the configuration required to draw a badge control using Angular Material. Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter − Following is the content of the modified module descriptor app.module.ts. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MatBadgeModule, MatButtonModule, MatIconModule} from '@angular/material' import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MatBadgeModule, MatButtonModule, MatIconModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Following is the content of the modified HTML host file app.component.html. <p><span matBadge = "4" matBadgeOverlap = "false">Mail</span></p> <p> <button mat-raised-button color = "primary" matBadge = "8" matBadgePosition = "before" matBadgeColor = "accent"> Action </button> </p> <p><mat-icon matBadge = "15" matBadgeColor = "warn">home</mat-icon></p> Verify the result. As first, we've created a span, a button and a icon. Then, we've added badges to each element using mat-badge attribute. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2991, "s": 2755, "text": "The <mat-badge>, an Angular Directive, is used to create a badges which is a small status descriptor for UI elements. A badge typically carries a number or other short set of characters, that appears in proximity to another UI element." }, { "code": null, "e": 3100, "s": 2991, "text": "In this chapter, we will showcase the configuration required to draw a badge control using Angular Material." }, { "code": null, "e": 3211, "s": 3100, "text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −" }, { "code": null, "e": 3285, "s": 3211, "text": "Following is the content of the modified module descriptor app.module.ts." }, { "code": null, "e": 3962, "s": 3285, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatBadgeModule, MatButtonModule, MatIconModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatBadgeModule, MatButtonModule, MatIconModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 4038, "s": 3962, "text": "Following is the content of the modified HTML host file app.component.html." }, { "code": null, "e": 4333, "s": 4038, "text": "<p><span matBadge = \"4\" matBadgeOverlap = \"false\">Mail</span></p>\n<p>\n <button mat-raised-button color = \"primary\"\n matBadge = \"8\" matBadgePosition = \"before\" matBadgeColor = \"accent\">\n Action\n </button>\n</p>\n<p><mat-icon matBadge = \"15\" matBadgeColor = \"warn\">home</mat-icon></p>" }, { "code": null, "e": 4352, "s": 4333, "text": "Verify the result." }, { "code": null, "e": 4405, "s": 4352, "text": "As first, we've created a span, a button and a icon." }, { "code": null, "e": 4473, "s": 4405, "text": "Then, we've added badges to each element using mat-badge attribute." }, { "code": null, "e": 4508, "s": 4473, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4522, "s": 4508, "text": " Anadi Sharma" }, { "code": null, "e": 4557, "s": 4522, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4571, "s": 4557, "text": " Anadi Sharma" }, { "code": null, "e": 4606, "s": 4571, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4626, "s": 4606, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4661, "s": 4626, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4678, "s": 4661, "text": " Frahaan Hussain" }, { "code": null, "e": 4711, "s": 4678, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4723, "s": 4711, "text": " Senol Atac" }, { "code": null, "e": 4758, "s": 4723, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4770, "s": 4758, "text": " Senol Atac" }, { "code": null, "e": 4777, "s": 4770, "text": " Print" }, { "code": null, "e": 4788, "s": 4777, "text": " Add Notes" } ]
Unix / Linux Shell - The if...else...fi statement
The if...else...fi statement is the next form of control statement that allows Shell to execute statements in a controlled way and make the right choice. if [ expression ] then Statement(s) to be executed if expression is true else Statement(s) to be executed if expression is not true fi The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are executed. If the expression is false, then no statement will be executed. The above example can also be written using the if...else statement as follows − #!/bin/sh a=10 b=20 if [ $a == $b ] then echo "a is equal to b" else echo "a is not equal to b" fi Upon execution, you will receive the following result − a is not equal to b 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2901, "s": 2747, "text": "The if...else...fi statement is the next form of control statement that allows Shell to execute statements in a controlled way and make the right choice." }, { "code": null, "e": 3043, "s": 2901, "text": "if [ expression ]\nthen\n Statement(s) to be executed if expression is true\nelse\n Statement(s) to be executed if expression is not true\nfi\n" }, { "code": null, "e": 3227, "s": 3043, "text": "The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are executed. If the expression is false, then no statement will be executed." }, { "code": null, "e": 3308, "s": 3227, "text": "The above example can also be written using the if...else statement as follows −" }, { "code": null, "e": 3415, "s": 3308, "text": "#!/bin/sh\n\na=10\nb=20\n\nif [ $a == $b ]\nthen\n echo \"a is equal to b\"\nelse\n echo \"a is not equal to b\"\nfi" }, { "code": null, "e": 3471, "s": 3415, "text": "Upon execution, you will receive the following result −" }, { "code": null, "e": 3492, "s": 3471, "text": "a is not equal to b\n" }, { "code": null, "e": 3527, "s": 3492, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 3555, "s": 3527, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3589, "s": 3555, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3606, "s": 3589, "text": " Frahaan Hussain" }, { "code": null, "e": 3639, "s": 3606, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 3650, "s": 3639, "text": " Pradeep D" }, { "code": null, "e": 3685, "s": 3650, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3701, "s": 3685, "text": " Musab Zayadneh" }, { "code": null, "e": 3734, "s": 3701, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 3746, "s": 3734, "text": " GUHARAJANM" }, { "code": null, "e": 3778, "s": 3746, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 3786, "s": 3778, "text": " Uplatz" }, { "code": null, "e": 3793, "s": 3786, "text": " Print" }, { "code": null, "e": 3804, "s": 3793, "text": " Add Notes" } ]
Applying Data Science in the Life Insurance Industry: A Perspective from a Qualified Actuary | by Jin Cui | Towards Data Science
I’m a qualified actuary with 10 years of experience practising in the life insurance industry in Australia. For those of you who may not be familiar with what an actuary does day-to-day, at a high level, an actuary’s role spans: setting premium rates for mortality and morbidity products, calculating claims obligations and associated capital requirments for the life insurer, calibrating economic value for the life insurer’s shareholders and understanding deviation in the actual experience (e.g. for claims and discontinuance) against the expected experience. About 3 years ago I embarked on a journey to self-learn data science/machine learning techniques after coming across a documentary on AlphaGo. I found it particularly fascinating how machines can be trained to learn abstract concepts, in this instance, human intuitions for making a move in the game of Go. With a reasonable background in Statistics by education, I was quick to pick up a number of data science techniques and apply them in my line of work. I’ll expain how these techniques help improve actuarial analyses later in this article with two (2) use cases. I consider data science techniques good supplements to the traditional actuarial techniques which are mostly Statistics-based, and have been fortunate enough not having to jump onto the data science bandwagon from a completely unrelated field. In my day-to-day work (and I can speak for most life insurance actuaries in Australia), Excel has been the primary tool for analysing data, and VBA macro for automating some of the Excel-based ETL works. From a programming perspective, most life insurance actuaries would have a bit of exposure to R while at university. Excel comes with its pros and cons, which I’ll discuss in a bit more detail later on. Data science is at the infancy stage for most life insurance companies in Australia, according to a consultancy I spoke to. ‘Machine Learning’ and ‘Data Science’ are buzz words executives have heard of, but may find them hard to relate to. As an example, on one occasion, I have heard executives commenting on machine learning as if it was the same as the fairly distant artificial general intelligence. To me, the cause of the low penetration of data science techniques in the life insurance industry is two-fold: Data collected by life insurance companies have historically been scarce compared to the general insurance companies (e.g. motor insurers). This is due to the fact that most of the population own at least one car, whilst not necessarily having a life insurance policy. In addition, it’s much more likely to claim on one’s motor insurance policy, compared to a life insurance policy. This has implicitly made machine learning models which rely on high volume of training data (e.g. neural networks) less appealing. Life insurance executives have not (yet) been presented with practical use cases of how data science techniques can add value to an organisation. Given it’s a relatively new development, few people in the organisation are equipped to build and at the same time promote a business case to secure buy-ins and investments. As an example, few people in the Product team would be aware that we can apply a bit of web-scraping to gather updates of competitors’ product features, as opposed to manually collecting this information by going on each competitor’s website. This article aims to demonstrate how data science techniques can add value to a life insurance company, particularly the actuarial workflow, with two (2) use cases based on my own experience. I do have more use cases which I’m hoping to share in future articles. Most life insurers record claims causes for claims lodged by policyholders. Some examples of claims causes recorded are: Dislocated, Fractured (L) Hip Metastatic Melanoma Cardiac Arrest Claims causes at times are recorded in the form of free-texts. These are unstructured data which present challenges for actuaries who would like to analyse claims at the claims cause level. The three examples of claims causes above have the same meaning as Broken Hip, Skin Cancer, and Heart Attack respectively. However, by simply getting the computer to read the texts without a human understanding, these claims would all be treated as unique claims. For example, the computer may recognise 15 unique levels in the ‘Claims cause’ column below, whereas there should really be just one unique level (Neoplasm, or Cancer) actuaries are concerned with. Before using the NLP technique I’m about to describe below for this task, I have been filtering in Excel, for example, claims containing similar string of words like “Cancer” or “Tumor”, and manually classifying them to the Neoplasm category. You can imagine how manual and laborious this is, at times requiring me to look up medical terms such as “Cholangiocarcinoma”, “Seminoma” and others claim by claim. The task in this use case is to automatically classify claims causes into the pre-defined categories using some Natural Language Processing (“NLP”). Some categories at which to aggregate the claims causes may be Accident/Injury, Neoplasm, Musculoskeletal, Circulatory Diseases, Respiratory Diseases, Mental Disorder, just to name a few. This can be achieved in the following five (5) steps. Step 1 After defining the categories at which to aggregate the claims causes, manually label the free-text claims causes into these categories. This is to provide some training data to the NLP model, but I promise this would be the last laborious step in this task! In practice, the labelling was done for 366 claims, out of a dataset of approximately 6,000 claims. Personally this did not add much to the effort as I have been doing this already previously. Step 2 For the (366) claims now with a label, perform text cleaning on claims causes such as removing special characters, removing double white spaces and lower-casing. It’s easy to expand this step to include other cleaning steps of choice such as rectifying spelling errors. Some sample Python codes for text cleaning are provided below: import re#remove special charactertext_remove_special_character = []for texts in raw_claims_cause:text_remove_special_character.append((re.sub(r'[^\w\s]', '', str(texts).strip())))#remove double white spacetext_remove_white_space = []for texts in raw_claims_cause:text_remove_white_space.append(" ".join(texts.split()))#lower-casingtext_lowercase = []for texts in raw_claims_cause:text_lowercase.append(texts.lower()) Step 3 Create word embedding for the cleaned texts for claims causes. I have chosen a form of BERT vecotrisation per the sample Python codes below. from sentence_transformers import SentenceTransformerbert_input_claims_with_label = text_claims_register['text_claims_causes_cleaned'].tolist()model_claims_with_label = SentenceTransformer('paraphrase-mpnet-base-v2')embeddings_claims_with_label = model_claims_with_label.encode(bert_input_claims_with_label)print('Shape of vector outputs:', embeddings_claims_with_label.shape) The Bidirectional Encoder Representations from Transformers (“BERT”) model is a NLP model developed and released by Google in 2018. It’s a pre-trained model using text passages on Wikipedia and BookCorpus (just to ensure the training data are grammatically sound). In essense, each free-text claims cause has been ‘translated’ by BERT into a language the computer can understand, represented by a vector of length 768. The output of this step is effectively vectors for each free-text claims cause with a label, again of length 768. The shape of the overall word embedding is as expected: Shape of vector outputs: (366, 768) Step 4 Repeat Steps 1–3 for claims causes without a label. The output of this step is effectively vectors for each free-text claims cause without a label (i.e. the claims causes we want to label), again of length 768. If you have n claims causes without a label, you should expect the shape of the word embedding to be of dimension (n, 768). Step 5 Vector output for claims causes without a label is compared against the vector output for claims causes with a label. The claims cause label of the closest match is returned based on cosine similarity. In simple terms, as the training data consists of 366 claims, for each claims cause we want to automatically label (i.e. for each row in the similarity_df dataframe in the sample code below), there exists 366 columns which numerically score how similar the particular claims cause is with each of the claims in the training data, and the position of the claim which gives the highest score is returned with the pandas idxmax method. from sklearn.metrics.pairwise import cosine_similarityembedding_array_claims_with_label = np.array(embeddings_claims_with_label)embedding_array_claims_without_label = np.array(embeddings_claims_without_label)similarity = cosine_similarity(embedding_array_claims_without_label, embedding_array_claims_with_label)similarity_df = pd.DataFrame(similarity)#return position of closest match, with which the label can be looked upsimilarity_index = similarity_df.idxmax(axis = 1) Below is a snippet of the end outputs for a number of claims, which definitely passed the ‘eye-test’. Implications for actuaries There are a number of implications for actuarial analyses if claims causes are able to be mapped and aggregated at this level. Some examples include: Investigating trend by claims cause (e.g. trend of subjective claims such as Mental Disorder or related claims, during the COVID-19 pandemic) Comparing company claims experience by claims causes against the industry experience (which are published by Government auhtorities in Australia) Understanding top n claims causes by rating factors such as Occupation, Gender and etc. Triaging claims to be assessed to suitable claims assessors by specialty (e.g. certain claims assessors may be more specialised in Mental Disorder claims than others) Separately, using similar methodology, this use case can be extrapolated to Occupation classes. For example, mapping occupation descriptions such as “Plumber, 3 years of experience” to the Blue Collar category and “Lawyer, degree qualified” to the Professional/White Collar category, which can then feed actuarial analyses further. Summary — use case 1 To summarise, this use case presents a way for actuaries to automatically classify free-text claims causes data into pre-defined categories for further analyses. Ultimately, with the help of BERT, computers are able to understand human language. For this instance, computers are able to understand and compare medical terms or description of a claims event, which can be messy at times. The alternative which is manual filtering in Excel is not practical, especially for large number of claims. As mentioned previously, Excel has been the primary ETL tool for most life insurance actuaries. Whilst Excel offers users transparency in transforming data, it has a number of crippling disadvantages in the context of actuarial applications: Excel has a row and column limit. More often that not, even before this limit is reached, navigating through the spreadsheets would be slow and difficult given the requirements on computing resources. Excel is not a scalable tool as it’s often difficult to efficiently connect data in one workbook with another, not to mention to perform calculations, especially when datasets are large in size. The task this use case is based upon is not (practically) achievable with Excel, but easily achievable with a bit of dataframe manipulation with PySpark. To describe the task using a simple example, imagine a life insurance policyholder has purchased a policy with two (2) covers, a cover for the event of Death (“Death cover”) and a cover for the event of a pre-defined medical condition (“Trauma cover”). The two covers are associated with different payout amounts, usually more on Death cover than the Trauma cover. In addition, in most cases in Australia, paying out the Trauma cover would reduce the amount originally purchased with the Death cover. For example, let’s assume the policyholder has purchased a Death cover with the payout amount of $100k and a Trauma cover with a payout amount of $50k. If the policyholder claimed on the Trauma cover and gets paid out $50k, the Death cover reduces to $50k (i.e. $100k - $50k). The readers don’t need to understand the technicalities but this product structure, which is common in Australia, warrants different mortality assumptions for the Death cover. In simple terms, as illustrated in Chart 2.1 below, the blue and green components of the Death cover need to be modelled with different actuarial assumptions. In essence, this requires a ‘split’ of the Death cover into two components for which we’ll model claims costs differently. Effectively, this requires identifying policyholders having a Death cover and a ‘linked’ Trauma cover, and in this ‘frame’ of the data for the particular policyholder, adding an additional row for the Death cover, and calculating the payout amounts for the two rows of the Death covers based on the payout amount for the Trauma cover. You should quickly see that this would be extremely difficult to achieve with Excel, in part because the transformation is not one-to-one. In tabular format, the transformation required is illustrated in Chart 2.2 below: This is when PySpark and its built-in SQL functions become very powerful, and with it, the transformaton required can be achieved in the following four (4) steps: Step 1 Create a new column “Linked Amount”, which returns the payout amount of the Trauma cover at a Policyholder ID level as illustrated in Chart 2.3 below. This can be done by creating a window or ‘frame’ over the Policyholder ID field (which I’ve used interchangeably with Policyholder_ID in the sample codes below): from pyspark.sql import functions as Ffrom pyspark.sql import Window as Wdef compute_Linked_Amount(Policyholder_ID: List[str]) -> Column:window = W.partitionBy(*Policyholder_ID) \.rangeBetween(W.unboundedPreceding, W.unboundedFollowing) \.orderBy("Policyholder_ID")return F.when(F.col("Cover") == "Death", F.lit(0.0)).otherwise(F.col("Amount")).over(window) Step 2 Create another new column “Split Type”, specified with the array data type for rows of Death covers only, set the value for these rows to [Death Comp 1, Death Comp 2] (i.e. a 2 by 1 array with the same strings), as illustrated below: Step 3 ‘Explode’ each of these rows into 2 identical rows except for the value of the new column being respectively Death Comp 1 and Death Comp 2. This is illustrated below. The ‘explode’ operation can be achieved using the explode_outer SQL functions within PySpark. Step 4 Create the final payout amount column, formulated with the following WHEN OTHERWISE statement. from pyspark.sql import functions as FF.when(col("Split Type") == "Death Comp 1", \F.col("Amount") - F.col("Linked Amount") \.otherwise(F.col("Linked Amount") You should be able to see that after removing rows with a 0 value in the “Final Amount” column, the transformation is complete per Chart 2.2. Summary — use case 2 To summarise, this use case represents a transformation which requires rows corresponding to the Death covers in a dataframe to be split into separate rows if the same policyholder also has a Trauma cover. This is not easily achievable with operations in Excel. It has been demonstrated in the use case that such transformation is easily achievable with PySpark, which offers users the following: Ability to create a window over a subset of the data (e.g. for each policyholder using Policyholder ID field) and extract information at this level. For this instance, this identified whether the policyholder has both the Death and Trauma covers, and if the policyholder does, populated the payout amount for the Trauma cover in the row of the Death cover per Step 1 of the use case. Ability to insert a column in a dataframe of the array data type, which makes operations like splitting possible with built-in SQL functions such as ‘explode_outer’. Efficiency at which the transformation is done compared to Excel, as PySpark is known for its speed for operations in large datasets/dataframes. This is critical as we extrapolate the use case to cover types apart from Death and Trauma, as well as to all the policyholders for commercial use within a life insurance company. Data science, machine learning may still seem like distant words to a life insurance actuary in 2021, but they are closer to home than one might think. Personally (and commercially), it takes a bit of a effort to break the barrier to entry which will eventually be worthwhile. At last, I hope you find this article a good read and please share it if you do.
[ { "code": null, "e": 735, "s": 172, "text": "I’m a qualified actuary with 10 years of experience practising in the life insurance industry in Australia. For those of you who may not be familiar with what an actuary does day-to-day, at a high level, an actuary’s role spans: setting premium rates for mortality and morbidity products, calculating claims obligations and associated capital requirments for the life insurer, calibrating economic value for the life insurer’s shareholders and understanding deviation in the actual experience (e.g. for claims and discontinuance) against the expected experience." }, { "code": null, "e": 1042, "s": 735, "text": "About 3 years ago I embarked on a journey to self-learn data science/machine learning techniques after coming across a documentary on AlphaGo. I found it particularly fascinating how machines can be trained to learn abstract concepts, in this instance, human intuitions for making a move in the game of Go." }, { "code": null, "e": 1304, "s": 1042, "text": "With a reasonable background in Statistics by education, I was quick to pick up a number of data science techniques and apply them in my line of work. I’ll expain how these techniques help improve actuarial analyses later in this article with two (2) use cases." }, { "code": null, "e": 1548, "s": 1304, "text": "I consider data science techniques good supplements to the traditional actuarial techniques which are mostly Statistics-based, and have been fortunate enough not having to jump onto the data science bandwagon from a completely unrelated field." }, { "code": null, "e": 1752, "s": 1548, "text": "In my day-to-day work (and I can speak for most life insurance actuaries in Australia), Excel has been the primary tool for analysing data, and VBA macro for automating some of the Excel-based ETL works." }, { "code": null, "e": 1869, "s": 1752, "text": "From a programming perspective, most life insurance actuaries would have a bit of exposure to R while at university." }, { "code": null, "e": 1955, "s": 1869, "text": "Excel comes with its pros and cons, which I’ll discuss in a bit more detail later on." }, { "code": null, "e": 2359, "s": 1955, "text": "Data science is at the infancy stage for most life insurance companies in Australia, according to a consultancy I spoke to. ‘Machine Learning’ and ‘Data Science’ are buzz words executives have heard of, but may find them hard to relate to. As an example, on one occasion, I have heard executives commenting on machine learning as if it was the same as the fairly distant artificial general intelligence." }, { "code": null, "e": 2470, "s": 2359, "text": "To me, the cause of the low penetration of data science techniques in the life insurance industry is two-fold:" }, { "code": null, "e": 2984, "s": 2470, "text": "Data collected by life insurance companies have historically been scarce compared to the general insurance companies (e.g. motor insurers). This is due to the fact that most of the population own at least one car, whilst not necessarily having a life insurance policy. In addition, it’s much more likely to claim on one’s motor insurance policy, compared to a life insurance policy. This has implicitly made machine learning models which rely on high volume of training data (e.g. neural networks) less appealing." }, { "code": null, "e": 3547, "s": 2984, "text": "Life insurance executives have not (yet) been presented with practical use cases of how data science techniques can add value to an organisation. Given it’s a relatively new development, few people in the organisation are equipped to build and at the same time promote a business case to secure buy-ins and investments. As an example, few people in the Product team would be aware that we can apply a bit of web-scraping to gather updates of competitors’ product features, as opposed to manually collecting this information by going on each competitor’s website." }, { "code": null, "e": 3810, "s": 3547, "text": "This article aims to demonstrate how data science techniques can add value to a life insurance company, particularly the actuarial workflow, with two (2) use cases based on my own experience. I do have more use cases which I’m hoping to share in future articles." }, { "code": null, "e": 3931, "s": 3810, "text": "Most life insurers record claims causes for claims lodged by policyholders. Some examples of claims causes recorded are:" }, { "code": null, "e": 3961, "s": 3931, "text": "Dislocated, Fractured (L) Hip" }, { "code": null, "e": 3981, "s": 3961, "text": "Metastatic Melanoma" }, { "code": null, "e": 3996, "s": 3981, "text": "Cardiac Arrest" }, { "code": null, "e": 4186, "s": 3996, "text": "Claims causes at times are recorded in the form of free-texts. These are unstructured data which present challenges for actuaries who would like to analyse claims at the claims cause level." }, { "code": null, "e": 4450, "s": 4186, "text": "The three examples of claims causes above have the same meaning as Broken Hip, Skin Cancer, and Heart Attack respectively. However, by simply getting the computer to read the texts without a human understanding, these claims would all be treated as unique claims." }, { "code": null, "e": 4648, "s": 4450, "text": "For example, the computer may recognise 15 unique levels in the ‘Claims cause’ column below, whereas there should really be just one unique level (Neoplasm, or Cancer) actuaries are concerned with." }, { "code": null, "e": 5056, "s": 4648, "text": "Before using the NLP technique I’m about to describe below for this task, I have been filtering in Excel, for example, claims containing similar string of words like “Cancer” or “Tumor”, and manually classifying them to the Neoplasm category. You can imagine how manual and laborious this is, at times requiring me to look up medical terms such as “Cholangiocarcinoma”, “Seminoma” and others claim by claim." }, { "code": null, "e": 5447, "s": 5056, "text": "The task in this use case is to automatically classify claims causes into the pre-defined categories using some Natural Language Processing (“NLP”). Some categories at which to aggregate the claims causes may be Accident/Injury, Neoplasm, Musculoskeletal, Circulatory Diseases, Respiratory Diseases, Mental Disorder, just to name a few. This can be achieved in the following five (5) steps." }, { "code": null, "e": 5454, "s": 5447, "text": "Step 1" }, { "code": null, "e": 5713, "s": 5454, "text": "After defining the categories at which to aggregate the claims causes, manually label the free-text claims causes into these categories. This is to provide some training data to the NLP model, but I promise this would be the last laborious step in this task!" }, { "code": null, "e": 5906, "s": 5713, "text": "In practice, the labelling was done for 366 claims, out of a dataset of approximately 6,000 claims. Personally this did not add much to the effort as I have been doing this already previously." }, { "code": null, "e": 5913, "s": 5906, "text": "Step 2" }, { "code": null, "e": 6183, "s": 5913, "text": "For the (366) claims now with a label, perform text cleaning on claims causes such as removing special characters, removing double white spaces and lower-casing. It’s easy to expand this step to include other cleaning steps of choice such as rectifying spelling errors." }, { "code": null, "e": 6246, "s": 6183, "text": "Some sample Python codes for text cleaning are provided below:" }, { "code": null, "e": 6664, "s": 6246, "text": "import re#remove special charactertext_remove_special_character = []for texts in raw_claims_cause:text_remove_special_character.append((re.sub(r'[^\\w\\s]', '', str(texts).strip())))#remove double white spacetext_remove_white_space = []for texts in raw_claims_cause:text_remove_white_space.append(\" \".join(texts.split()))#lower-casingtext_lowercase = []for texts in raw_claims_cause:text_lowercase.append(texts.lower())" }, { "code": null, "e": 6671, "s": 6664, "text": "Step 3" }, { "code": null, "e": 6812, "s": 6671, "text": "Create word embedding for the cleaned texts for claims causes. I have chosen a form of BERT vecotrisation per the sample Python codes below." }, { "code": null, "e": 7189, "s": 6812, "text": "from sentence_transformers import SentenceTransformerbert_input_claims_with_label = text_claims_register['text_claims_causes_cleaned'].tolist()model_claims_with_label = SentenceTransformer('paraphrase-mpnet-base-v2')embeddings_claims_with_label = model_claims_with_label.encode(bert_input_claims_with_label)print('Shape of vector outputs:', embeddings_claims_with_label.shape)" }, { "code": null, "e": 7454, "s": 7189, "text": "The Bidirectional Encoder Representations from Transformers (“BERT”) model is a NLP model developed and released by Google in 2018. It’s a pre-trained model using text passages on Wikipedia and BookCorpus (just to ensure the training data are grammatically sound)." }, { "code": null, "e": 7608, "s": 7454, "text": "In essense, each free-text claims cause has been ‘translated’ by BERT into a language the computer can understand, represented by a vector of length 768." }, { "code": null, "e": 7722, "s": 7608, "text": "The output of this step is effectively vectors for each free-text claims cause with a label, again of length 768." }, { "code": null, "e": 7778, "s": 7722, "text": "The shape of the overall word embedding is as expected:" }, { "code": null, "e": 7814, "s": 7778, "text": "Shape of vector outputs: (366, 768)" }, { "code": null, "e": 7821, "s": 7814, "text": "Step 4" }, { "code": null, "e": 8156, "s": 7821, "text": "Repeat Steps 1–3 for claims causes without a label. The output of this step is effectively vectors for each free-text claims cause without a label (i.e. the claims causes we want to label), again of length 768. If you have n claims causes without a label, you should expect the shape of the word embedding to be of dimension (n, 768)." }, { "code": null, "e": 8163, "s": 8156, "text": "Step 5" }, { "code": null, "e": 8365, "s": 8163, "text": "Vector output for claims causes without a label is compared against the vector output for claims causes with a label. The claims cause label of the closest match is returned based on cosine similarity." }, { "code": null, "e": 8798, "s": 8365, "text": "In simple terms, as the training data consists of 366 claims, for each claims cause we want to automatically label (i.e. for each row in the similarity_df dataframe in the sample code below), there exists 366 columns which numerically score how similar the particular claims cause is with each of the claims in the training data, and the position of the claim which gives the highest score is returned with the pandas idxmax method." }, { "code": null, "e": 9271, "s": 8798, "text": "from sklearn.metrics.pairwise import cosine_similarityembedding_array_claims_with_label = np.array(embeddings_claims_with_label)embedding_array_claims_without_label = np.array(embeddings_claims_without_label)similarity = cosine_similarity(embedding_array_claims_without_label, embedding_array_claims_with_label)similarity_df = pd.DataFrame(similarity)#return position of closest match, with which the label can be looked upsimilarity_index = similarity_df.idxmax(axis = 1)" }, { "code": null, "e": 9373, "s": 9271, "text": "Below is a snippet of the end outputs for a number of claims, which definitely passed the ‘eye-test’." }, { "code": null, "e": 9400, "s": 9373, "text": "Implications for actuaries" }, { "code": null, "e": 9550, "s": 9400, "text": "There are a number of implications for actuarial analyses if claims causes are able to be mapped and aggregated at this level. Some examples include:" }, { "code": null, "e": 9692, "s": 9550, "text": "Investigating trend by claims cause (e.g. trend of subjective claims such as Mental Disorder or related claims, during the COVID-19 pandemic)" }, { "code": null, "e": 9838, "s": 9692, "text": "Comparing company claims experience by claims causes against the industry experience (which are published by Government auhtorities in Australia)" }, { "code": null, "e": 9926, "s": 9838, "text": "Understanding top n claims causes by rating factors such as Occupation, Gender and etc." }, { "code": null, "e": 10093, "s": 9926, "text": "Triaging claims to be assessed to suitable claims assessors by specialty (e.g. certain claims assessors may be more specialised in Mental Disorder claims than others)" }, { "code": null, "e": 10425, "s": 10093, "text": "Separately, using similar methodology, this use case can be extrapolated to Occupation classes. For example, mapping occupation descriptions such as “Plumber, 3 years of experience” to the Blue Collar category and “Lawyer, degree qualified” to the Professional/White Collar category, which can then feed actuarial analyses further." }, { "code": null, "e": 10446, "s": 10425, "text": "Summary — use case 1" }, { "code": null, "e": 10833, "s": 10446, "text": "To summarise, this use case presents a way for actuaries to automatically classify free-text claims causes data into pre-defined categories for further analyses. Ultimately, with the help of BERT, computers are able to understand human language. For this instance, computers are able to understand and compare medical terms or description of a claims event, which can be messy at times." }, { "code": null, "e": 10941, "s": 10833, "text": "The alternative which is manual filtering in Excel is not practical, especially for large number of claims." }, { "code": null, "e": 11183, "s": 10941, "text": "As mentioned previously, Excel has been the primary ETL tool for most life insurance actuaries. Whilst Excel offers users transparency in transforming data, it has a number of crippling disadvantages in the context of actuarial applications:" }, { "code": null, "e": 11384, "s": 11183, "text": "Excel has a row and column limit. More often that not, even before this limit is reached, navigating through the spreadsheets would be slow and difficult given the requirements on computing resources." }, { "code": null, "e": 11579, "s": 11384, "text": "Excel is not a scalable tool as it’s often difficult to efficiently connect data in one workbook with another, not to mention to perform calculations, especially when datasets are large in size." }, { "code": null, "e": 11733, "s": 11579, "text": "The task this use case is based upon is not (practically) achievable with Excel, but easily achievable with a bit of dataframe manipulation with PySpark." }, { "code": null, "e": 11986, "s": 11733, "text": "To describe the task using a simple example, imagine a life insurance policyholder has purchased a policy with two (2) covers, a cover for the event of Death (“Death cover”) and a cover for the event of a pre-defined medical condition (“Trauma cover”)." }, { "code": null, "e": 12511, "s": 11986, "text": "The two covers are associated with different payout amounts, usually more on Death cover than the Trauma cover. In addition, in most cases in Australia, paying out the Trauma cover would reduce the amount originally purchased with the Death cover. For example, let’s assume the policyholder has purchased a Death cover with the payout amount of $100k and a Trauma cover with a payout amount of $50k. If the policyholder claimed on the Trauma cover and gets paid out $50k, the Death cover reduces to $50k (i.e. $100k - $50k)." }, { "code": null, "e": 12969, "s": 12511, "text": "The readers don’t need to understand the technicalities but this product structure, which is common in Australia, warrants different mortality assumptions for the Death cover. In simple terms, as illustrated in Chart 2.1 below, the blue and green components of the Death cover need to be modelled with different actuarial assumptions. In essence, this requires a ‘split’ of the Death cover into two components for which we’ll model claims costs differently." }, { "code": null, "e": 13525, "s": 12969, "text": "Effectively, this requires identifying policyholders having a Death cover and a ‘linked’ Trauma cover, and in this ‘frame’ of the data for the particular policyholder, adding an additional row for the Death cover, and calculating the payout amounts for the two rows of the Death covers based on the payout amount for the Trauma cover. You should quickly see that this would be extremely difficult to achieve with Excel, in part because the transformation is not one-to-one. In tabular format, the transformation required is illustrated in Chart 2.2 below:" }, { "code": null, "e": 13688, "s": 13525, "text": "This is when PySpark and its built-in SQL functions become very powerful, and with it, the transformaton required can be achieved in the following four (4) steps:" }, { "code": null, "e": 13695, "s": 13688, "text": "Step 1" }, { "code": null, "e": 13846, "s": 13695, "text": "Create a new column “Linked Amount”, which returns the payout amount of the Trauma cover at a Policyholder ID level as illustrated in Chart 2.3 below." }, { "code": null, "e": 14008, "s": 13846, "text": "This can be done by creating a window or ‘frame’ over the Policyholder ID field (which I’ve used interchangeably with Policyholder_ID in the sample codes below):" }, { "code": null, "e": 14366, "s": 14008, "text": "from pyspark.sql import functions as Ffrom pyspark.sql import Window as Wdef compute_Linked_Amount(Policyholder_ID: List[str]) -> Column:window = W.partitionBy(*Policyholder_ID) \\.rangeBetween(W.unboundedPreceding, W.unboundedFollowing) \\.orderBy(\"Policyholder_ID\")return F.when(F.col(\"Cover\") == \"Death\", F.lit(0.0)).otherwise(F.col(\"Amount\")).over(window)" }, { "code": null, "e": 14373, "s": 14366, "text": "Step 2" }, { "code": null, "e": 14607, "s": 14373, "text": "Create another new column “Split Type”, specified with the array data type for rows of Death covers only, set the value for these rows to [Death Comp 1, Death Comp 2] (i.e. a 2 by 1 array with the same strings), as illustrated below:" }, { "code": null, "e": 14614, "s": 14607, "text": "Step 3" }, { "code": null, "e": 14875, "s": 14614, "text": "‘Explode’ each of these rows into 2 identical rows except for the value of the new column being respectively Death Comp 1 and Death Comp 2. This is illustrated below. The ‘explode’ operation can be achieved using the explode_outer SQL functions within PySpark." }, { "code": null, "e": 14882, "s": 14875, "text": "Step 4" }, { "code": null, "e": 14977, "s": 14882, "text": "Create the final payout amount column, formulated with the following WHEN OTHERWISE statement." }, { "code": null, "e": 15136, "s": 14977, "text": "from pyspark.sql import functions as FF.when(col(\"Split Type\") == \"Death Comp 1\", \\F.col(\"Amount\") - F.col(\"Linked Amount\") \\.otherwise(F.col(\"Linked Amount\")" }, { "code": null, "e": 15278, "s": 15136, "text": "You should be able to see that after removing rows with a 0 value in the “Final Amount” column, the transformation is complete per Chart 2.2." }, { "code": null, "e": 15299, "s": 15278, "text": "Summary — use case 2" }, { "code": null, "e": 15561, "s": 15299, "text": "To summarise, this use case represents a transformation which requires rows corresponding to the Death covers in a dataframe to be split into separate rows if the same policyholder also has a Trauma cover. This is not easily achievable with operations in Excel." }, { "code": null, "e": 15696, "s": 15561, "text": "It has been demonstrated in the use case that such transformation is easily achievable with PySpark, which offers users the following:" }, { "code": null, "e": 16080, "s": 15696, "text": "Ability to create a window over a subset of the data (e.g. for each policyholder using Policyholder ID field) and extract information at this level. For this instance, this identified whether the policyholder has both the Death and Trauma covers, and if the policyholder does, populated the payout amount for the Trauma cover in the row of the Death cover per Step 1 of the use case." }, { "code": null, "e": 16246, "s": 16080, "text": "Ability to insert a column in a dataframe of the array data type, which makes operations like splitting possible with built-in SQL functions such as ‘explode_outer’." }, { "code": null, "e": 16571, "s": 16246, "text": "Efficiency at which the transformation is done compared to Excel, as PySpark is known for its speed for operations in large datasets/dataframes. This is critical as we extrapolate the use case to cover types apart from Death and Trauma, as well as to all the policyholders for commercial use within a life insurance company." }, { "code": null, "e": 16848, "s": 16571, "text": "Data science, machine learning may still seem like distant words to a life insurance actuary in 2021, but they are closer to home than one might think. Personally (and commercially), it takes a bit of a effort to break the barrier to entry which will eventually be worthwhile." } ]
Balanced Prime - GeeksforGeeks
06 May, 2021 In number theory, a Balanced Prime is a prime number with equal-sized prime gaps above and below it, so that it is equal to the arithmetic mean of the nearest primes above and below. Or to put it algebraically, given a prime number pn, where n is its index in the ordered set of prime numbers,First few balanced prime are 5, 53, 157, 173......Given a positive integer N. The task is to print Nth balanced prime number. Examples: Input : n = 2 Output : 53 Input : n = 3 Output : 157 The idea is to generate prime numbers using Sieve of Eratosthenes and store it in an array. Now iterate over the array to check whether it is balanced prime or not and keep counting the balanced prime. Once you reach the nth prime, return it.Below is the implementation of this approach: C++ Java Python3 PHP C# Javascript // CPP Program to find Nth Balanced Prime#include<bits/stdc++.h>#define MAX 501using namespace std; // Return the Nth balanced prime.int balancedprime(int n){ // Sieve of Eratosthenes bool prime[MAX+1]; memset(prime, true, sizeof(prime)); for (int p = 2; p*p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p*2; i <= MAX; i += p) prime[i] = false; } } // storing all primes vector<int> v; for (int p = 3; p <= MAX; p += 2) if (prime[p]) v.push_back(p); int count = 0; // Finding the Nth balanced Prime for (int i = 1; i < v.size(); i++) { if (v[i] == (v[i+1] + v[i - 1])/2) count++; if (count == n) return v[i]; }} // Driven Programint main(){ int n = 4; cout << balancedprime(n) << endl; return 0;} // Java Program to find Nth Balanced Primeimport java.util.*; public class GFG{ static int MAX = 501; // Return the Nth balanced prime. public static int balancedprime(int n) { // Sieve of Eratosthenes boolean[] prime = new boolean[MAX+1]; for(int k = 0 ; k < MAX+1; k++) prime[k] = true; for (int p = 2; p*p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p*2; i <= MAX; i += p) prime[i] = false; } } // storing all primes Vector<Integer> v = new Vector<Integer>(); for (int p = 3; p <= MAX; p += 2) if (prime[p]) v.add(p); int count = 0; // Finding the Nth balanced Prime for (int i = 1; i < v.size(); i++) { if ((int)v.get(i) == ((int)v.get(i+1) + (int)v.get(i-1))/2) count++; if (count == n) return (int) v.get(i); } return 1; } // Driven Program public static void main(String[] args) { int n = 4; System.out.print(balancedprime(n)); }} // This code is contributed by Prasad Kshirsagar # Python3 code to find Nth Balanced Prime MAX = 501 # Return the Nth balanced prime.def balancedprime( n ): # Sieve of Eratosthenes prime = [True]*(MAX+1) p=2 while p * p <= MAX: # If prime[p] is not changed, # then it is a prime if prime[p] == True: # Update all multiples of p i = p * 2 while i <= MAX: prime[i] = False i = i + p p = p +1 # storing all primes v = list() p = 3 while p <= MAX: if prime[p]: v.append(p) p = p + 2 count = 0 # Finding the Nth balanced Prime i=1 for i in range(len(v)): if v[i] == (v[i+1] + v[i - 1])/2: count += 1 if count == n: return v[i] # Driven Programn = 4print(balancedprime(n)) # This code is contributed by "Sharad_Bhardwaj". <?php// PHP Program to find Nth Balanced Prime $MAX=501; // Return the Nth balanced prime.function balancedprime($n){ global $MAX; // Sieve of Eratosthenes $prime=array_fill(0,$MAX+1,true); for ($p = 2; $p*$p <= $MAX; $p++) { // If prime[p] is not changed, then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p*2; $i <= $MAX; $i += $p) $prime[$i] = false; } } // storing all primes $v=array(); for ($p = 3; $p <= $MAX; $p += 2) if ($prime[$p]) array_push($v,$p); $count = 0; // Finding the Nth balanced Prime for ($i = 1; $i < count($v); $i++) { if ($v[$i] == ($v[$i+1] + $v[$i - 1])/2) $count++; if ($count == $n) return $v[$i]; }} // Driven Program $n = 4;echo balancedprime($n); // this code is contributed by mits.?> // C# Program to find Nth Balanced Primeusing System;using System.Collections.Generic;public class GFG{ static int MAX = 501; // Return the Nth balanced prime. public static int balancedprime(int n) { // Sieve of Eratosthenes bool[] prime = new bool[MAX+1]; for(int k = 0 ; k < MAX+1; k++) prime[k] = true; for (int p = 2; p*p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p*2; i <= MAX; i += p) prime[i] = false; } } // storing all primes List<int> v = new List<int>(); for (int p = 3; p <= MAX; p += 2) if (prime[p]) v.Add(p); int c = 0; // Finding the Nth balanced Prime for (int i = 1; i < v.Count-1; i++) { if ((int)v[i]==(int)(v[i+1]+v[i-1])/2) c++; if (c == n) return (int) v[i]; } return 1; } // Driven Program public static void Main() { int n = 4; Console.WriteLine(balancedprime(n)); }} // This code is contributed by mits <script> // Javascript Program to find Nth Balanced Prime var MAX = 501; // Return the Nth balanced prime.function balancedprime(n){ // Sieve of Eratosthenes var prime = Array(MAX+1).fill(true); for (var p = 2; p*p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (var i = p*2; i <= MAX; i += p) prime[i] = false; } } // storing all primes var v = []; for (var p = 3; p <= MAX; p += 2) if (prime[p]) v.push(p); var count = 0; // Finding the Nth balanced Prime for (var i = 1; i < v.length; i++) { if (v[i] == (v[i+1] + v[i - 1])/2) count++; if (count == n) return v[i]; }} // Driven Programvar n = 4; document.write( balancedprime(n) ); </script> Output: 173 Prasad_Kshirsagar Mithun Kumar noob2000 Prime Number sieve Mathematical Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Singular Value Decomposition (SVD) Check if a number is Palindrome Segment Tree | Set 1 (Sum of given range) How to check if a given point lies inside or outside a polygon? Program to multiply two matrices Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space
[ { "code": null, "e": 26073, "s": 26045, "text": "\n06 May, 2021" }, { "code": null, "e": 26504, "s": 26073, "text": "In number theory, a Balanced Prime is a prime number with equal-sized prime gaps above and below it, so that it is equal to the arithmetic mean of the nearest primes above and below. Or to put it algebraically, given a prime number pn, where n is its index in the ordered set of prime numbers,First few balanced prime are 5, 53, 157, 173......Given a positive integer N. The task is to print Nth balanced prime number. Examples: " }, { "code": null, "e": 26558, "s": 26504, "text": "Input : n = 2\nOutput : 53\n\nInput : n = 3\nOutput : 157" }, { "code": null, "e": 26850, "s": 26560, "text": "The idea is to generate prime numbers using Sieve of Eratosthenes and store it in an array. Now iterate over the array to check whether it is balanced prime or not and keep counting the balanced prime. Once you reach the nth prime, return it.Below is the implementation of this approach: " }, { "code": null, "e": 26854, "s": 26850, "text": "C++" }, { "code": null, "e": 26859, "s": 26854, "text": "Java" }, { "code": null, "e": 26867, "s": 26859, "text": "Python3" }, { "code": null, "e": 26871, "s": 26867, "text": "PHP" }, { "code": null, "e": 26874, "s": 26871, "text": "C#" }, { "code": null, "e": 26885, "s": 26874, "text": "Javascript" }, { "code": "// CPP Program to find Nth Balanced Prime#include<bits/stdc++.h>#define MAX 501using namespace std; // Return the Nth balanced prime.int balancedprime(int n){ // Sieve of Eratosthenes bool prime[MAX+1]; memset(prime, true, sizeof(prime)); for (int p = 2; p*p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p*2; i <= MAX; i += p) prime[i] = false; } } // storing all primes vector<int> v; for (int p = 3; p <= MAX; p += 2) if (prime[p]) v.push_back(p); int count = 0; // Finding the Nth balanced Prime for (int i = 1; i < v.size(); i++) { if (v[i] == (v[i+1] + v[i - 1])/2) count++; if (count == n) return v[i]; }} // Driven Programint main(){ int n = 4; cout << balancedprime(n) << endl; return 0;}", "e": 27855, "s": 26885, "text": null }, { "code": "// Java Program to find Nth Balanced Primeimport java.util.*; public class GFG{ static int MAX = 501; // Return the Nth balanced prime. public static int balancedprime(int n) { // Sieve of Eratosthenes boolean[] prime = new boolean[MAX+1]; for(int k = 0 ; k < MAX+1; k++) prime[k] = true; for (int p = 2; p*p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p*2; i <= MAX; i += p) prime[i] = false; } } // storing all primes Vector<Integer> v = new Vector<Integer>(); for (int p = 3; p <= MAX; p += 2) if (prime[p]) v.add(p); int count = 0; // Finding the Nth balanced Prime for (int i = 1; i < v.size(); i++) { if ((int)v.get(i) == ((int)v.get(i+1) + (int)v.get(i-1))/2) count++; if (count == n) return (int) v.get(i); } return 1; } // Driven Program public static void main(String[] args) { int n = 4; System.out.print(balancedprime(n)); }} // This code is contributed by Prasad Kshirsagar", "e": 29325, "s": 27855, "text": null }, { "code": "# Python3 code to find Nth Balanced Prime MAX = 501 # Return the Nth balanced prime.def balancedprime( n ): # Sieve of Eratosthenes prime = [True]*(MAX+1) p=2 while p * p <= MAX: # If prime[p] is not changed, # then it is a prime if prime[p] == True: # Update all multiples of p i = p * 2 while i <= MAX: prime[i] = False i = i + p p = p +1 # storing all primes v = list() p = 3 while p <= MAX: if prime[p]: v.append(p) p = p + 2 count = 0 # Finding the Nth balanced Prime i=1 for i in range(len(v)): if v[i] == (v[i+1] + v[i - 1])/2: count += 1 if count == n: return v[i] # Driven Programn = 4print(balancedprime(n)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 30227, "s": 29325, "text": null }, { "code": "<?php// PHP Program to find Nth Balanced Prime $MAX=501; // Return the Nth balanced prime.function balancedprime($n){ global $MAX; // Sieve of Eratosthenes $prime=array_fill(0,$MAX+1,true); for ($p = 2; $p*$p <= $MAX; $p++) { // If prime[p] is not changed, then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p*2; $i <= $MAX; $i += $p) $prime[$i] = false; } } // storing all primes $v=array(); for ($p = 3; $p <= $MAX; $p += 2) if ($prime[$p]) array_push($v,$p); $count = 0; // Finding the Nth balanced Prime for ($i = 1; $i < count($v); $i++) { if ($v[$i] == ($v[$i+1] + $v[$i - 1])/2) $count++; if ($count == $n) return $v[$i]; }} // Driven Program $n = 4;echo balancedprime($n); // this code is contributed by mits.?>", "e": 31151, "s": 30227, "text": null }, { "code": "// C# Program to find Nth Balanced Primeusing System;using System.Collections.Generic;public class GFG{ static int MAX = 501; // Return the Nth balanced prime. public static int balancedprime(int n) { // Sieve of Eratosthenes bool[] prime = new bool[MAX+1]; for(int k = 0 ; k < MAX+1; k++) prime[k] = true; for (int p = 2; p*p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p*2; i <= MAX; i += p) prime[i] = false; } } // storing all primes List<int> v = new List<int>(); for (int p = 3; p <= MAX; p += 2) if (prime[p]) v.Add(p); int c = 0; // Finding the Nth balanced Prime for (int i = 1; i < v.Count-1; i++) { if ((int)v[i]==(int)(v[i+1]+v[i-1])/2) c++; if (c == n) return (int) v[i]; } return 1; } // Driven Program public static void Main() { int n = 4; Console.WriteLine(balancedprime(n)); }} // This code is contributed by mits", "e": 32501, "s": 31151, "text": null }, { "code": "<script> // Javascript Program to find Nth Balanced Prime var MAX = 501; // Return the Nth balanced prime.function balancedprime(n){ // Sieve of Eratosthenes var prime = Array(MAX+1).fill(true); for (var p = 2; p*p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (var i = p*2; i <= MAX; i += p) prime[i] = false; } } // storing all primes var v = []; for (var p = 3; p <= MAX; p += 2) if (prime[p]) v.push(p); var count = 0; // Finding the Nth balanced Prime for (var i = 1; i < v.length; i++) { if (v[i] == (v[i+1] + v[i - 1])/2) count++; if (count == n) return v[i]; }} // Driven Programvar n = 4; document.write( balancedprime(n) ); </script>", "e": 33401, "s": 32501, "text": null }, { "code": null, "e": 33411, "s": 33401, "text": "Output: " }, { "code": null, "e": 33415, "s": 33411, "text": "173" }, { "code": null, "e": 33435, "s": 33417, "text": "Prasad_Kshirsagar" }, { "code": null, "e": 33448, "s": 33435, "text": "Mithun Kumar" }, { "code": null, "e": 33457, "s": 33448, "text": "noob2000" }, { "code": null, "e": 33470, "s": 33457, "text": "Prime Number" }, { "code": null, "e": 33476, "s": 33470, "text": "sieve" }, { "code": null, "e": 33489, "s": 33476, "text": "Mathematical" }, { "code": null, "e": 33502, "s": 33489, "text": "Mathematical" }, { "code": null, "e": 33515, "s": 33502, "text": "Prime Number" }, { "code": null, "e": 33521, "s": 33515, "text": "sieve" }, { "code": null, "e": 33619, "s": 33521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33663, "s": 33619, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 33694, "s": 33663, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33719, "s": 33694, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 33754, "s": 33719, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 33786, "s": 33754, "text": "Check if a number is Palindrome" }, { "code": null, "e": 33828, "s": 33786, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 33892, "s": 33828, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 33925, "s": 33892, "text": "Program to multiply two matrices" }, { "code": null, "e": 33960, "s": 33925, "text": "Count ways to reach the n'th stair" } ]
Validation Curve - GeeksforGeeks
22 Apr, 2021 A Validation Curve is an important diagnostic tool that shows the sensitivity between to changes in a Machine Learning model’s accuracy with change in some parameter of the model. A validation curve is typically drawn between some parameter of the model and the model’s score. Two curves are present in a validation curve – one for the training set score and one for the cross-validation score. By default, the function for validation curve, present in the scikit-learn library performs 3-fold cross-validation. A validation curve is used to evaluate an existing model based on hyper-parameters and is not used to tune a model. This is because, if we tune the model according to the validation score, the model may be biased towards the specific data against which the model is tuned; thereby, not being a good estimate of the generalization of the model.Interpreting a Validation Curve Interpreting the results of a validation curve can sometimes be tricky. Keep the following points in mind while looking at a validation curve : Ideally, we would want both the validation curve and the training curve to look as similar as possible. If both scores are low, the model is likely to be underfitting. This means either the model is too simple or it is informed by too few features. It could also be the case that the model is regularized too much. If the training curve reaches a high score relatively quickly and the validation curve is lagging behind, the model is overfitting. This means the model is very complex and there is too little data; or it could simply mean there is too little data. We would want the value of the parameter where the training and validation curves are closest to each other. Implementation of Validation Curves in Python : For the sake of simplicity, in this example, we will use the very popular, ‘digits‘ dataset. More Information about this dataset is available in the link below: https://scikit-learn.org/stable/auto_examples/datasets/plot_digits_last_imageFor this example, we will use k-Nearest Neighbour classifier and will plot the accuracy of the model on the training set score and the cross-validation score against the value of ‘k’, i.e., the number of neighbours to consider.Code: Python code to implement 5-fold cross-validation and to test the value of ‘k’ from 1 to 10. python3 # Import Required librariesimport matplotlib.pyplot as pltimport numpy as npfrom sklearn.datasets import load_digitsfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import validation_curve # Loading datasetdataset = load_digits() # X contains the data and y contains the labelsX, y = dataset.data, dataset.target # Setting the range for the parameter (from 1 to 10)parameter_range = np.arange(1, 10, 1) # Calculate accuracy on training and test set using the# gamma parameter with 5-fold cross validationtrain_score, test_score = validation_curve(KNeighborsClassifier(), X, y, param_name = "n_neighbors", param_range = parameter_range, cv = 5, scoring = "accuracy") # Calculating mean and standard deviation of training scoremean_train_score = np.mean(train_score, axis = 1)std_train_score = np.std(train_score, axis = 1) # Calculating mean and standard deviation of testing scoremean_test_score = np.mean(test_score, axis = 1)std_test_score = np.std(test_score, axis = 1) # Plot mean accuracy scores for training and testing scoresplt.plot(parameter_range, mean_train_score, label = "Training Score", color = 'b')plt.plot(parameter_range, mean_test_score, label = "Cross Validation Score", color = 'g') # Creating the plotplt.title("Validation Curve with KNN Classifier")plt.xlabel("Number of Neighbours")plt.ylabel("Accuracy")plt.tight_layout()plt.legend(loc = 'best')plt.show() Output: From this graph, we can observe that ‘k’ = 2 would be the ideal value of k. As the number of neighbours (k) increases, both the accuracy of Training Score as well as the cross-validation score decreases. simmytarika5 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm Intuition of Adam Optimizer Introduction to Recurrent Neural Network CNN | Introduction to Pooling Layer Singular Value Decomposition (SVD) Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25699, "s": 25671, "text": "\n22 Apr, 2021" }, { "code": null, "e": 26732, "s": 25699, "text": "A Validation Curve is an important diagnostic tool that shows the sensitivity between to changes in a Machine Learning model’s accuracy with change in some parameter of the model. A validation curve is typically drawn between some parameter of the model and the model’s score. Two curves are present in a validation curve – one for the training set score and one for the cross-validation score. By default, the function for validation curve, present in the scikit-learn library performs 3-fold cross-validation. A validation curve is used to evaluate an existing model based on hyper-parameters and is not used to tune a model. This is because, if we tune the model according to the validation score, the model may be biased towards the specific data against which the model is tuned; thereby, not being a good estimate of the generalization of the model.Interpreting a Validation Curve Interpreting the results of a validation curve can sometimes be tricky. Keep the following points in mind while looking at a validation curve : " }, { "code": null, "e": 26836, "s": 26732, "text": "Ideally, we would want both the validation curve and the training curve to look as similar as possible." }, { "code": null, "e": 27047, "s": 26836, "text": "If both scores are low, the model is likely to be underfitting. This means either the model is too simple or it is informed by too few features. It could also be the case that the model is regularized too much." }, { "code": null, "e": 27296, "s": 27047, "text": "If the training curve reaches a high score relatively quickly and the validation curve is lagging behind, the model is overfitting. This means the model is very complex and there is too little data; or it could simply mean there is too little data." }, { "code": null, "e": 27405, "s": 27296, "text": "We would want the value of the parameter where the training and validation curves are closest to each other." }, { "code": null, "e": 28017, "s": 27405, "text": "Implementation of Validation Curves in Python : For the sake of simplicity, in this example, we will use the very popular, ‘digits‘ dataset. More Information about this dataset is available in the link below: https://scikit-learn.org/stable/auto_examples/datasets/plot_digits_last_imageFor this example, we will use k-Nearest Neighbour classifier and will plot the accuracy of the model on the training set score and the cross-validation score against the value of ‘k’, i.e., the number of neighbours to consider.Code: Python code to implement 5-fold cross-validation and to test the value of ‘k’ from 1 to 10. " }, { "code": null, "e": 28025, "s": 28017, "text": "python3" }, { "code": "# Import Required librariesimport matplotlib.pyplot as pltimport numpy as npfrom sklearn.datasets import load_digitsfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import validation_curve # Loading datasetdataset = load_digits() # X contains the data and y contains the labelsX, y = dataset.data, dataset.target # Setting the range for the parameter (from 1 to 10)parameter_range = np.arange(1, 10, 1) # Calculate accuracy on training and test set using the# gamma parameter with 5-fold cross validationtrain_score, test_score = validation_curve(KNeighborsClassifier(), X, y, param_name = \"n_neighbors\", param_range = parameter_range, cv = 5, scoring = \"accuracy\") # Calculating mean and standard deviation of training scoremean_train_score = np.mean(train_score, axis = 1)std_train_score = np.std(train_score, axis = 1) # Calculating mean and standard deviation of testing scoremean_test_score = np.mean(test_score, axis = 1)std_test_score = np.std(test_score, axis = 1) # Plot mean accuracy scores for training and testing scoresplt.plot(parameter_range, mean_train_score, label = \"Training Score\", color = 'b')plt.plot(parameter_range, mean_test_score, label = \"Cross Validation Score\", color = 'g') # Creating the plotplt.title(\"Validation Curve with KNN Classifier\")plt.xlabel(\"Number of Neighbours\")plt.ylabel(\"Accuracy\")plt.tight_layout()plt.legend(loc = 'best')plt.show()", "e": 29557, "s": 28025, "text": null }, { "code": null, "e": 29567, "s": 29557, "text": "Output: " }, { "code": null, "e": 29772, "s": 29567, "text": "From this graph, we can observe that ‘k’ = 2 would be the ideal value of k. As the number of neighbours (k) increases, both the accuracy of Training Score as well as the cross-validation score decreases. " }, { "code": null, "e": 29785, "s": 29772, "text": "simmytarika5" }, { "code": null, "e": 29802, "s": 29785, "text": "Machine Learning" }, { "code": null, "e": 29809, "s": 29802, "text": "Python" }, { "code": null, "e": 29826, "s": 29809, "text": "Machine Learning" }, { "code": null, "e": 29924, "s": 29826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29957, "s": 29924, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29985, "s": 29957, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 30026, "s": 29985, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 30062, "s": 30026, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 30097, "s": 30062, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 30125, "s": 30097, "text": "Read JSON file using Python" }, { "code": null, "e": 30175, "s": 30125, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30197, "s": 30175, "text": "Python map() function" } ]
Implement multiple conditions in MongoDB?
Let us first create a collection with documents − > db.multipleConditionDemo.insertOne({"_id":1,"Name":"John"}); { "acknowledged" : true, "insertedId" : 1 } > db.multipleConditionDemo.insertOne({"_id":2,"Name":"Carol"}); { "acknowledged" : true, "insertedId" : 2 } > db.multipleConditionDemo.insertOne({"_id":3,"Name":"Sam"}); { "acknowledged" : true, "insertedId" : 3 } > db.multipleConditionDemo.insertOne({"_id":4,"Name":"David"}); { "acknowledged" : true, "insertedId" : 4 } Following is the query to display all documents from a collection with the help of find() method − > db.multipleConditionDemo.find().pretty(); This will produce the following output − { "_id" : 1, "Name" : "John" } { "_id" : 2, "Name" : "Carol" } { "_id" : 3, "Name" : "Sam" } { "_id" : 4, "Name" : "David" } Following is the query to implement multiple conditions in WHERE clause − > db.multipleConditionDemo.remove({ $or: [ { _id: 2 }, { _id: 3 } ] }); WriteResult({ "nRemoved" : 2 }) Let us check the documents from the above collection once again − > db.multipleConditionDemo.find().pretty(); This will produce the following output − { "_id" : 1, "Name" : "John" } { "_id" : 4, "Name" : "David" }
[ { "code": null, "e": 1112, "s": 1062, "text": "Let us first create a collection with documents −" }, { "code": null, "e": 1541, "s": 1112, "text": "> db.multipleConditionDemo.insertOne({\"_id\":1,\"Name\":\"John\"});\n{ \"acknowledged\" : true, \"insertedId\" : 1 }\n> db.multipleConditionDemo.insertOne({\"_id\":2,\"Name\":\"Carol\"});\n{ \"acknowledged\" : true, \"insertedId\" : 2 }\n> db.multipleConditionDemo.insertOne({\"_id\":3,\"Name\":\"Sam\"});\n{ \"acknowledged\" : true, \"insertedId\" : 3 }\n> db.multipleConditionDemo.insertOne({\"_id\":4,\"Name\":\"David\"});\n{ \"acknowledged\" : true, \"insertedId\" : 4 }" }, { "code": null, "e": 1640, "s": 1541, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1684, "s": 1640, "text": "> db.multipleConditionDemo.find().pretty();" }, { "code": null, "e": 1725, "s": 1684, "text": "This will produce the following output −" }, { "code": null, "e": 1850, "s": 1725, "text": "{ \"_id\" : 1, \"Name\" : \"John\" }\n{ \"_id\" : 2, \"Name\" : \"Carol\" }\n{ \"_id\" : 3, \"Name\" : \"Sam\" }\n{ \"_id\" : 4, \"Name\" : \"David\" }" }, { "code": null, "e": 1924, "s": 1850, "text": "Following is the query to implement multiple conditions in WHERE clause −" }, { "code": null, "e": 2028, "s": 1924, "text": "> db.multipleConditionDemo.remove({ $or: [ { _id: 2 }, { _id: 3 } ] });\nWriteResult({ \"nRemoved\" : 2 })" }, { "code": null, "e": 2094, "s": 2028, "text": "Let us check the documents from the above collection once again −" }, { "code": null, "e": 2138, "s": 2094, "text": "> db.multipleConditionDemo.find().pretty();" }, { "code": null, "e": 2179, "s": 2138, "text": "This will produce the following output −" }, { "code": null, "e": 2242, "s": 2179, "text": "{ \"_id\" : 1, \"Name\" : \"John\" }\n{ \"_id\" : 4, \"Name\" : \"David\" }" } ]
Properties elements() method in Java with Examples - GeeksforGeeks
11 Aug, 2021 The elements() method of Properties class is used to get the enumeration of this Properties object. It can be further used to retrieve the elements sequentially using this Enumeration received. Syntax: public Enumeration elements() Parameters: This method do not accepts any parameters.Returns: This method returns an Enumeration of the values in this Properties object.Below programs illustrate the elements() method:Program 1: Java // Java program to demonstrate// elements() method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put("Pen", 10); properties.put("Book", 500); properties.put("Clothes", 400); properties.put("Mobile", 5000); // Print Properties details System.out.println("Current Properties: " + properties.toString()); // Creating an empty enumeration to store Enumeration enu = properties.elements(); System.out.println("The enumeration of values are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }} Current Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400} The enumeration of values are: 500 5000 10 400 Program 2: Java // Java program to demonstrate// elements() method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(1, "100RS"); properties.put(2, "500RS"); properties.put(3, "1000RS"); // print Properties details System.out.println("Current Properties: " + properties.toString()); // Creating an empty enumeration to store Enumeration enu = properties.elements(); System.out.println("The enumeration of values are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }} Current Properties: {3=1000RS, 2=500RS, 1=100RS} The enumeration of values are: 1000RS 500RS 100RS References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#elements– nidhi_biet as5853535 Java - util package Java-Functions Java-Properties 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 Stream In Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multithreading in Java
[ { "code": null, "e": 26203, "s": 26175, "text": "\n11 Aug, 2021" }, { "code": null, "e": 26398, "s": 26203, "text": "The elements() method of Properties class is used to get the enumeration of this Properties object. It can be further used to retrieve the elements sequentially using this Enumeration received. " }, { "code": null, "e": 26408, "s": 26398, "text": "Syntax: " }, { "code": null, "e": 26438, "s": 26408, "text": "public Enumeration elements()" }, { "code": null, "e": 26637, "s": 26438, "text": "Parameters: This method do not accepts any parameters.Returns: This method returns an Enumeration of the values in this Properties object.Below programs illustrate the elements() method:Program 1: " }, { "code": null, "e": 26642, "s": 26637, "text": "Java" }, { "code": "// Java program to demonstrate// elements() method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(\"Pen\", 10); properties.put(\"Book\", 500); properties.put(\"Clothes\", 400); properties.put(\"Mobile\", 5000); // Print Properties details System.out.println(\"Current Properties: \" + properties.toString()); // Creating an empty enumeration to store Enumeration enu = properties.elements(); System.out.println(\"The enumeration of values are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}", "e": 27486, "s": 26642, "text": null }, { "code": null, "e": 27598, "s": 27486, "text": "Current Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}\nThe enumeration of values are:\n500\n5000\n10\n400" }, { "code": null, "e": 27612, "s": 27600, "text": "Program 2: " }, { "code": null, "e": 27617, "s": 27612, "text": "Java" }, { "code": "// Java program to demonstrate// elements() method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(1, \"100RS\"); properties.put(2, \"500RS\"); properties.put(3, \"1000RS\"); // print Properties details System.out.println(\"Current Properties: \" + properties.toString()); // Creating an empty enumeration to store Enumeration enu = properties.elements(); System.out.println(\"The enumeration of values are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}", "e": 28420, "s": 27617, "text": null }, { "code": null, "e": 28519, "s": 28420, "text": "Current Properties: {3=1000RS, 2=500RS, 1=100RS}\nThe enumeration of values are:\n1000RS\n500RS\n100RS" }, { "code": null, "e": 28611, "s": 28521, "text": "References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#elements–" }, { "code": null, "e": 28622, "s": 28611, "text": "nidhi_biet" }, { "code": null, "e": 28632, "s": 28622, "text": "as5853535" }, { "code": null, "e": 28652, "s": 28632, "text": "Java - util package" }, { "code": null, "e": 28667, "s": 28652, "text": "Java-Functions" }, { "code": null, "e": 28683, "s": 28667, "text": "Java-Properties" }, { "code": null, "e": 28688, "s": 28683, "text": "Java" }, { "code": null, "e": 28693, "s": 28688, "text": "Java" }, { "code": null, "e": 28791, "s": 28693, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28842, "s": 28791, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28857, "s": 28842, "text": "Stream In Java" }, { "code": null, "e": 28887, "s": 28857, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28906, "s": 28887, "text": "Interfaces in Java" }, { "code": null, "e": 28937, "s": 28906, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28955, "s": 28937, "text": "ArrayList in Java" }, { "code": null, "e": 28987, "s": 28955, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29007, "s": 28987, "text": "Stack Class in Java" }, { "code": null, "e": 29031, "s": 29007, "text": "Singleton Class in Java" } ]
Count Magic squares in a grid - GeeksforGeeks
17 Nov, 2021 Given an Grid of integers. The task is to find total numbers of 3 x 3 (contiguous) Magic Square subgrids in the given grid. A Magic square is a 3 x 3 grid filled with all distinct numbers from 1 to 9 such that each row, column, and both diagonals have equal sum.Examples: Input: G = { { 4, 3, 8, 4 }, { 9, 5, 1, 9 }, { 2, 7, 6, 2 } } Output: 1 Explanation: The following subgrid is a 3 x 3 magic square: [ 4 3 8, 9 5 1, 2 7 6 ]Input : G = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 10, 11, 12, 13, 14 }, { 15, 16, 17, 18, 19 } } Output : 0 Approach: Let us check every 3 x 3 subgrid individually. For each grid, all numbers must be unique and between (1 and 9) also every rows, columns, and both diagonals must have the equal sum.Also notice the fact that a subgrid is a Magic Square if its middle element is 5. Because adding the 12 values from the four lines that crosses the center, add up to 60, but they also add up to the entire grid (45), plus 3 times the middle value. This implies the middle value is 5. Hence we can check this condition which help us skip over various subgrids. You can learn more about Magic_square here or here.The procedure to check for a subgrid to be a Magic Square is as follows: The middle element must be 5. The sum of the grid must be 45, and contains all distinct values from 1 to 9. Each horizontal(row) and vertical(column) must add up to 15. Both of the diagonal lines must also sum to 15. Below is the implementation of above approach: C++ Python3 C# Javascript // CPP program to count magic squares#include <bits/stdc++.h>using namespace std; const int R = 3;const int C = 4; // function to check is subgrid is Magic Squareint magic(int a, int b, int c, int d, int e, int f, int g, int h, int i){ set<int> s1 = { a, b, c, d, e, f, g, h, i }, s2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Elements of grid must contain all numbers from 1 to // 9, sum of all rows, columns and diagonals must be // same, i.e., 15. if (s1 == s2 && (a + b + c) == 15 && (d + e + f) == 15 && (g + h + i) == 15 && (a + d + g) == 15 && (b + e + h) == 15 && (c + f + i) == 15 && (a + e + i) == 15 && (c + e + g) == 15) return true; return false; } // Function to count total Magic square subgridsint CountMagicSquare(int Grid[R][C]){ int ans = 0; for (int i = 0; i < R - 2; i++) for (int j = 0; j < C - 2; j++) { // if condition true skip check if (Grid[i + 1][j + 1] != 5) continue; // check for magic square subgrid if (magic(Grid[i][j], Grid[i][j + 1], Grid[i][j + 2], Grid[i + 1][j], Grid[i + 1][j + 1], Grid[i + 1][j + 2], Grid[i + 2][j], Grid[i + 2][j + 1], Grid[i + 2][j + 2])) ans += 1; cout<<"ans = "<<ans<<endl; } // return total magic square return ans;} // Driver programint main(){ int G[R][C] = { { 4, 3, 8, 4 }, { 9, 5, 1, 9 }, { 2, 7, 6, 2 } }; // function call to print required answer cout << CountMagicSquare(G); return 0;} // This code is written by Sanjit_Prasad # Python3 program to count magic squaresR = 3C = 4 # function to check is subgrid is Magic Squaredef magic(a, b, c, d, e, f, g, h, i): s1 = set([a, b, c, d, e, f, g, h, i]) s2 = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) # Elements of grid must contain all numbers # from 1 to 9, sum of all rows, columns and # diagonals must be same, i.e., 15. if (s1 == s2 and (a + b + c) == 15 and (d + e + f) == 15 and (g + h + i) == 15 and (a + d + g) == 15 and (b + e + h) == 15 and (c + f + i) == 15 and (a + e + i) == 15 and (c + e + g) == 15): return True return false # Function to count total Magic square subgridsdef CountMagicSquare(Grid): ans = 0 for i in range(0, R - 2): for j in range(0, C - 2): # if condition true skip check if Grid[i + 1][j + 1] != 5: continue # check for magic square subgrid if (magic(Grid[i][j], Grid[i][j + 1], Grid[i][j + 2], Grid[i + 1][j], Grid[i + 1][j + 1], Grid[i + 1][j + 2], Grid[i + 2][j], Grid[i + 2][j + 1], Grid[i + 2][j + 2]) == True): ans += 1 # return total magic square return ans # Driver Codeif __name__ == "__main__": G = [[4, 3, 8, 4], [9, 5, 1, 9], [2, 7, 6, 2]] # Function call to print required answer print(CountMagicSquare(G)) # This code is contributed by Rituraj Jain // C# program to count magic squaresusing System;using System.Collections.Generic; class GFg { const int R = 3; const int C = 4; // function to check is subgrid is Magic Square static int magic(int a, int b, int c, int d, int e, int f, int g, int h, int i) { HashSet<int> s1 = new HashSet<int>() { a, b, c, d, e, f, g, h, i }; HashSet<int> s2 = new HashSet<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Elements of grid must contain all numbers from 1 // to 9, sum of all rows, columns and diagonals must // be same, i.e., 15. if (s1.SetEquals(s2) && (a + b + c) == 15 && (d + e + f) == 15 && (g + h + i) == 15 && (a + d + g) == 15 && (b + e + h) == 15 && (c + f + i) == 15 && (a + e + i) == 15 && (c + e + g) == 15) return 1; return 0; } // Function to count total Magic square subgrids static int CountMagicSquare(int[, ] Grid) { int ans = 0; for (int i = 0; i < R - 2; i++) for (int j = 0; j < C - 2; j++) { // if condition true skip check if (Grid[i + 1, j + 1] != 5) continue; // check for magic square subgrid if (magic(Grid[i, j], Grid[i, j + 1], Grid[i, j + 2], Grid[i + 1, j], Grid[i + 1, j + 1], Grid[i + 1, j + 2], Grid[i + 2, j], Grid[i + 2, j + 1], Grid[i + 2, j + 2]) != 0) ans += 1; } // return total magic square return ans; } // Driver program public static void Main() { int[, ] G = { { 4, 3, 8, 4 }, { 9, 5, 1, 9 }, { 2, 7, 6, 2 } }; // function call to print required answer Console.WriteLine(CountMagicSquare(G)); }} // This code is contributed by ukasp. <script> // JavaScript program to count magic squaresvar R = 3;var C = 4; function eqSet(as, bs) { if (as.size !== bs.size) return false; for (var a of as) if (!bs.has(a)) return false; return true;} // function to check is subgrid is Magic Squarefunction magic(a, b, c, d, e, f, g, h, i){ var s1 = new Set([a, b, c, d, e, f, g, h, i]); var s2 = new Set([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]); // Elements of grid must contain all numbers from 1 to // 9, sum of all rows, columns and diagonals must be // same, i.e., 15. if (eqSet(s1, s2) && (a + b + c) == 15 && (d + e + f) == 15 && (g + h + i) == 15 && (a + d + g) == 15 && (b + e + h) == 15 && (c + f + i) == 15 && (a + e + i) == 15 && (c + e + g) == 15) return true; return false; } // Function to count total Magic square subgridsfunction CountMagicSquare(Grid){ var ans = 0; for (var i = 0; i < R - 2; i++) for (var j = 0; j < C - 2; j++) { // if condition true skip check if (Grid[i + 1][j + 1] != 5) continue; // check for magic square subgrid if (magic(Grid[i][j], Grid[i][j + 1], Grid[i][j + 2], Grid[i + 1][j], Grid[i + 1][j + 1], Grid[i + 1][j + 2], Grid[i + 2][j], Grid[i + 2][j + 1], Grid[i + 2][j + 2])) ans += 1; } // return total magic square return ans;} // Driver programvar G = [[4, 3, 8, 4 ], [ 9, 5, 1, 9 ], [ 2, 7, 6, 2 ]];// function call to print required answerdocument.write( CountMagicSquare(G)); </script> 1 Time Complexity: O(R * C) rituraj_jain shubham_singh surinderdawra388 rrrtnx ukasp programming-puzzle Mathematical Matrix Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Singular Value Decomposition (SVD) Check if a number is Palindrome Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Print a given matrix in spiral form Sudoku | Backtracking-7
[ { "code": null, "e": 26073, "s": 26045, "text": "\n17 Nov, 2021" }, { "code": null, "e": 26346, "s": 26073, "text": "Given an Grid of integers. The task is to find total numbers of 3 x 3 (contiguous) Magic Square subgrids in the given grid. A Magic square is a 3 x 3 grid filled with all distinct numbers from 1 to 9 such that each row, column, and both diagonals have equal sum.Examples: " }, { "code": null, "e": 26614, "s": 26346, "text": "Input: G = { { 4, 3, 8, 4 }, { 9, 5, 1, 9 }, { 2, 7, 6, 2 } } Output: 1 Explanation: The following subgrid is a 3 x 3 magic square: [ 4 3 8, 9 5 1, 2 7 6 ]Input : G = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 10, 11, 12, 13, 14 }, { 15, 16, 17, 18, 19 } } Output : 0" }, { "code": null, "e": 27291, "s": 26616, "text": "Approach: Let us check every 3 x 3 subgrid individually. For each grid, all numbers must be unique and between (1 and 9) also every rows, columns, and both diagonals must have the equal sum.Also notice the fact that a subgrid is a Magic Square if its middle element is 5. Because adding the 12 values from the four lines that crosses the center, add up to 60, but they also add up to the entire grid (45), plus 3 times the middle value. This implies the middle value is 5. Hence we can check this condition which help us skip over various subgrids. You can learn more about Magic_square here or here.The procedure to check for a subgrid to be a Magic Square is as follows: " }, { "code": null, "e": 27321, "s": 27291, "text": "The middle element must be 5." }, { "code": null, "e": 27399, "s": 27321, "text": "The sum of the grid must be 45, and contains all distinct values from 1 to 9." }, { "code": null, "e": 27460, "s": 27399, "text": "Each horizontal(row) and vertical(column) must add up to 15." }, { "code": null, "e": 27508, "s": 27460, "text": "Both of the diagonal lines must also sum to 15." }, { "code": null, "e": 27557, "s": 27508, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27561, "s": 27557, "text": "C++" }, { "code": null, "e": 27569, "s": 27561, "text": "Python3" }, { "code": null, "e": 27572, "s": 27569, "text": "C#" }, { "code": null, "e": 27583, "s": 27572, "text": "Javascript" }, { "code": "// CPP program to count magic squares#include <bits/stdc++.h>using namespace std; const int R = 3;const int C = 4; // function to check is subgrid is Magic Squareint magic(int a, int b, int c, int d, int e, int f, int g, int h, int i){ set<int> s1 = { a, b, c, d, e, f, g, h, i }, s2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Elements of grid must contain all numbers from 1 to // 9, sum of all rows, columns and diagonals must be // same, i.e., 15. if (s1 == s2 && (a + b + c) == 15 && (d + e + f) == 15 && (g + h + i) == 15 && (a + d + g) == 15 && (b + e + h) == 15 && (c + f + i) == 15 && (a + e + i) == 15 && (c + e + g) == 15) return true; return false; } // Function to count total Magic square subgridsint CountMagicSquare(int Grid[R][C]){ int ans = 0; for (int i = 0; i < R - 2; i++) for (int j = 0; j < C - 2; j++) { // if condition true skip check if (Grid[i + 1][j + 1] != 5) continue; // check for magic square subgrid if (magic(Grid[i][j], Grid[i][j + 1], Grid[i][j + 2], Grid[i + 1][j], Grid[i + 1][j + 1], Grid[i + 1][j + 2], Grid[i + 2][j], Grid[i + 2][j + 1], Grid[i + 2][j + 2])) ans += 1; cout<<\"ans = \"<<ans<<endl; } // return total magic square return ans;} // Driver programint main(){ int G[R][C] = { { 4, 3, 8, 4 }, { 9, 5, 1, 9 }, { 2, 7, 6, 2 } }; // function call to print required answer cout << CountMagicSquare(G); return 0;} // This code is written by Sanjit_Prasad", "e": 29292, "s": 27583, "text": null }, { "code": "# Python3 program to count magic squaresR = 3C = 4 # function to check is subgrid is Magic Squaredef magic(a, b, c, d, e, f, g, h, i): s1 = set([a, b, c, d, e, f, g, h, i]) s2 = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) # Elements of grid must contain all numbers # from 1 to 9, sum of all rows, columns and # diagonals must be same, i.e., 15. if (s1 == s2 and (a + b + c) == 15 and (d + e + f) == 15 and (g + h + i) == 15 and (a + d + g) == 15 and (b + e + h) == 15 and (c + f + i) == 15 and (a + e + i) == 15 and (c + e + g) == 15): return True return false # Function to count total Magic square subgridsdef CountMagicSquare(Grid): ans = 0 for i in range(0, R - 2): for j in range(0, C - 2): # if condition true skip check if Grid[i + 1][j + 1] != 5: continue # check for magic square subgrid if (magic(Grid[i][j], Grid[i][j + 1], Grid[i][j + 2], Grid[i + 1][j], Grid[i + 1][j + 1], Grid[i + 1][j + 2], Grid[i + 2][j], Grid[i + 2][j + 1], Grid[i + 2][j + 2]) == True): ans += 1 # return total magic square return ans # Driver Codeif __name__ == \"__main__\": G = [[4, 3, 8, 4], [9, 5, 1, 9], [2, 7, 6, 2]] # Function call to print required answer print(CountMagicSquare(G)) # This code is contributed by Rituraj Jain", "e": 30766, "s": 29292, "text": null }, { "code": "// C# program to count magic squaresusing System;using System.Collections.Generic; class GFg { const int R = 3; const int C = 4; // function to check is subgrid is Magic Square static int magic(int a, int b, int c, int d, int e, int f, int g, int h, int i) { HashSet<int> s1 = new HashSet<int>() { a, b, c, d, e, f, g, h, i }; HashSet<int> s2 = new HashSet<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Elements of grid must contain all numbers from 1 // to 9, sum of all rows, columns and diagonals must // be same, i.e., 15. if (s1.SetEquals(s2) && (a + b + c) == 15 && (d + e + f) == 15 && (g + h + i) == 15 && (a + d + g) == 15 && (b + e + h) == 15 && (c + f + i) == 15 && (a + e + i) == 15 && (c + e + g) == 15) return 1; return 0; } // Function to count total Magic square subgrids static int CountMagicSquare(int[, ] Grid) { int ans = 0; for (int i = 0; i < R - 2; i++) for (int j = 0; j < C - 2; j++) { // if condition true skip check if (Grid[i + 1, j + 1] != 5) continue; // check for magic square subgrid if (magic(Grid[i, j], Grid[i, j + 1], Grid[i, j + 2], Grid[i + 1, j], Grid[i + 1, j + 1], Grid[i + 1, j + 2], Grid[i + 2, j], Grid[i + 2, j + 1], Grid[i + 2, j + 2]) != 0) ans += 1; } // return total magic square return ans; } // Driver program public static void Main() { int[, ] G = { { 4, 3, 8, 4 }, { 9, 5, 1, 9 }, { 2, 7, 6, 2 } }; // function call to print required answer Console.WriteLine(CountMagicSquare(G)); }} // This code is contributed by ukasp.", "e": 32829, "s": 30766, "text": null }, { "code": "<script> // JavaScript program to count magic squaresvar R = 3;var C = 4; function eqSet(as, bs) { if (as.size !== bs.size) return false; for (var a of as) if (!bs.has(a)) return false; return true;} // function to check is subgrid is Magic Squarefunction magic(a, b, c, d, e, f, g, h, i){ var s1 = new Set([a, b, c, d, e, f, g, h, i]); var s2 = new Set([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]); // Elements of grid must contain all numbers from 1 to // 9, sum of all rows, columns and diagonals must be // same, i.e., 15. if (eqSet(s1, s2) && (a + b + c) == 15 && (d + e + f) == 15 && (g + h + i) == 15 && (a + d + g) == 15 && (b + e + h) == 15 && (c + f + i) == 15 && (a + e + i) == 15 && (c + e + g) == 15) return true; return false; } // Function to count total Magic square subgridsfunction CountMagicSquare(Grid){ var ans = 0; for (var i = 0; i < R - 2; i++) for (var j = 0; j < C - 2; j++) { // if condition true skip check if (Grid[i + 1][j + 1] != 5) continue; // check for magic square subgrid if (magic(Grid[i][j], Grid[i][j + 1], Grid[i][j + 2], Grid[i + 1][j], Grid[i + 1][j + 1], Grid[i + 1][j + 2], Grid[i + 2][j], Grid[i + 2][j + 1], Grid[i + 2][j + 2])) ans += 1; } // return total magic square return ans;} // Driver programvar G = [[4, 3, 8, 4 ], [ 9, 5, 1, 9 ], [ 2, 7, 6, 2 ]];// function call to print required answerdocument.write( CountMagicSquare(G)); </script>", "e": 34478, "s": 32829, "text": null }, { "code": null, "e": 34480, "s": 34478, "text": "1" }, { "code": null, "e": 34509, "s": 34482, "text": "Time Complexity: O(R * C) " }, { "code": null, "e": 34522, "s": 34509, "text": "rituraj_jain" }, { "code": null, "e": 34536, "s": 34522, "text": "shubham_singh" }, { "code": null, "e": 34553, "s": 34536, "text": "surinderdawra388" }, { "code": null, "e": 34560, "s": 34553, "text": "rrrtnx" }, { "code": null, "e": 34566, "s": 34560, "text": "ukasp" }, { "code": null, "e": 34585, "s": 34566, "text": "programming-puzzle" }, { "code": null, "e": 34598, "s": 34585, "text": "Mathematical" }, { "code": null, "e": 34605, "s": 34598, "text": "Matrix" }, { "code": null, "e": 34618, "s": 34605, "text": "Mathematical" }, { "code": null, "e": 34625, "s": 34618, "text": "Matrix" }, { "code": null, "e": 34723, "s": 34625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34767, "s": 34723, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 34798, "s": 34767, "text": "Modular multiplicative inverse" }, { "code": null, "e": 34823, "s": 34798, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 34858, "s": 34823, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 34890, "s": 34858, "text": "Check if a number is Palindrome" }, { "code": null, "e": 34925, "s": 34890, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 34969, "s": 34925, "text": "Program to find largest element in an array" }, { "code": null, "e": 35000, "s": 34969, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 35036, "s": 35000, "text": "Print a given matrix in spiral form" } ]
C++ Basics - GeeksforGeeks
06 Sep, 2021 C++ is a cross-platform language that can be used to create high-performance applications. It was developed by Bjarne Stroustrup, as an extension to the C language. The language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14, and C++17. C++ is one of the world’s most popular programming languages. C++ can be found in today’s operating systems, Graphical User Interfaces, and embedded systems. C++ is an object-oriented programming language that gives a clear structure to programs and allows code to be reused, lowering development costs. C++ is portable and can be used to develop applications that can be adapted to multiple platforms. C++ is fun and easy to learn! As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa. C++ // C++ Hello World Program#include <iostream>using namespace std;int main(){ cout << "Hello World!\n"; return 0;} Hello World! Comments: The two slash(//) signs are used to add comments in a program. It does not have any effect on the behavior or outcome of the program. It is used to give a description of the program you’re writing.#include<iostream>: #include is the pre-processor directive that is used to include files in our program. Here we are including the iostream standard file which is necessary for the declarations of basic standard input/output library in C++.Using namespace std: All elements of the standard C++ library are declared within a namespace. Here we are using the std namespace.int main(): The execution of any C++ program starts with the main function, hence it is necessary to have a main function in your program. ‘int’ is the return value of this function. (We will be studying functions in more detail later).{}: The curly brackets are used to indicate the starting and ending point of any function. Every opening bracket should have a corresponding closing bracket.cout<<”Hello World!\n”; This is a C++ statement. cout represents the standard output stream in C++. It is declared in the iostream standard file within the std namespace. The text between quotations will be printed on the screen. \n will not be printed, it is used to add a line break. Each statement in C++ ends with a semicolon (;).return 0; return signifies the end of a function. Here the function is main, so when we hit return 0, it exits the program. We are returning 0 because we mentioned the return type of the main function as integer (int main). A zero indicates that everything went fine and one indicates that something has gone wrong. Comments: The two slash(//) signs are used to add comments in a program. It does not have any effect on the behavior or outcome of the program. It is used to give a description of the program you’re writing. #include<iostream>: #include is the pre-processor directive that is used to include files in our program. Here we are including the iostream standard file which is necessary for the declarations of basic standard input/output library in C++. Using namespace std: All elements of the standard C++ library are declared within a namespace. Here we are using the std namespace. int main(): The execution of any C++ program starts with the main function, hence it is necessary to have a main function in your program. ‘int’ is the return value of this function. (We will be studying functions in more detail later). {}: The curly brackets are used to indicate the starting and ending point of any function. Every opening bracket should have a corresponding closing bracket. cout<<”Hello World!\n”; This is a C++ statement. cout represents the standard output stream in C++. It is declared in the iostream standard file within the std namespace. The text between quotations will be printed on the screen. \n will not be printed, it is used to add a line break. Each statement in C++ ends with a semicolon (;). return 0; return signifies the end of a function. Here the function is main, so when we hit return 0, it exits the program. We are returning 0 because we mentioned the return type of the main function as integer (int main). A zero indicates that everything went fine and one indicates that something has gone wrong. The header file iostream must be included to make use of the input/output (cin/cout) operators. Standard Output (cout) By default, the standard output of a program points at the screen. So with the cout operator and the “insertion” operator (фф) you can print a message onto the screen. To print the content of a variable the double quotes are not used. The << operator can be used multiple times in a single statement. It is possible to combine variables and text: The cout operator does not put a line break at the end of the output. So if you want to print two sentences you will have to use the new-line character ( \n ). It is possible to use the endl manipulator instead of the new-line character. Below is the C++ program to illustrate standard output: C++ // C++ program to implement// standard output#include <iostream>using namespace std;int main(){ cout << "Geeks For Geeks"; return 0;} Geeks For Geeks Standard input (cin) In most cases, the standard input device is the keyboard. With the cin and >> operators, it is possible to read input from the keyboard. The cin operator will always return the variable type that you use with cin. So if you request an integer you will get an integer and so on. This can cause an error when the user of the program does not return the type that you are expecting. (Example: you ask for an integer and you get a string of characters.) The cin operator is also chainable. In this case, the user must give two input values, that are separated by any valid blank separator (tab, space, or new-line). Below is the C++ program to illustrate standard input: C++ // C++ program to implement// standard input#include <iostream>using namespace std;int main(){ int a; cout << "Enter a number" << endl; // User can input an integer cin >> a; cout << "User entered number " << a << endl;} Enter a number User entered number 0 Data types are declarations for variables. This determines the type and size of data associated with variables which are essential to know since different data types occupy the different sizes of memory. 1. int This data type is used to store integers. It occupies 4 bytes in memory. It can store values from -2147483648 to 2147483647. Eg. int age = 18 2. float and double Used to store floating-point numbers (decimals and exponential) The size of a float is 4 bytes and the size of double is 8 bytes. Float is used to store up to 7 decimal digits whereas double is used to store up to 15 decimal digits. Example:float pi = 3.14.double distance = 24E8 // 24 x 108 float pi = 3.14. double distance = 24E8 // 24 x 108 3. char This data type is used to store characters. It occupies 1 byte in memory. Characters in C++ are enclosed inside single quotes ‘ ‘ ASCII code is used to store characters in memory. Example: char ch =’a’ 4. bool This data type has only 2 values true and false. It occupies 1 byte in memory. True is represented as 1 and false as 0. Example: bool flag = false Type modifiers are used to modify the fundamental data types. Below is the C++ program to implement Data types: C++ // C++ program to implement// data types#include <iostream>using namespace std;int main(){ cout << "Size of bool is: " << sizeof(bool) << " bytes" << endl; cout << "Size of char is: " << sizeof(char) << " bytes" << endl; cout << "Size of int is: " << sizeof(int) << " bytes" << endl; cout << "Size of short int is: " << sizeof(short int) << " bytes" << endl; cout << "Size of long int is: " << sizeof(long int) << " bytes" << endl; cout << "Size of signed long int is: " << sizeof(signed long int) << " bytes" << endl; cout << "Size of unsigned long int is: " << sizeof(unsigned long int) << " bytes" << endl; cout << "Size of float is: " << sizeof(float) << " bytes" << endl; cout << "Size of double is: " << sizeof(double) << " bytes" << endl; cout << "Size of wchar_t is: " << sizeof(wchar_t) << " bytes" << endl; return 0;} Size of bool is: 1 bytes Size of char is: 1 bytes Size of int is: 4 bytes Size of short int is: 2 bytes Size of long int is: 8 bytes Size of signed long int is: 8 bytes Size of unsigned long int is: 8 bytes Size of float is: 4 bytes Size of double is: 8 bytes Size of wchar_t is: 4 bytes These are the data types that are derived from fundamental (or built-in) data types. For example arrays, pointers, function, reference. Below is the C++ program to implement derived data types: C++ // C++ program to implement// derived data types#include <iostream>using namespace std; // Function definitionint sum(int n1, int n2) { return n1 + n2; } int main(){ // array declaration and // initialization int arr[5] = {2, 4, 6, 8, 10}; cout << "Array elements are : "; for (int i = 0; i < 5; i++) { // printing array elements cout << arr[i] << " "; } // pointers int a = 10; // Declared a pointer of // type int int* p; // Pointer p points the address // of a p = &a; cout << "\n" << "Value of a is " << a << endl; // address of a will be printed cout << "Value of p is " << p << endl; // value of a will be printed cout << "Value of *p is " << *p << endl; // function calling from main cout << "Sum is:" << sum(5, 2) << endl; // reference int x = 10; int& ref = x; // Value of x is now changed // to 30 ref = 30; cout << "x = " << x << endl; // Value of x is now changed // to 40 x = 40; cout << "ref = " << ref << endl; return 0;} Array elements are : 2 4 6 8 10 Value of a is 10 Value of p is 0x7ffd0ec3c084 Value of *p is 10 Sum is:7 x = 30 ref = 40 These are the data types that are defined by the user themselves. For example, class, structure, union, enumeration, etc. Below is the C++ program to implement class user-defined data types: C++ // C++ program to implement// user-defined data types#include <iostream>using namespace std;class GFG{ public: string gfg; void print() { cout << "String is: " << gfg; }}; // Driver codeint main(){ GFG obj1; obj1.gfg = "GeeksForGeeks is the best Technical Website"; obj1.print(); return 0;} String is: GeeksForGeeks is the best Technical Website Below is the C++ program to implement structure user-defined data type: C++ // C++ program to implement // struct #include <iostream>using namespace std; struct Geeks { int a, b;}; // Driver codeint main(){ struct Geeks arr[10]; arr[0].a = 30; arr[0].b = 40; cout << arr[0].a << ", " << arr[0].b; return 0;} 30, 40 Below is the C++ program to implement union user-defined data type: C++ // C++ program to implement // union#include <iostream>using namespace std;union gfg { int a, b;}; // Driver codeint main(){ union gfg g; g.a = 5; cout << "After changing a = 5:" << endl << "a = " << g.a << ", b = " << g.b << endl; g.b = 15; cout << "After changing b = 15:" << endl << "a = " << g.a << ", b = " << g.b << endl; return 0;} After changing a = 5: a = 5, b = 5 After changing b = 15: a = 15, b = 15 Below is the C++ program to implement enumeration data type: C++ // C++ program to implement // enum#include <iostream>using namespace std;enum season { Autmn, Spring, Winter, Summer}; // Driver codeint main(){ enum season month; month = Summer; cout << month; return 0;} 3 Operators are nothing but symbols that tell the compiler to perform some specific operations. Operators are of the following types – 1. Arithmetic Operators Arithmetic operators perform some arithmetic operations on one or two operands. Operators that operate on one operand are called unary arithmetic operators and operators that operate on two operands are called binary arithmetic operators. +,-,*,/,% are binary operators. ++, — are unary operators. Suppose: A=5 and B=10 Below is the C++ program to implement arithmetic operators: C++ // C++ program to implement// arithmetic operators#include <iostream>using namespace std; // Driver codeint main(){ int a = 5; int b = 10; cout << "Sum of a and b is" << " " << a + b << endl; cout << "Difference of b and a is" << " " << b - a << endl; cout << "Multiplication of a and b is" << " " << a * b << endl; cout << "Division of b and a is" << " " << b / a << endl; cout << "Modulo of b and a is" << " " << b % a << endl; return 0;} Sum of a and b is 15 Difference of b and a is 5 Multiplication of a and b is 50 Division of b and a is 2 Modulo of b and a is 0 Pre-incrementer: It increments the value of the operand instantly.Post-incrementer: It stores the current value of the operand temporarily and only after that statement is completed, the value of the operand is incremented.Pre-decrementer: It decrements the value of the operand instantly.Post-decrementer: It stores the current value of the operand temporarily and only after that statement is completed, the value of the operand is decremented. Pre-incrementer: It increments the value of the operand instantly. Post-incrementer: It stores the current value of the operand temporarily and only after that statement is completed, the value of the operand is incremented. Pre-decrementer: It decrements the value of the operand instantly. Post-decrementer: It stores the current value of the operand temporarily and only after that statement is completed, the value of the operand is decremented. Below is the C++ program to implement Post-incrementer and Post-decrementer: C++ // C++ program to implement// post-incrementer and// post-decrementer#include <iostream>using namespace std; // Driver codeint main(){ int a = 10; int b; int c; b = a++; cout << a << " " << b << endl; c = a--; cout << a << " " << c << endl; return 0;} 11 10 10 11 Below is the C++ program to implement Pre-incrementer and Pre-decrementer: C++ // C++ program to implement// pre-incrementer and // pre-decrementer#include <iostream>using namespace std; // Driver codeint main(){ int a = 10; int b; int c; b = ++a; cout << a << " " << b << endl; c = --a; cout << a << " " << c << endl; return 0;} 11 11 10 10 2. Relational Operators Relational operators define the relation between 2 entities. They give a boolean value as result i.e true or false. Suppose: A=5 and B=10 Below is the C++ program to implement relational operators: C++ // C++ program to implement// relational operators#include <iostream>using namespace std; // Driver codeint main(){ int a = 5; int b = 10; if (a == b) { cout << "a==b is not equal to true" << endl; } if (a != b) { cout << "a != b is true" << endl; } if (a > b) { cout << "a > b is not true" << endl; } if (a < b) { cout << "a < b is true" << endl; } if (a >= b) { cout << "a >= b is not true" << endl; } if (a <= b) { cout << "a <= b is true" << endl; } return 0;} a != b is true a < b is true a <= b is true 3. Logical Operators Logical operators are used to connecting multiple expressions or conditions together. We have 3 basic logical operators. Suppose: A=0 and B=1 Below is the C++ program to implement the logical operators: C++ // C++ program to implement// the logical operators#include <iostream>using namespace std; // Driver codeint main(){ int a = 0; int b = 1; if (a && b) { cout << "a && b is false" << endl; } if (a || b) { cout << "a || b is true" << endl; } if (!a) { cout << "!a is true" << endl; } return 0;} a || b is true !a is true Example: If we need to check whether a number is divisible by both 2 and 3, we will use the AND operator: (num%2==0) && num(num%3==0) If this expression gives true value then that means that num is divisible by both 2 and 3. (num%2==0) || (num%3==0) If this expression gives true value then that means that num is divisible by 2 or 3 or both. 4. Bitwise Operators Bitwise operators are the operators that operate on bits and perform bit-by-bit operations. Suppose: A = 5(0101) and B = 6(0110) 0101 & 0110 ———- 0100 0101 | 0110 ——— 0111 0101 ^ 0110 ———- 0011 4 (0100) 4 << 1 = 1000 = 8 4 >> 1 = 0010 = 2 If shift operator is applied on a number N then, N<<a will give a result N*2^a N>>a will give a result N/2^a Below is the C++ program to implement bitwise operators: C++ // C++ program to implement// bitwise operators#include <iostream>using namespace std; // Driver codeint main(){ // Binary representation // of 5 is 0101 int a = 5; // Binary representation // of 6 is 0110 int b = 6; cout << (a & b) << endl; cout << (a | b) << endl; cout << (a ^ b) << endl; cout << (a << 1) << endl; cout << (a >> 1) << endl; return 0;} 4 7 3 10 2 5. Assignment Operators Below is the C++ program to implement assignment operator: C++ // C++ program to implement// assignment operator#include <iostream>using namespace std; // Driver codeint main(){ // a is assigned value 5 int a = 5; // a becomes 5 cout << a << endl; // this is same as a=a+2 a += 2; // a becomes 5+2 =7 cout << a << endl; // this is same as a=a-2 a -= 2; // a becomes 7-2 =5 cout << a << endl; // this is same as a=a*2 a *= 2; // a becomes 5*2 =10 cout << a << endl; // this is same as a=a/2 a /= 2; // a becomes 10/2 =5 cout << a << endl; return 0;} 5 7 5 10 5 6. Misc Operators Below is the C++ program to implement miscellaneous operator: C++ // C++ program to implement// miscellaneous operator#include <iostream>using namespace std; // Driver codeint main(){ int a = 4; // sizeof () returns the size // of variable in bytes cout << sizeof(a) << endl; int x = 5; int y = 8; // ternary or conditional operator int min = x < y ? x : y; cout << "Minimum value from x and y is " << min << endl; // casting from float to int cout << int(4.350) << endl; // comma operator is used for int d = 2, b = 3, c = 4; // multiple declarations cout << d << " " << b << " " << c << " " << endl; return 0;} 4 Minimum value from x and y is 5 4 2 3 4 1. if/else The if block is used to specify the code to be executed if the condition specified in it is true, the else block is executed otherwise. Below is the C++ program to implement if-else: C++ // C++ program to implement// if-else#include <iostream>using namespace std; // Driver codeint main(){ int age; cin >> age; if (age >= 18) { cout << "You can vote."; } else { cout << "Not eligible for voting."; } return 0;} Not eligible for voting. 2. else if To specify multiple if conditions, we first use if and then the consecutive statements use else if. Below is the C++ program to implement else if: C++ // C++ program to implement// else if#include <iostream>using namespace std; // Driver codeint main(){ int x, y; cin >> x >> y; if (x == y) { cout << "Both the numbers are equal"; } else if (x > y) { cout << "X is greater than Y"; } else { cout << "Y is greater than X"; } return 0;} Y is greater than X 3. nested if To specify conditions within conditions we make the use of nested ifs. Below is the C++ program to implement nested if: C++ // C++ program to implement// nested if#include <iostream>using namespace std; // Driver codeint main(){ int x, y; cin >> x >> y; if (x == y) { cout << "Both the numbers are equal"; } else { if (x > y) { cout << "X is greater than Y"; } else { cout << "Y is greater than X"; } } return 0;} Y is greater than X 4. Switch Statement Switch case statements are a substitute for long if statements that compare a variable to multiple values. After a match is found, it executes the corresponding code of that value case. Syntax: switch (n) { case 1: // code to be executed if n == 1; break; case 2: // code to be executed if n == 2; break; default: // code to be executed if n doesn't match any of the above cases } The variable in the switch should have a constant value. The break statement is optional. It terminates the switch statement and moves control to the next line after the switch. If the break statement is not added, the switch will not get terminated and it will continue onto the next line after the switch. Every case value should be unique. The default case is optional. But it is important as it is executed when no case value could be matched. Basic Calculator Using Switch Statement: C++ // C++ program to implement// the switch statement#include <iostream>using namespace std; // Driver codeint main(){ int n1, n2; char op; cout << "Enter 2 numbers: "; cin >> n1 >> n2; cout << "Enter operand: "; cin >> op; switch (op) { case '+': cout << n1 + n2 << endl; break; case '-': cout << n1 - n2 << endl; break; case '*': cout << n1 * n2 << endl; break; case '/': cout << n1 / n2 << endl; break; case '%': cout << n1 % n2 << endl; break; default: cout << "Operator not found!" << endl; break; } return 0;} Enter 2 numbers: Enter operand: Operator not found! A loop is used for executing a block of statements repeatedly until a particular condition is satisfied. A loop consists of an initialization statement, a test condition, and an increment statement. 1. for loop The syntax of the for loop is for (initialization; condition; update) { // body of-loop } Below is the C++ program to implement for loop: C++ // C++ program to implement// for loop#include <iostream>using namespace std; // Driver codeint main(){ for (int i = 1; i <= 5; i++) { cout << i << " "; } return 0;} 1 2 3 4 5 Explanation: The for loop is initialized by the value 1, the test condition is i<=5 i.e the loop is executed till the value of i remains lesser than or equal to 5. In each iteration, the value of i is incremented by one by doing i++. 2. while loop The syntax for while loop is while (condition) { // body of the loop } Below is the C++ program to implement while loop: C++ // C++ program to implement// while loop#include <iostream>using namespace std; // Driver codeint main(){ int i = 1; while (i <= 5) { cout << i << " "; i++; } return 0;} 1 2 3 4 5 Explanation: The while loop is initialized by the value 1, the test condition is i<=5 i.e the loop is executed till the value of i remains lesser than or equal to 5. In each iteration, the value of i is incremented by one by doing i++. 3. do͙ while loop The syntax for while loop is do { // body of loop; } while (condition); Below is the C++ program to implement do-while loop: C++ // C++ program to implement// do-while loop#include <iostream>using namespace std; // Driver codeint main(){ int i = 1; do { cout << i << " "; i++; } while (i <= 5); return 0;} 1 2 3 4 5 Explanation: The do-while loop variable is initialized by the value 1, in each iteration, the value of i is incremented by one by doing i++, the test condition is i<=5 i.e the loop is executed till the value of i remains lesser than or equal to 5. Since the testing condition is checked only once the loop has already run so a do-while loop runs at least once. Jumps in loops are used to control the flow of loops. There are two statements used to implement jump in loops – Continue and Break. These statements are used when we need to change the flow of the loop when some specified condition is met. 1. Continue The continue statement is used to skip to the next iteration of that loop. This means that it stops one iteration of the loop. All the statements present after the continue statement in that loop are not executed. Below is the C++ program to implement the Continue statement: C++ // C++ program to implement// the continue statement#include <iostream>using namespace std; // Driver codeint main(){ int i; for (i = 1; i <= 20; i++) { if (i % 3 == 0) { continue; } cout << i << endl; }} 1 2 4 5 7 8 10 11 13 14 16 17 19 20 Explanation: In this for loop, whenever i is a number divisible by 3, it will not be printed as the loop will skip to the next iteration due to the continue statement. Hence, all the numbers except those which are divisible by 3 will be printed. 2. Break The break statement is used to terminate the current loop. As soon as the break statement is encountered in a loop, all further iterations of the loop are stopped and control is shifted to the first statement after the end of the loop. Below is the C++ program to implement the break statement: C++ // C++ program to implement// the break statement#include <iostream>using namespace std; // Driver codeint main(){ int i; for (i = 1; i <= 20; i++) { if (i == 11) { break; } cout << i << endl; }} 1 2 3 4 5 6 7 8 9 10 Explanation: In this loop, when i becomes equal to 11, the for loop terminates due to break statement, Hence, the program will print numbers from 1 to 10 only. as5853535 Technical Scripter 2020 C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Inline Functions in C++ Pair in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ List in C++ Standard Template Library (STL)
[ { "code": null, "e": 25479, "s": 25451, "text": "\n06 Sep, 2021" }, { "code": null, "e": 25735, "s": 25479, "text": "C++ is a cross-platform language that can be used to create high-performance applications. It was developed by Bjarne Stroustrup, as an extension to the C language. The language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14, and C++17." }, { "code": null, "e": 25797, "s": 25735, "text": "C++ is one of the world’s most popular programming languages." }, { "code": null, "e": 25893, "s": 25797, "text": "C++ can be found in today’s operating systems, Graphical User Interfaces, and embedded systems." }, { "code": null, "e": 26039, "s": 25893, "text": "C++ is an object-oriented programming language that gives a clear structure to programs and allows code to be reused, lowering development costs." }, { "code": null, "e": 26138, "s": 26039, "text": "C++ is portable and can be used to develop applications that can be adapted to multiple platforms." }, { "code": null, "e": 26168, "s": 26138, "text": "C++ is fun and easy to learn!" }, { "code": null, "e": 26265, "s": 26168, "text": "As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa." }, { "code": null, "e": 26269, "s": 26265, "text": "C++" }, { "code": "// C++ Hello World Program#include <iostream>using namespace std;int main(){ cout << \"Hello World!\\n\"; return 0;}", "e": 26385, "s": 26269, "text": null }, { "code": null, "e": 26398, "s": 26385, "text": "Hello World!" }, { "code": null, "e": 28023, "s": 26398, "text": "Comments: The two slash(//) signs are used to add comments in a program. It does not have any effect on the behavior or outcome of the program. It is used to give a description of the program you’re writing.#include<iostream>: #include is the pre-processor directive that is used to include files in our program. Here we are including the iostream standard file which is necessary for the declarations of basic standard input/output library in C++.Using namespace std: All elements of the standard C++ library are declared within a namespace. Here we are using the std namespace.int main(): The execution of any C++ program starts with the main function, hence it is necessary to have a main function in your program. ‘int’ is the return value of this function. (We will be studying functions in more detail later).{}: The curly brackets are used to indicate the starting and ending point of any function. Every opening bracket should have a corresponding closing bracket.cout<<”Hello World!\\n”; This is a C++ statement. cout represents the standard output stream in C++. It is declared in the iostream standard file within the std namespace. The text between quotations will be printed on the screen. \\n will not be printed, it is used to add a line break. Each statement in C++ ends with a semicolon (;).return 0; return signifies the end of a function. Here the function is main, so when we hit return 0, it exits the program. We are returning 0 because we mentioned the return type of the main function as integer (int main). A zero indicates that everything went fine and one indicates that something has gone wrong." }, { "code": null, "e": 28231, "s": 28023, "text": "Comments: The two slash(//) signs are used to add comments in a program. It does not have any effect on the behavior or outcome of the program. It is used to give a description of the program you’re writing." }, { "code": null, "e": 28474, "s": 28231, "text": "#include<iostream>: #include is the pre-processor directive that is used to include files in our program. Here we are including the iostream standard file which is necessary for the declarations of basic standard input/output library in C++." }, { "code": null, "e": 28607, "s": 28474, "text": "Using namespace std: All elements of the standard C++ library are declared within a namespace. Here we are using the std namespace." }, { "code": null, "e": 28844, "s": 28607, "text": "int main(): The execution of any C++ program starts with the main function, hence it is necessary to have a main function in your program. ‘int’ is the return value of this function. (We will be studying functions in more detail later)." }, { "code": null, "e": 29002, "s": 28844, "text": "{}: The curly brackets are used to indicate the starting and ending point of any function. Every opening bracket should have a corresponding closing bracket." }, { "code": null, "e": 29338, "s": 29002, "text": "cout<<”Hello World!\\n”; This is a C++ statement. cout represents the standard output stream in C++. It is declared in the iostream standard file within the std namespace. The text between quotations will be printed on the screen. \\n will not be printed, it is used to add a line break. Each statement in C++ ends with a semicolon (;)." }, { "code": null, "e": 29654, "s": 29338, "text": "return 0; return signifies the end of a function. Here the function is main, so when we hit return 0, it exits the program. We are returning 0 because we mentioned the return type of the main function as integer (int main). A zero indicates that everything went fine and one indicates that something has gone wrong." }, { "code": null, "e": 29750, "s": 29654, "text": "The header file iostream must be included to make use of the input/output (cin/cout) operators." }, { "code": null, "e": 29775, "s": 29750, "text": "Standard Output (cout) " }, { "code": null, "e": 29943, "s": 29775, "text": "By default, the standard output of a program points at the screen. So with the cout operator and the “insertion” operator (фф) you can print a message onto the screen." }, { "code": null, "e": 30010, "s": 29943, "text": "To print the content of a variable the double quotes are not used." }, { "code": null, "e": 30076, "s": 30010, "text": "The << operator can be used multiple times in a single statement." }, { "code": null, "e": 30122, "s": 30076, "text": "It is possible to combine variables and text:" }, { "code": null, "e": 30282, "s": 30122, "text": "The cout operator does not put a line break at the end of the output. So if you want to print two sentences you will have to use the new-line character ( \\n )." }, { "code": null, "e": 30360, "s": 30282, "text": "It is possible to use the endl manipulator instead of the new-line character." }, { "code": null, "e": 30416, "s": 30360, "text": "Below is the C++ program to illustrate standard output:" }, { "code": null, "e": 30420, "s": 30416, "text": "C++" }, { "code": "// C++ program to implement// standard output#include <iostream>using namespace std;int main(){ cout << \"Geeks For Geeks\"; return 0;}", "e": 30556, "s": 30420, "text": null }, { "code": null, "e": 30572, "s": 30556, "text": "Geeks For Geeks" }, { "code": null, "e": 30595, "s": 30572, "text": "Standard input (cin) " }, { "code": null, "e": 30732, "s": 30595, "text": "In most cases, the standard input device is the keyboard. With the cin and >> operators, it is possible to read input from the keyboard." }, { "code": null, "e": 31045, "s": 30732, "text": "The cin operator will always return the variable type that you use with cin. So if you request an integer you will get an integer and so on. This can cause an error when the user of the program does not return the type that you are expecting. (Example: you ask for an integer and you get a string of characters.)" }, { "code": null, "e": 31207, "s": 31045, "text": "The cin operator is also chainable. In this case, the user must give two input values, that are separated by any valid blank separator (tab, space, or new-line)." }, { "code": null, "e": 31262, "s": 31207, "text": "Below is the C++ program to illustrate standard input:" }, { "code": null, "e": 31266, "s": 31262, "text": "C++" }, { "code": "// C++ program to implement// standard input#include <iostream>using namespace std;int main(){ int a; cout << \"Enter a number\" << endl; // User can input an integer cin >> a; cout << \"User entered number \" << a << endl;}", "e": 31497, "s": 31266, "text": null }, { "code": null, "e": 31535, "s": 31497, "text": "Enter a number\nUser entered number 0\n" }, { "code": null, "e": 31739, "s": 31535, "text": "Data types are declarations for variables. This determines the type and size of data associated with variables which are essential to know since different data types occupy the different sizes of memory." }, { "code": null, "e": 31747, "s": 31739, "text": "1. int " }, { "code": null, "e": 31789, "s": 31747, "text": "This data type is used to store integers." }, { "code": null, "e": 31820, "s": 31789, "text": "It occupies 4 bytes in memory." }, { "code": null, "e": 31872, "s": 31820, "text": "It can store values from -2147483648 to 2147483647." }, { "code": null, "e": 31889, "s": 31872, "text": "Eg. int age = 18" }, { "code": null, "e": 31909, "s": 31889, "text": "2. float and double" }, { "code": null, "e": 31973, "s": 31909, "text": "Used to store floating-point numbers (decimals and exponential)" }, { "code": null, "e": 32039, "s": 31973, "text": "The size of a float is 4 bytes and the size of double is 8 bytes." }, { "code": null, "e": 32142, "s": 32039, "text": "Float is used to store up to 7 decimal digits whereas double is used to store up to 15 decimal digits." }, { "code": null, "e": 32202, "s": 32142, "text": "Example:float pi = 3.14.double distance = 24E8 // 24 x 108 " }, { "code": null, "e": 32219, "s": 32202, "text": "float pi = 3.14." }, { "code": null, "e": 32255, "s": 32219, "text": "double distance = 24E8 // 24 x 108 " }, { "code": null, "e": 32264, "s": 32255, "text": "3. char " }, { "code": null, "e": 32308, "s": 32264, "text": "This data type is used to store characters." }, { "code": null, "e": 32338, "s": 32308, "text": "It occupies 1 byte in memory." }, { "code": null, "e": 32444, "s": 32338, "text": "Characters in C++ are enclosed inside single quotes ‘ ‘ ASCII code is used to store characters in memory." }, { "code": null, "e": 32466, "s": 32444, "text": "Example: char ch =’a’" }, { "code": null, "e": 32475, "s": 32466, "text": "4. bool " }, { "code": null, "e": 32524, "s": 32475, "text": "This data type has only 2 values true and false." }, { "code": null, "e": 32554, "s": 32524, "text": "It occupies 1 byte in memory." }, { "code": null, "e": 32595, "s": 32554, "text": "True is represented as 1 and false as 0." }, { "code": null, "e": 32622, "s": 32595, "text": "Example: bool flag = false" }, { "code": null, "e": 32684, "s": 32622, "text": "Type modifiers are used to modify the fundamental data types." }, { "code": null, "e": 32734, "s": 32684, "text": "Below is the C++ program to implement Data types:" }, { "code": null, "e": 32738, "s": 32734, "text": "C++" }, { "code": "// C++ program to implement// data types#include <iostream>using namespace std;int main(){ cout << \"Size of bool is: \" << sizeof(bool) << \" bytes\" << endl; cout << \"Size of char is: \" << sizeof(char) << \" bytes\" << endl; cout << \"Size of int is: \" << sizeof(int) << \" bytes\" << endl; cout << \"Size of short int is: \" << sizeof(short int) << \" bytes\" << endl; cout << \"Size of long int is: \" << sizeof(long int) << \" bytes\" << endl; cout << \"Size of signed long int is: \" << sizeof(signed long int) << \" bytes\" << endl; cout << \"Size of unsigned long int is: \" << sizeof(unsigned long int) << \" bytes\" << endl; cout << \"Size of float is: \" << sizeof(float) << \" bytes\" << endl; cout << \"Size of double is: \" << sizeof(double) << \" bytes\" << endl; cout << \"Size of wchar_t is: \" << sizeof(wchar_t) << \" bytes\" << endl; return 0;}", "e": 33778, "s": 32738, "text": null }, { "code": null, "e": 34066, "s": 33778, "text": "Size of bool is: 1 bytes\nSize of char is: 1 bytes\nSize of int is: 4 bytes\nSize of short int is: 2 bytes\nSize of long int is: 8 bytes\nSize of signed long int is: 8 bytes\nSize of unsigned long int is: 8 bytes\nSize of float is: 4 bytes\nSize of double is: 8 bytes\nSize of wchar_t is: 4 bytes" }, { "code": null, "e": 34202, "s": 34066, "text": "These are the data types that are derived from fundamental (or built-in) data types. For example arrays, pointers, function, reference." }, { "code": null, "e": 34260, "s": 34202, "text": "Below is the C++ program to implement derived data types:" }, { "code": null, "e": 34264, "s": 34260, "text": "C++" }, { "code": "// C++ program to implement// derived data types#include <iostream>using namespace std; // Function definitionint sum(int n1, int n2) { return n1 + n2; } int main(){ // array declaration and // initialization int arr[5] = {2, 4, 6, 8, 10}; cout << \"Array elements are : \"; for (int i = 0; i < 5; i++) { // printing array elements cout << arr[i] << \" \"; } // pointers int a = 10; // Declared a pointer of // type int int* p; // Pointer p points the address // of a p = &a; cout << \"\\n\" << \"Value of a is \" << a << endl; // address of a will be printed cout << \"Value of p is \" << p << endl; // value of a will be printed cout << \"Value of *p is \" << *p << endl; // function calling from main cout << \"Sum is:\" << sum(5, 2) << endl; // reference int x = 10; int& ref = x; // Value of x is now changed // to 30 ref = 30; cout << \"x = \" << x << endl; // Value of x is now changed // to 40 x = 40; cout << \"ref = \" << ref << endl; return 0;}", "e": 35332, "s": 34264, "text": null }, { "code": null, "e": 35454, "s": 35332, "text": "Array elements are : 2 4 6 8 10 \nValue of a is 10\nValue of p is 0x7ffd0ec3c084\nValue of *p is 10\nSum is:7\nx = 30\nref = 40" }, { "code": null, "e": 35520, "s": 35454, "text": "These are the data types that are defined by the user themselves." }, { "code": null, "e": 35576, "s": 35520, "text": "For example, class, structure, union, enumeration, etc." }, { "code": null, "e": 35645, "s": 35576, "text": "Below is the C++ program to implement class user-defined data types:" }, { "code": null, "e": 35649, "s": 35645, "text": "C++" }, { "code": "// C++ program to implement// user-defined data types#include <iostream>using namespace std;class GFG{ public: string gfg; void print() { cout << \"String is: \" << gfg; }}; // Driver codeint main(){ GFG obj1; obj1.gfg = \"GeeksForGeeks is the best Technical Website\"; obj1.print(); return 0;}", "e": 35969, "s": 35649, "text": null }, { "code": null, "e": 36024, "s": 35969, "text": "String is: GeeksForGeeks is the best Technical Website" }, { "code": null, "e": 36096, "s": 36024, "text": "Below is the C++ program to implement structure user-defined data type:" }, { "code": null, "e": 36100, "s": 36096, "text": "C++" }, { "code": "// C++ program to implement // struct #include <iostream>using namespace std; struct Geeks { int a, b;}; // Driver codeint main(){ struct Geeks arr[10]; arr[0].a = 30; arr[0].b = 40; cout << arr[0].a << \", \" << arr[0].b; return 0;}", "e": 36349, "s": 36100, "text": null }, { "code": null, "e": 36356, "s": 36349, "text": "30, 40" }, { "code": null, "e": 36424, "s": 36356, "text": "Below is the C++ program to implement union user-defined data type:" }, { "code": null, "e": 36428, "s": 36424, "text": "C++" }, { "code": "// C++ program to implement // union#include <iostream>using namespace std;union gfg { int a, b;}; // Driver codeint main(){ union gfg g; g.a = 5; cout << \"After changing a = 5:\" << endl << \"a = \" << g.a << \", b = \" << g.b << endl; g.b = 15; cout << \"After changing b = 15:\" << endl << \"a = \" << g.a << \", b = \" << g.b << endl; return 0;}", "e": 36817, "s": 36428, "text": null }, { "code": null, "e": 36890, "s": 36817, "text": "After changing a = 5:\na = 5, b = 5\nAfter changing b = 15:\na = 15, b = 15" }, { "code": null, "e": 36951, "s": 36890, "text": "Below is the C++ program to implement enumeration data type:" }, { "code": null, "e": 36955, "s": 36951, "text": "C++" }, { "code": "// C++ program to implement // enum#include <iostream>using namespace std;enum season { Autmn, Spring, Winter, Summer}; // Driver codeint main(){ enum season month; month = Summer; cout << month; return 0;}", "e": 37169, "s": 36955, "text": null }, { "code": null, "e": 37171, "s": 37169, "text": "3" }, { "code": null, "e": 37304, "s": 37171, "text": "Operators are nothing but symbols that tell the compiler to perform some specific operations. Operators are of the following types –" }, { "code": null, "e": 37330, "s": 37304, "text": "1. Arithmetic Operators " }, { "code": null, "e": 37569, "s": 37330, "text": "Arithmetic operators perform some arithmetic operations on one or two operands. Operators that operate on one operand are called unary arithmetic operators and operators that operate on two operands are called binary arithmetic operators." }, { "code": null, "e": 37601, "s": 37569, "text": "+,-,*,/,% are binary operators." }, { "code": null, "e": 37628, "s": 37601, "text": "++, — are unary operators." }, { "code": null, "e": 37650, "s": 37628, "text": "Suppose: A=5 and B=10" }, { "code": null, "e": 37710, "s": 37650, "text": "Below is the C++ program to implement arithmetic operators:" }, { "code": null, "e": 37714, "s": 37710, "text": "C++" }, { "code": "// C++ program to implement// arithmetic operators#include <iostream>using namespace std; // Driver codeint main(){ int a = 5; int b = 10; cout << \"Sum of a and b is\" << \" \" << a + b << endl; cout << \"Difference of b and a is\" << \" \" << b - a << endl; cout << \"Multiplication of a and b is\" << \" \" << a * b << endl; cout << \"Division of b and a is\" << \" \" << b / a << endl; cout << \"Modulo of b and a is\" << \" \" << b % a << endl; return 0;}", "e": 38216, "s": 37714, "text": null }, { "code": null, "e": 38344, "s": 38216, "text": "Sum of a and b is 15\nDifference of b and a is 5\nMultiplication of a and b is 50\nDivision of b and a is 2\nModulo of b and a is 0" }, { "code": null, "e": 38791, "s": 38344, "text": "Pre-incrementer: It increments the value of the operand instantly.Post-incrementer: It stores the current value of the operand temporarily and only after that statement is completed, the value of the operand is incremented.Pre-decrementer: It decrements the value of the operand instantly.Post-decrementer: It stores the current value of the operand temporarily and only after that statement is completed, the value of the operand is decremented." }, { "code": null, "e": 38858, "s": 38791, "text": "Pre-incrementer: It increments the value of the operand instantly." }, { "code": null, "e": 39016, "s": 38858, "text": "Post-incrementer: It stores the current value of the operand temporarily and only after that statement is completed, the value of the operand is incremented." }, { "code": null, "e": 39083, "s": 39016, "text": "Pre-decrementer: It decrements the value of the operand instantly." }, { "code": null, "e": 39241, "s": 39083, "text": "Post-decrementer: It stores the current value of the operand temporarily and only after that statement is completed, the value of the operand is decremented." }, { "code": null, "e": 39318, "s": 39241, "text": "Below is the C++ program to implement Post-incrementer and Post-decrementer:" }, { "code": null, "e": 39322, "s": 39318, "text": "C++" }, { "code": "// C++ program to implement// post-incrementer and// post-decrementer#include <iostream>using namespace std; // Driver codeint main(){ int a = 10; int b; int c; b = a++; cout << a << \" \" << b << endl; c = a--; cout << a << \" \" << c << endl; return 0;}", "e": 39601, "s": 39322, "text": null }, { "code": null, "e": 39613, "s": 39601, "text": "11 10\n10 11" }, { "code": null, "e": 39688, "s": 39613, "text": "Below is the C++ program to implement Pre-incrementer and Pre-decrementer:" }, { "code": null, "e": 39692, "s": 39688, "text": "C++" }, { "code": "// C++ program to implement// pre-incrementer and // pre-decrementer#include <iostream>using namespace std; // Driver codeint main(){ int a = 10; int b; int c; b = ++a; cout << a << \" \" << b << endl; c = --a; cout << a << \" \" << c << endl; return 0;}", "e": 39970, "s": 39692, "text": null }, { "code": null, "e": 39982, "s": 39970, "text": "11 11\n10 10" }, { "code": null, "e": 40008, "s": 39982, "text": "2. Relational Operators " }, { "code": null, "e": 40124, "s": 40008, "text": "Relational operators define the relation between 2 entities. They give a boolean value as result i.e true or false." }, { "code": null, "e": 40146, "s": 40124, "text": "Suppose: A=5 and B=10" }, { "code": null, "e": 40206, "s": 40146, "text": "Below is the C++ program to implement relational operators:" }, { "code": null, "e": 40210, "s": 40206, "text": "C++" }, { "code": "// C++ program to implement// relational operators#include <iostream>using namespace std; // Driver codeint main(){ int a = 5; int b = 10; if (a == b) { cout << \"a==b is not equal to true\" << endl; } if (a != b) { cout << \"a != b is true\" << endl; } if (a > b) { cout << \"a > b is not true\" << endl; } if (a < b) { cout << \"a < b is true\" << endl; } if (a >= b) { cout << \"a >= b is not true\" << endl; } if (a <= b) { cout << \"a <= b is true\" << endl; } return 0;}", "e": 40802, "s": 40210, "text": null }, { "code": null, "e": 40846, "s": 40802, "text": "a != b is true\na < b is true\na <= b is true" }, { "code": null, "e": 40869, "s": 40846, "text": "3. Logical Operators " }, { "code": null, "e": 40990, "s": 40869, "text": "Logical operators are used to connecting multiple expressions or conditions together. We have 3 basic logical operators." }, { "code": null, "e": 41011, "s": 40990, "text": "Suppose: A=0 and B=1" }, { "code": null, "e": 41072, "s": 41011, "text": "Below is the C++ program to implement the logical operators:" }, { "code": null, "e": 41076, "s": 41072, "text": "C++" }, { "code": "// C++ program to implement// the logical operators#include <iostream>using namespace std; // Driver codeint main(){ int a = 0; int b = 1; if (a && b) { cout << \"a && b is false\" << endl; } if (a || b) { cout << \"a || b is true\" << endl; } if (!a) { cout << \"!a is true\" << endl; } return 0;}", "e": 41441, "s": 41076, "text": null }, { "code": null, "e": 41467, "s": 41441, "text": "a || b is true\n!a is true" }, { "code": null, "e": 41476, "s": 41467, "text": "Example:" }, { "code": null, "e": 41601, "s": 41476, "text": "If we need to check whether a number is divisible by both 2 and 3, we will use the AND operator: (num%2==0) && num(num%3==0)" }, { "code": null, "e": 41717, "s": 41601, "text": "If this expression gives true value then that means that num is divisible by both 2 and 3. (num%2==0) || (num%3==0)" }, { "code": null, "e": 41810, "s": 41717, "text": "If this expression gives true value then that means that num is divisible by 2 or 3 or both." }, { "code": null, "e": 41833, "s": 41810, "text": "4. Bitwise Operators " }, { "code": null, "e": 41925, "s": 41833, "text": "Bitwise operators are the operators that operate on bits and perform bit-by-bit operations." }, { "code": null, "e": 41962, "s": 41925, "text": "Suppose: A = 5(0101) and B = 6(0110)" }, { "code": null, "e": 41971, "s": 41962, "text": " 0101" }, { "code": null, "e": 41978, "s": 41971, "text": "& 0110" }, { "code": null, "e": 41983, "s": 41978, "text": "———-" }, { "code": null, "e": 41992, "s": 41983, "text": " 0100" }, { "code": null, "e": 41999, "s": 41992, "text": " 0101" }, { "code": null, "e": 42006, "s": 41999, "text": "| 0110" }, { "code": null, "e": 42010, "s": 42006, "text": "———" }, { "code": null, "e": 42018, "s": 42010, "text": " 0111" }, { "code": null, "e": 42027, "s": 42018, "text": " 0101" }, { "code": null, "e": 42034, "s": 42027, "text": "^ 0110" }, { "code": null, "e": 42039, "s": 42034, "text": "———-" }, { "code": null, "e": 42048, "s": 42039, "text": " 0011" }, { "code": null, "e": 42057, "s": 42048, "text": "4 (0100)" }, { "code": null, "e": 42064, "s": 42057, "text": "4 << 1" }, { "code": null, "e": 42075, "s": 42064, "text": "= 1000 = 8" }, { "code": null, "e": 42082, "s": 42075, "text": "4 >> 1" }, { "code": null, "e": 42093, "s": 42082, "text": "= 0010 = 2" }, { "code": null, "e": 42142, "s": 42093, "text": "If shift operator is applied on a number N then," }, { "code": null, "e": 42172, "s": 42142, "text": "N<<a will give a result N*2^a" }, { "code": null, "e": 42202, "s": 42172, "text": "N>>a will give a result N/2^a" }, { "code": null, "e": 42259, "s": 42202, "text": "Below is the C++ program to implement bitwise operators:" }, { "code": null, "e": 42263, "s": 42259, "text": "C++" }, { "code": "// C++ program to implement// bitwise operators#include <iostream>using namespace std; // Driver codeint main(){ // Binary representation // of 5 is 0101 int a = 5; // Binary representation // of 6 is 0110 int b = 6; cout << (a & b) << endl; cout << (a | b) << endl; cout << (a ^ b) << endl; cout << (a << 1) << endl; cout << (a >> 1) << endl; return 0;}", "e": 42641, "s": 42263, "text": null }, { "code": null, "e": 42652, "s": 42641, "text": "4\n7\n3\n10\n2" }, { "code": null, "e": 42676, "s": 42652, "text": "5. Assignment Operators" }, { "code": null, "e": 42735, "s": 42676, "text": "Below is the C++ program to implement assignment operator:" }, { "code": null, "e": 42739, "s": 42735, "text": "C++" }, { "code": "// C++ program to implement// assignment operator#include <iostream>using namespace std; // Driver codeint main(){ // a is assigned value 5 int a = 5; // a becomes 5 cout << a << endl; // this is same as a=a+2 a += 2; // a becomes 5+2 =7 cout << a << endl; // this is same as a=a-2 a -= 2; // a becomes 7-2 =5 cout << a << endl; // this is same as a=a*2 a *= 2; // a becomes 5*2 =10 cout << a << endl; // this is same as a=a/2 a /= 2; // a becomes 10/2 =5 cout << a << endl; return 0;}", "e": 43287, "s": 42739, "text": null }, { "code": null, "e": 43298, "s": 43287, "text": "5\n7\n5\n10\n5" }, { "code": null, "e": 43316, "s": 43298, "text": "6. Misc Operators" }, { "code": null, "e": 43378, "s": 43316, "text": "Below is the C++ program to implement miscellaneous operator:" }, { "code": null, "e": 43382, "s": 43378, "text": "C++" }, { "code": "// C++ program to implement// miscellaneous operator#include <iostream>using namespace std; // Driver codeint main(){ int a = 4; // sizeof () returns the size // of variable in bytes cout << sizeof(a) << endl; int x = 5; int y = 8; // ternary or conditional operator int min = x < y ? x : y; cout << \"Minimum value from x and y is \" << min << endl; // casting from float to int cout << int(4.350) << endl; // comma operator is used for int d = 2, b = 3, c = 4; // multiple declarations cout << d << \" \" << b << \" \" << c << \" \" << endl; return 0;}", "e": 43989, "s": 43382, "text": null }, { "code": null, "e": 44032, "s": 43989, "text": "4\nMinimum value from x and y is 5\n4\n2 3 4 " }, { "code": null, "e": 44045, "s": 44032, "text": "1. if/else " }, { "code": null, "e": 44228, "s": 44045, "text": "The if block is used to specify the code to be executed if the condition specified in it is true, the else block is executed otherwise. Below is the C++ program to implement if-else:" }, { "code": null, "e": 44232, "s": 44228, "text": "C++" }, { "code": "// C++ program to implement// if-else#include <iostream>using namespace std; // Driver codeint main(){ int age; cin >> age; if (age >= 18) { cout << \"You can vote.\"; } else { cout << \"Not eligible for voting.\"; } return 0;}", "e": 44478, "s": 44232, "text": null }, { "code": null, "e": 44503, "s": 44478, "text": "Not eligible for voting." }, { "code": null, "e": 44516, "s": 44503, "text": "2. else if " }, { "code": null, "e": 44663, "s": 44516, "text": "To specify multiple if conditions, we first use if and then the consecutive statements use else if. Below is the C++ program to implement else if:" }, { "code": null, "e": 44667, "s": 44663, "text": "C++" }, { "code": "// C++ program to implement// else if#include <iostream>using namespace std; // Driver codeint main(){ int x, y; cin >> x >> y; if (x == y) { cout << \"Both the numbers are equal\"; } else if (x > y) { cout << \"X is greater than Y\"; } else { cout << \"Y is greater than X\"; } return 0;}", "e": 44976, "s": 44667, "text": null }, { "code": null, "e": 44996, "s": 44976, "text": "Y is greater than X" }, { "code": null, "e": 45011, "s": 44996, "text": "3. nested if " }, { "code": null, "e": 45131, "s": 45011, "text": "To specify conditions within conditions we make the use of nested ifs. Below is the C++ program to implement nested if:" }, { "code": null, "e": 45135, "s": 45131, "text": "C++" }, { "code": "// C++ program to implement// nested if#include <iostream>using namespace std; // Driver codeint main(){ int x, y; cin >> x >> y; if (x == y) { cout << \"Both the numbers are equal\"; } else { if (x > y) { cout << \"X is greater than Y\"; } else { cout << \"Y is greater than X\"; } } return 0;}", "e": 45474, "s": 45135, "text": null }, { "code": null, "e": 45494, "s": 45474, "text": "Y is greater than X" }, { "code": null, "e": 45516, "s": 45494, "text": "4. Switch Statement " }, { "code": null, "e": 45704, "s": 45516, "text": "Switch case statements are a substitute for long if statements that compare a variable to multiple values. After a match is found, it executes the corresponding code of that value case. " }, { "code": null, "e": 45714, "s": 45704, "text": "Syntax: " }, { "code": null, "e": 45921, "s": 45714, "text": "switch (n)\n{\n case 1: // code to be executed if n == 1;\n break;\n case 2: // code to be executed if n == 2;\n break;\n default: // code to be executed if n doesn't match any of the above cases\n} " }, { "code": null, "e": 45978, "s": 45921, "text": "The variable in the switch should have a constant value." }, { "code": null, "e": 46099, "s": 45978, "text": "The break statement is optional. It terminates the switch statement and moves control to the next line after the switch." }, { "code": null, "e": 46229, "s": 46099, "text": "If the break statement is not added, the switch will not get terminated and it will continue onto the next line after the switch." }, { "code": null, "e": 46264, "s": 46229, "text": "Every case value should be unique." }, { "code": null, "e": 46369, "s": 46264, "text": "The default case is optional. But it is important as it is executed when no case value could be matched." }, { "code": null, "e": 46410, "s": 46369, "text": "Basic Calculator Using Switch Statement:" }, { "code": null, "e": 46414, "s": 46410, "text": "C++" }, { "code": "// C++ program to implement// the switch statement#include <iostream>using namespace std; // Driver codeint main(){ int n1, n2; char op; cout << \"Enter 2 numbers: \"; cin >> n1 >> n2; cout << \"Enter operand: \"; cin >> op; switch (op) { case '+': cout << n1 + n2 << endl; break; case '-': cout << n1 - n2 << endl; break; case '*': cout << n1 * n2 << endl; break; case '/': cout << n1 / n2 << endl; break; case '%': cout << n1 % n2 << endl; break; default: cout << \"Operator not found!\" << endl; break; } return 0;}", "e": 47039, "s": 46414, "text": null }, { "code": null, "e": 47091, "s": 47039, "text": "Enter 2 numbers: Enter operand: Operator not found!" }, { "code": null, "e": 47290, "s": 47091, "text": "A loop is used for executing a block of statements repeatedly until a particular condition is satisfied. A loop consists of an initialization statement, a test condition, and an increment statement." }, { "code": null, "e": 47304, "s": 47290, "text": "1. for loop " }, { "code": null, "e": 47336, "s": 47304, "text": "The syntax of the for loop is " }, { "code": null, "e": 47399, "s": 47336, "text": "for (initialization; condition; update)\n{\n // body of-loop\n}" }, { "code": null, "e": 47447, "s": 47399, "text": "Below is the C++ program to implement for loop:" }, { "code": null, "e": 47451, "s": 47447, "text": "C++" }, { "code": "// C++ program to implement// for loop#include <iostream>using namespace std; // Driver codeint main(){ for (int i = 1; i <= 5; i++) { cout << i << \" \"; } return 0;}", "e": 47626, "s": 47451, "text": null }, { "code": null, "e": 47637, "s": 47626, "text": "1 2 3 4 5 " }, { "code": null, "e": 47650, "s": 47637, "text": "Explanation:" }, { "code": null, "e": 47871, "s": 47650, "text": "The for loop is initialized by the value 1, the test condition is i<=5 i.e the loop is executed till the value of i remains lesser than or equal to 5. In each iteration, the value of i is incremented by one by doing i++." }, { "code": null, "e": 47887, "s": 47871, "text": "2. while loop " }, { "code": null, "e": 47918, "s": 47887, "text": "The syntax for while loop is " }, { "code": null, "e": 47962, "s": 47918, "text": "while (condition) \n{\n // body of the loop\n}" }, { "code": null, "e": 48012, "s": 47962, "text": "Below is the C++ program to implement while loop:" }, { "code": null, "e": 48016, "s": 48012, "text": "C++" }, { "code": "// C++ program to implement// while loop#include <iostream>using namespace std; // Driver codeint main(){ int i = 1; while (i <= 5) { cout << i << \" \"; i++; } return 0;}", "e": 48199, "s": 48016, "text": null }, { "code": null, "e": 48210, "s": 48199, "text": "1 2 3 4 5 " }, { "code": null, "e": 48223, "s": 48210, "text": "Explanation:" }, { "code": null, "e": 48446, "s": 48223, "text": "The while loop is initialized by the value 1, the test condition is i<=5 i.e the loop is executed till the value of i remains lesser than or equal to 5. In each iteration, the value of i is incremented by one by doing i++." }, { "code": null, "e": 48466, "s": 48446, "text": "3. do͙ while loop " }, { "code": null, "e": 48497, "s": 48466, "text": "The syntax for while loop is " }, { "code": null, "e": 48540, "s": 48497, "text": "do {\n// body of loop;\n}\nwhile (condition);" }, { "code": null, "e": 48593, "s": 48540, "text": "Below is the C++ program to implement do-while loop:" }, { "code": null, "e": 48597, "s": 48593, "text": "C++" }, { "code": "// C++ program to implement// do-while loop#include <iostream>using namespace std; // Driver codeint main(){ int i = 1; do { cout << i << \" \"; i++; } while (i <= 5); return 0;}", "e": 48785, "s": 48597, "text": null }, { "code": null, "e": 48796, "s": 48785, "text": "1 2 3 4 5 " }, { "code": null, "e": 48809, "s": 48796, "text": "Explanation:" }, { "code": null, "e": 49157, "s": 48809, "text": "The do-while loop variable is initialized by the value 1, in each iteration, the value of i is incremented by one by doing i++, the test condition is i<=5 i.e the loop is executed till the value of i remains lesser than or equal to 5. Since the testing condition is checked only once the loop has already run so a do-while loop runs at least once." }, { "code": null, "e": 49398, "s": 49157, "text": "Jumps in loops are used to control the flow of loops. There are two statements used to implement jump in loops – Continue and Break. These statements are used when we need to change the flow of the loop when some specified condition is met." }, { "code": null, "e": 49412, "s": 49398, "text": "1. Continue " }, { "code": null, "e": 49626, "s": 49412, "text": "The continue statement is used to skip to the next iteration of that loop. This means that it stops one iteration of the loop. All the statements present after the continue statement in that loop are not executed." }, { "code": null, "e": 49688, "s": 49626, "text": "Below is the C++ program to implement the Continue statement:" }, { "code": null, "e": 49692, "s": 49688, "text": "C++" }, { "code": "// C++ program to implement// the continue statement#include <iostream>using namespace std; // Driver codeint main(){ int i; for (i = 1; i <= 20; i++) { if (i % 3 == 0) { continue; } cout << i << endl; }}", "e": 49921, "s": 49692, "text": null }, { "code": null, "e": 49957, "s": 49921, "text": "1\n2\n4\n5\n7\n8\n10\n11\n13\n14\n16\n17\n19\n20" }, { "code": null, "e": 49970, "s": 49957, "text": "Explanation:" }, { "code": null, "e": 50203, "s": 49970, "text": "In this for loop, whenever i is a number divisible by 3, it will not be printed as the loop will skip to the next iteration due to the continue statement. Hence, all the numbers except those which are divisible by 3 will be printed." }, { "code": null, "e": 50214, "s": 50203, "text": "2. Break " }, { "code": null, "e": 50450, "s": 50214, "text": "The break statement is used to terminate the current loop. As soon as the break statement is encountered in a loop, all further iterations of the loop are stopped and control is shifted to the first statement after the end of the loop." }, { "code": null, "e": 50509, "s": 50450, "text": "Below is the C++ program to implement the break statement:" }, { "code": null, "e": 50513, "s": 50509, "text": "C++" }, { "code": "// C++ program to implement// the break statement#include <iostream>using namespace std; // Driver codeint main(){ int i; for (i = 1; i <= 20; i++) { if (i == 11) { break; } cout << i << endl; }}", "e": 50733, "s": 50513, "text": null }, { "code": null, "e": 50754, "s": 50733, "text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10" }, { "code": null, "e": 50767, "s": 50754, "text": "Explanation:" }, { "code": null, "e": 50914, "s": 50767, "text": "In this loop, when i becomes equal to 11, the for loop terminates due to break statement, Hence, the program will print numbers from 1 to 10 only." }, { "code": null, "e": 50924, "s": 50914, "text": "as5853535" }, { "code": null, "e": 50948, "s": 50924, "text": "Technical Scripter 2020" }, { "code": null, "e": 50952, "s": 50948, "text": "C++" }, { "code": null, "e": 50971, "s": 50952, "text": "Technical Scripter" }, { "code": null, "e": 50975, "s": 50971, "text": "CPP" }, { "code": null, "e": 51073, "s": 50975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51101, "s": 51073, "text": "Operator Overloading in C++" }, { "code": null, "e": 51121, "s": 51101, "text": "Polymorphism in C++" }, { "code": null, "e": 51154, "s": 51121, "text": "Friend class and function in C++" }, { "code": null, "e": 51178, "s": 51154, "text": "Sorting a vector in C++" }, { "code": null, "e": 51203, "s": 51178, "text": "std::string class in C++" }, { "code": null, "e": 51227, "s": 51203, "text": "Inline Functions in C++" }, { "code": null, "e": 51271, "s": 51227, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 51324, "s": 51271, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 51360, "s": 51324, "text": "Convert string to char array in C++" } ]
MySQL Date Data Type
15 Feb, 2021 MySQL Date Data Type : There are various data types that are supported in MySQL. Among them sometimes we need to take DATE data type to store data values. The DATE type is used for values with a date part but no time part. It displays DATE values in ‘YYYY-MM-DD’ format. We can store any date value which is in the given range ‘1000-01-01’ to ‘9999-12-31’. Syntax : Variable_Name DATE The following examples will illustrate how we can use Date data type in a variable. Example 1 : Creating a StudentDetails table –It consists of Student_Id, First_name, Last_name, Date_Of_Birth, Class, Contact_Details columns. Among which the data type of Date_Of_Birth column is DATE. CREATE TABLE StudentDetails ( Student_Id INT AUTO_INCREMENT, First_name VARCHAR (100) NOT NULL, Last_name VARCHAR (100) NOT NULL, Date_Of_Birth DATE NOT NULL, Class VARCHAR (10) NOT NULL, Contact_Details BIGINT NOT NULL, PRIMARY KEY(Student_Id ) ); Inserting data into the Table – INSERT INTO StudentDetails(First_name , Last_name , Date_Of_Birth , Class, Contact_Details) VALUES ('Amit', 'Jana', '2004-12-22', 'XI', 1234567890), ('Manik', 'Aggarwal', '2006-07-04', 'IX', 1245678998), ('Nitin', 'Das', '2005-03-14', 'X', 2245664909), ('Priya', 'Pal', '2007-07-24', 'VIII', 3245642199), ('Biswanath', 'Sharma', '2005-11-11', 'X', 2456789761), ('Mani', 'Punia', '2006-01-20', 'IX', 3245675421), ('Pritam', 'Patel', '2008-01-04', 'VII', 3453415421), ('Sayak', 'Sharma', '2007-05-10', 'VIII' , 1214657890); To verify using the following command as follows. SELECT * FROM StudentDetails ; Output : So, we have successfully stored the DATE data-type in the Date_Of_Birth Column. Example 2 : Creating a ProductDetails table –It consists of ProductId, ProductName, and Manufactured_On columns, among which the data type for Manufactured_On columns is DATE. CREATE TABLE ProductDetails( ProductId INT NOT NULL, ProductName VARCHAR(20) NOT NULL, Manufactured_On DATE NOT NULL, PRIMARY KEY(ProductId) ); Inserting data into the Table –The CURRENTDATE function is used to assign value in the Manufactured_On column. The return data type for CURRENTDATE function is DATE. INSERT INTO ProductDetails(ProductId, ProductName, Manufactured_On) VALUES (11001, 'ASUS X554L', CURRENT_DATE()) ; To verify using the following command as follows. SELECT * from ProductDetails; Output : Example 3 : Creating an orders table –It consists of OrderNumber, OrderDate, ShippedDate, DeliveryDate columns. Among which the data type of OrderDate, ShippedDate, and DeliveryDate column is DATE. CREATE TABLE Orders( OrderNumber INT AUTO_INCREMENT, OrderDate DATE NOT NULL, ShippedDate DATE NOT NULL, DeliveryDate DATE NOT NULL, PRIMARY KEY(OrderNumber ) ); Inserting data into the Table – INSERT INTO Orders(OrderNumber , OrderDate , ShippedDate , DeliveryDate ) VALUES (1001, '2019-12-21', '2004-12-22', '2019-12-26'), (1002, '2020-01-21', '2020-01-21', '2020-01-22'), (1003, '2020-05-01', '2020-05-03', '2020-05-10'), (1004, '2020-07-31', '2020-08-01', '2020-08-01'); To verify used the following command as follows. SELECT * FROM Orders; Output : 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 | Sub queries in From Clause Window functions 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 RANK() Function in SQL Server How to Import JSON Data into SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2021" }, { "code": null, "e": 51, "s": 28, "text": "MySQL Date Data Type :" }, { "code": null, "e": 386, "s": 51, "text": "There are various data types that are supported in MySQL. Among them sometimes we need to take DATE data type to store data values. The DATE type is used for values with a date part but no time part. It displays DATE values in ‘YYYY-MM-DD’ format. We can store any date value which is in the given range ‘1000-01-01’ to ‘9999-12-31’. " }, { "code": null, "e": 395, "s": 386, "text": "Syntax :" }, { "code": null, "e": 414, "s": 395, "text": "Variable_Name DATE" }, { "code": null, "e": 498, "s": 414, "text": "The following examples will illustrate how we can use Date data type in a variable." }, { "code": null, "e": 510, "s": 498, "text": "Example 1 :" }, { "code": null, "e": 699, "s": 510, "text": "Creating a StudentDetails table –It consists of Student_Id, First_name, Last_name, Date_Of_Birth, Class, Contact_Details columns. Among which the data type of Date_Of_Birth column is DATE." }, { "code": null, "e": 1016, "s": 699, "text": "CREATE TABLE StudentDetails (\n Student_Id INT AUTO_INCREMENT, \n First_name VARCHAR (100) NOT NULL, \n Last_name VARCHAR (100) NOT NULL, \n Date_Of_Birth DATE NOT NULL, \n Class VARCHAR (10) NOT NULL, \n Contact_Details BIGINT NOT NULL, \n PRIMARY KEY(Student_Id ) \n);" }, { "code": null, "e": 1048, "s": 1016, "text": "Inserting data into the Table –" }, { "code": null, "e": 1608, "s": 1048, "text": "INSERT INTO \nStudentDetails(First_name , Last_name , Date_Of_Birth , Class, Contact_Details) \nVALUES \n('Amit', 'Jana', '2004-12-22', 'XI', 1234567890), \n('Manik', 'Aggarwal', '2006-07-04', 'IX', 1245678998), \n('Nitin', 'Das', '2005-03-14', 'X', 2245664909), \n('Priya', 'Pal', '2007-07-24', 'VIII', 3245642199), \n('Biswanath', 'Sharma', '2005-11-11', 'X', 2456789761), \n('Mani', 'Punia', '2006-01-20', 'IX', 3245675421), \n('Pritam', 'Patel', '2008-01-04', 'VII', 3453415421), \n('Sayak', 'Sharma', '2007-05-10', 'VIII' , 1214657890);" }, { "code": null, "e": 1658, "s": 1608, "text": "To verify using the following command as follows." }, { "code": null, "e": 1689, "s": 1658, "text": "SELECT * FROM StudentDetails ;" }, { "code": null, "e": 1698, "s": 1689, "text": "Output :" }, { "code": null, "e": 1778, "s": 1698, "text": "So, we have successfully stored the DATE data-type in the Date_Of_Birth Column." }, { "code": null, "e": 1790, "s": 1778, "text": "Example 2 :" }, { "code": null, "e": 1955, "s": 1790, "text": "Creating a ProductDetails table –It consists of ProductId, ProductName, and Manufactured_On columns, among which the data type for Manufactured_On columns is DATE." }, { "code": null, "e": 2099, "s": 1955, "text": "CREATE TABLE ProductDetails(\nProductId INT NOT NULL,\nProductName VARCHAR(20) NOT NULL,\nManufactured_On DATE NOT NULL,\nPRIMARY KEY(ProductId)\n);" }, { "code": null, "e": 2265, "s": 2099, "text": "Inserting data into the Table –The CURRENTDATE function is used to assign value in the Manufactured_On column. The return data type for CURRENTDATE function is DATE." }, { "code": null, "e": 2382, "s": 2265, "text": "INSERT INTO \nProductDetails(ProductId, ProductName, Manufactured_On)\nVALUES\n(11001, 'ASUS X554L', CURRENT_DATE()) ;" }, { "code": null, "e": 2432, "s": 2382, "text": "To verify using the following command as follows." }, { "code": null, "e": 2463, "s": 2432, "text": "SELECT * from ProductDetails;" }, { "code": null, "e": 2472, "s": 2463, "text": "Output :" }, { "code": null, "e": 2484, "s": 2472, "text": "Example 3 :" }, { "code": null, "e": 2670, "s": 2484, "text": "Creating an orders table –It consists of OrderNumber, OrderDate, ShippedDate, DeliveryDate columns. Among which the data type of OrderDate, ShippedDate, and DeliveryDate column is DATE." }, { "code": null, "e": 2848, "s": 2670, "text": "CREATE TABLE Orders(\n OrderNumber INT AUTO_INCREMENT,\n OrderDate DATE NOT NULL,\n ShippedDate DATE NOT NULL,\n DeliveryDate DATE NOT NULL,\n PRIMARY KEY(OrderNumber )\n);" }, { "code": null, "e": 2880, "s": 2848, "text": "Inserting data into the Table –" }, { "code": null, "e": 3164, "s": 2880, "text": "INSERT INTO \nOrders(OrderNumber , OrderDate , ShippedDate , DeliveryDate )\nVALUES \n(1001, '2019-12-21', '2004-12-22', '2019-12-26'),\n(1002, '2020-01-21', '2020-01-21', '2020-01-22'),\n(1003, '2020-05-01', '2020-05-03', '2020-05-10'),\n(1004, '2020-07-31', '2020-08-01', '2020-08-01');" }, { "code": null, "e": 3213, "s": 3164, "text": "To verify used the following command as follows." }, { "code": null, "e": 3235, "s": 3213, "text": "SELECT * FROM Orders;" }, { "code": null, "e": 3244, "s": 3235, "text": "Output :" }, { "code": null, "e": 3253, "s": 3244, "text": "DBMS-SQL" }, { "code": null, "e": 3259, "s": 3253, "text": "mysql" }, { "code": null, "e": 3263, "s": 3259, "text": "SQL" }, { "code": null, "e": 3267, "s": 3263, "text": "SQL" }, { "code": null, "e": 3365, "s": 3267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3431, "s": 3365, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 3464, "s": 3431, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 3488, "s": 3464, "text": "Window functions in SQL" }, { "code": null, "e": 3520, "s": 3488, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 3598, "s": 3520, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 3615, "s": 3598, "text": "SQL using Python" }, { "code": null, "e": 3651, "s": 3615, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 3681, "s": 3651, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 3722, "s": 3681, "text": "How to Import JSON Data into SQL Server?" } ]
JavaScript | Modules
10 Oct, 2019 In the previous article on closures in javascript, we learned that Closure is one of the most important yet most misunderstood concepts in Javascript. The closure is a methodology in which a child function can keep the environment of its parent scope even after the parent function has already been executed, we can say it otherwise to remember or recreate the scope and its members that already has been executed once. Now JavaScript modules are the best implementation of Closure. Modules are small units of independent, reusable code that is desired to be used as the building blocks in creating a non-trivial Javascript application. Modules let the developer define private and public members separately, making it one of the more desired design patterns in JavaScript paradigm. You may see modules as Classes as in any other Object-Oriented Programming Language. Note: In ES2015, the class keyword was used to define classes in Javascript, but even though JavaScript still stands tall to be a classless programming language while ES2015 classes are basically special functions. Coming back to Modules let us first see one example to see what Modules can do, we will try to simulate the behavior of a Rectangle Class giving in the length of two sides and getting back the area. <script>// This is a Rectangle Module. function Rectangle() { var length, width; function create(l, w) { length = l; width = w; } function getArea() { return (length * width); } function getPerimeter() { return (2 * (length + width)); } // This is the object to consist public members. // The rest are private members. var publicAPI = { create : create, getArea : getArea, getPerimeter : getPerimeter }; // To be returned upon creation of a new instance. return publicAPI; } // create a Rectangle module instance var myRect = Rectangle(); myRect.create(5, 4); document.write("Area: " + myRect.getArea()); document.write("<br> Perimeter: " + myRect.getPerimeter()); </script> Output: Area: 20 Perimeter: 18 Here, the Rectangle() function serves as an outer scope that contains the variables required i.e. length, width, as well as the functions create(), getArea(), and getPerimeter(). All these together are the private details of thisRectangle module that cannot be accessed/modified from the outside. On the other hand, the public API as the name suggests is an object that consists of three functional members and is returned when the Rectangle function execution is complete. Using the API methods we can create and get the value of the area and perimeter of the rectangle. Note: As we mentioned earlier that modules are the closest concepts of Classes in any other OOP language, many developers might feel like using the ‘new’ keyword while creating a new instance of the Rectangle Module. Rectangle() is just a function, not a proper class to be instantiated, so it’s just called normally. Using new would be inappropriate and actually waste resources. Executing Rectangle() creates an instance of the Rectangle module and a whole new scope is created and allocated to the function, and therefore a new instance of the member of the functions was generated, as we assigned it to a variable, now the variable had the reference to the allowed public API members. Hence, we can see that running the Rectangle() method creates a new instance entirely separate from any other previous one. All the member functions have a closure over the length and width, which means that these functions can access them even after the Rectangle() function execution is finished. That sums up how Modules work in JavaScript. We will uncover more interesting topics on JavaScript and make relevant projects to hone our newly learned skills soon. javascript-basics JavaScript 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 Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request How to get character array from string in JavaScript? JavaScript | Promises Node.js | fs.writeFileSync() Method How to filter object array based on attributes? Lodash _.debounce() Method
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Oct, 2019" }, { "code": null, "e": 474, "s": 54, "text": "In the previous article on closures in javascript, we learned that Closure is one of the most important yet most misunderstood concepts in Javascript. The closure is a methodology in which a child function can keep the environment of its parent scope even after the parent function has already been executed, we can say it otherwise to remember or recreate the scope and its members that already has been executed once." }, { "code": null, "e": 922, "s": 474, "text": "Now JavaScript modules are the best implementation of Closure. Modules are small units of independent, reusable code that is desired to be used as the building blocks in creating a non-trivial Javascript application. Modules let the developer define private and public members separately, making it one of the more desired design patterns in JavaScript paradigm. You may see modules as Classes as in any other Object-Oriented Programming Language." }, { "code": null, "e": 1137, "s": 922, "text": "Note: In ES2015, the class keyword was used to define classes in Javascript, but even though JavaScript still stands tall to be a classless programming language while ES2015 classes are basically special functions." }, { "code": null, "e": 1336, "s": 1137, "text": "Coming back to Modules let us first see one example to see what Modules can do, we will try to simulate the behavior of a Rectangle Class giving in the length of two sides and getting back the area." }, { "code": "<script>// This is a Rectangle Module. function Rectangle() { var length, width; function create(l, w) { length = l; width = w; } function getArea() { return (length * width); } function getPerimeter() { return (2 * (length + width)); } // This is the object to consist public members. // The rest are private members. var publicAPI = { create : create, getArea : getArea, getPerimeter : getPerimeter }; // To be returned upon creation of a new instance. return publicAPI; } // create a Rectangle module instance var myRect = Rectangle(); myRect.create(5, 4); document.write(\"Area: \" + myRect.getArea()); document.write(\"<br> Perimeter: \" + myRect.getPerimeter()); </script>", "e": 2143, "s": 1336, "text": null }, { "code": null, "e": 2151, "s": 2143, "text": "Output:" }, { "code": null, "e": 2175, "s": 2151, "text": "Area: 20\nPerimeter: 18\n" }, { "code": null, "e": 2747, "s": 2175, "text": "Here, the Rectangle() function serves as an outer scope that contains the variables required i.e. length, width, as well as the functions create(), getArea(), and getPerimeter(). All these together are the private details of thisRectangle module that cannot be accessed/modified from the outside. On the other hand, the public API as the name suggests is an object that consists of three functional members and is returned when the Rectangle function execution is complete. Using the API methods we can create and get the value of the area and perimeter of the rectangle." }, { "code": null, "e": 3128, "s": 2747, "text": "Note: As we mentioned earlier that modules are the closest concepts of Classes in any other OOP language, many developers might feel like using the ‘new’ keyword while creating a new instance of the Rectangle Module. Rectangle() is just a function, not a proper class to be instantiated, so it’s just called normally. Using new would be inappropriate and actually waste resources." }, { "code": null, "e": 3560, "s": 3128, "text": "Executing Rectangle() creates an instance of the Rectangle module and a whole new scope is created and allocated to the function, and therefore a new instance of the member of the functions was generated, as we assigned it to a variable, now the variable had the reference to the allowed public API members. Hence, we can see that running the Rectangle() method creates a new instance entirely separate from any other previous one." }, { "code": null, "e": 3735, "s": 3560, "text": "All the member functions have a closure over the length and width, which means that these functions can access them even after the Rectangle() function execution is finished." }, { "code": null, "e": 3900, "s": 3735, "text": "That sums up how Modules work in JavaScript. We will uncover more interesting topics on JavaScript and make relevant projects to hone our newly learned skills soon." }, { "code": null, "e": 3918, "s": 3900, "text": "javascript-basics" }, { "code": null, "e": 3929, "s": 3918, "text": "JavaScript" }, { "code": null, "e": 4027, "s": 3929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4088, "s": 4027, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4160, "s": 4088, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4200, "s": 4160, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4242, "s": 4200, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4283, "s": 4242, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4337, "s": 4283, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 4359, "s": 4337, "text": "JavaScript | Promises" }, { "code": null, "e": 4395, "s": 4359, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 4443, "s": 4395, "text": "How to filter object array based on attributes?" } ]
Linux Admin - User Management
When discussing user management, we have three important terms to understand − Users Groups Permissions We have already discussed in-depth permissions as applied to files and folders. In this chapter, let's discuss about users and groups. In CentOS, there are two types accounts − System accounts − Used for a daemon or other piece of software. System accounts − Used for a daemon or other piece of software. Interactive accounts − Usually assigned to a user for accessing system resources. Interactive accounts − Usually assigned to a user for accessing system resources. The main difference between the two user types is − System accounts are used by daemons to access files and directories. These will usually be disallowed from interactive login via shell or physical console login. System accounts are used by daemons to access files and directories. These will usually be disallowed from interactive login via shell or physical console login. Interactive accounts are used by end-users to access computing resources from either a shell or physical console login. Interactive accounts are used by end-users to access computing resources from either a shell or physical console login. With this basic understanding of users, let's now create a new user for Bob Jones in the Accounting Department. A new user is added with the adduser command. Following are some adduser common switches − When creating a new user, use the -c, -m, -g, -n switches as follows − [root@localhost Downloads]# useradd -c "Bob Jones Accounting Dept Manager" -m -g accounting -n bjones Now let's see if our new user has been created − [root@localhost Downloads]# id bjones (bjones) gid = 1001(accounting) groups = 1001(accounting) [root@localhost Downloads]# grep bjones /etc/passwd bjones:x:1001:1001:Bob Jones Accounting Dept Manager:/home/bjones:/bin/bash [root@localhost Downloads]# Now we need to enable the new account using the passwd command − [root@localhost Downloads]# passwd bjones Changing password for user bjones. New password: Retype new password: passwd: all authentication tokens updated successfully. [root@localhost Downloads]# The user account is not enabled allowing the user to log into the system. There are several methods to disable accounts on a system. These range from editing the /etc/passwd file by hand. Or even using the passwd command with the -lswitch. Both of these methods have one big drawback: if the user has ssh access and uses an RSA key for authentication, they can still login using this method. Now let’s use the chage command, changing the password expiry date to a previous date. Also, it may be good to make a note on the account as to why we disabled it. [root@localhost Downloads]# chage -E 2005-10-01 bjones [root@localhost Downloads]# usermod -c "Disabled Account while Bob out of the country for five months" bjones [root@localhost Downloads]# grep bjones /etc/passwd bjones:x:1001:1001:Disabled Account while Bob out of the country for four months:/home/bjones:/bin/bash [root@localhost Downloads]# Managing groups in Linux makes it convenient for an administrator to combine the users within containers applying permission-sets applicable to all group members. For example, all users in Accounting may need access to the same files. Thus, we make an accounting group, adding Accounting users. For the most part, anything requiring special permissions should be done in a group. This approach will usually save time over applying special permissions to just one user. Example, Sally is in-charge of reports and only Sally needs access to certain files for reporting. However, what if Sally is sick one day and Bob does reports? Or the need for reporting grows? When a group is made, an Administrator only needs to do it once. The add users is applied as needs change or expand. Following are some common commands used for managing groups − chgrp groupadd groups usermod chgrp − Changes the group ownership for a file or directory. Let's make a directory for people in the accounting group to store files and create directories for files. [root@localhost Downloads]# mkdir /home/accounting [root@localhost Downloads]# ls -ld /home/accounting drwxr-xr-x. 2 root root 6 Jan 13 10:18 /home/accounting [root@localhost Downloads]# Next, let's give group ownership to the accounting group. [root@localhost Downloads]# chgrp -v accounting /home/accounting/ changed group of ‘/home/accounting/’ from root to accounting [root@localhost Downloads]# ls -ld /home/accounting/ drwxr-xr-x. 2 root accounting 6 Jan 13 10:18 /home/accounting/ [root@localhost Downloads]# Now, everyone in the accounting group has read and execute permissions to /home/accounting. They will need write permissions as well. [root@localhost Downloads]# chmod g+w /home/accounting/ [root@localhost Downloads]# ls -ld /home/accounting/ drwxrwxr-x. 2 root accounting 6 Jan 13 10:18 /home/accounting/ [root@localhost Downloads]# Since the accounting group may deal with sensitive documents, we need to apply some restrictive permissions for other or world. [root@localhost Downloads]# chmod o-rx /home/accounting/ [root@localhost Downloads]# ls -ld /home/accounting/ drwxrwx---. 2 root accounting 6 Jan 13 10:18 /home/accounting/ [root@localhost Downloads]# groupadd − Used to make a new group. Let's make a new group called secret. We will add a password to the group, allowing the users to add themselves with a known password. [root@localhost]# groupadd secret [root@localhost]# gpasswd secret Changing the password for group secret New Password: Re-enter new password: [root@localhost]# exit exit [centos@localhost ~]$ newgrp secret Password: [centos@localhost ~]$ groups secret wheel rdc [centos@localhost ~]$ In practice, passwords for groups are not used often. Secondary groups are adequate and sharing passwords amongst other users is not a great security practice. The groups command is used to show which group a user belongs to. We will use this, after making some changes to our current user. usermod is used to update account attributes. Following are the common usermod switches. [root@localhost]# groups centos centos : accounting secret [root@localhost]# [root@localhost]# usermod -a -G wheel centos [root@localhost]# groups centos centos : accounting wheel secret
[ { "code": null, "e": 2470, "s": 2391, "text": "When discussing user management, we have three important terms to understand −" }, { "code": null, "e": 2476, "s": 2470, "text": "Users" }, { "code": null, "e": 2483, "s": 2476, "text": "Groups" }, { "code": null, "e": 2495, "s": 2483, "text": "Permissions" }, { "code": null, "e": 2630, "s": 2495, "text": "We have already discussed in-depth permissions as applied to files and folders. In this chapter, let's discuss about users and groups." }, { "code": null, "e": 2672, "s": 2630, "text": "In CentOS, there are two types accounts −" }, { "code": null, "e": 2736, "s": 2672, "text": "System accounts − Used for a daemon or other piece of software." }, { "code": null, "e": 2800, "s": 2736, "text": "System accounts − Used for a daemon or other piece of software." }, { "code": null, "e": 2882, "s": 2800, "text": "Interactive accounts − Usually assigned to a user for accessing system resources." }, { "code": null, "e": 2964, "s": 2882, "text": "Interactive accounts − Usually assigned to a user for accessing system resources." }, { "code": null, "e": 3016, "s": 2964, "text": "The main difference between the two user types is −" }, { "code": null, "e": 3178, "s": 3016, "text": "System accounts are used by daemons to access files and directories. These will usually be disallowed from interactive login via shell or physical console login." }, { "code": null, "e": 3340, "s": 3178, "text": "System accounts are used by daemons to access files and directories. These will usually be disallowed from interactive login via shell or physical console login." }, { "code": null, "e": 3460, "s": 3340, "text": "Interactive accounts are used by end-users to access computing resources from either a shell or physical console login." }, { "code": null, "e": 3580, "s": 3460, "text": "Interactive accounts are used by end-users to access computing resources from either a shell or physical console login." }, { "code": null, "e": 3738, "s": 3580, "text": "With this basic understanding of users, let's now create a new user for Bob Jones in the Accounting Department. A new user is added with the adduser command." }, { "code": null, "e": 3783, "s": 3738, "text": "Following are some adduser common switches −" }, { "code": null, "e": 3854, "s": 3783, "text": "When creating a new user, use the -c, -m, -g, -n switches as follows −" }, { "code": null, "e": 3959, "s": 3854, "text": "[root@localhost Downloads]# useradd -c \"Bob Jones Accounting Dept Manager\" \n-m -g accounting -n bjones\n" }, { "code": null, "e": 4008, "s": 3959, "text": "Now let's see if our new user has been created −" }, { "code": null, "e": 4266, "s": 4008, "text": "[root@localhost Downloads]# id bjones \n(bjones) gid = 1001(accounting) groups = 1001(accounting)\n\n[root@localhost Downloads]# grep bjones /etc/passwd \nbjones:x:1001:1001:Bob Jones Accounting Dept Manager:/home/bjones:/bin/bash\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 4331, "s": 4266, "text": "Now we need to enable the new account using the passwd command −" }, { "code": null, "e": 4535, "s": 4331, "text": "[root@localhost Downloads]# passwd bjones \nChanging password for user bjones. \nNew password: \nRetype new password: \npasswd: all authentication tokens updated successfully.\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 4609, "s": 4535, "text": "The user account is not enabled allowing the user to log into the system." }, { "code": null, "e": 4927, "s": 4609, "text": "There are several methods to disable accounts on a system. These range from editing the /etc/passwd file by hand. Or even using the passwd command with the -lswitch. Both of these methods have one big drawback: if the user has ssh access and uses an RSA key for authentication, they can still login using this method." }, { "code": null, "e": 5091, "s": 4927, "text": "Now let’s use the chage command, changing the password expiry date to a previous date. Also, it may be good to make a note on the account as to why we disabled it." }, { "code": null, "e": 5449, "s": 5091, "text": "[root@localhost Downloads]# chage -E 2005-10-01 bjones\n \n[root@localhost Downloads]# usermod -c \"Disabled Account while Bob out of the country \nfor five months\" bjones\n\n[root@localhost Downloads]# grep bjones /etc/passwd \nbjones:x:1001:1001:Disabled Account while Bob out of the country for four \nmonths:/home/bjones:/bin/bash\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 5744, "s": 5449, "text": "Managing groups in Linux makes it convenient for an administrator to combine the users within containers applying permission-sets applicable to all group members. For example, all users in Accounting may need access to the same files. Thus, we make an accounting group, adding Accounting users." }, { "code": null, "e": 6228, "s": 5744, "text": "For the most part, anything requiring special permissions should be done in a group. This approach will usually save time over applying special permissions to just one user. Example, Sally is in-charge of reports and only Sally needs access to certain files for reporting. However, what if Sally is sick one day and Bob does reports? Or the need for reporting grows? When a group is made, an Administrator only needs to do it once. The add users is applied as needs change or expand." }, { "code": null, "e": 6290, "s": 6228, "text": "Following are some common commands used for managing groups −" }, { "code": null, "e": 6296, "s": 6290, "text": "chgrp" }, { "code": null, "e": 6305, "s": 6296, "text": "groupadd" }, { "code": null, "e": 6312, "s": 6305, "text": "groups" }, { "code": null, "e": 6320, "s": 6312, "text": "usermod" }, { "code": null, "e": 6381, "s": 6320, "text": "chgrp − Changes the group ownership for a file or directory." }, { "code": null, "e": 6488, "s": 6381, "text": "Let's make a directory for people in the accounting group to store files and create directories for files." }, { "code": null, "e": 6678, "s": 6488, "text": "[root@localhost Downloads]# mkdir /home/accounting\n\n[root@localhost Downloads]# ls -ld /home/accounting\ndrwxr-xr-x. 2 root root 6 Jan 13 10:18 /home/accounting\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 6736, "s": 6678, "text": "Next, let's give group ownership to the accounting group." }, { "code": null, "e": 7013, "s": 6736, "text": "[root@localhost Downloads]# chgrp -v accounting /home/accounting/ \nchanged group of ‘/home/accounting/’ from root to accounting\n\n[root@localhost Downloads]# ls -ld /home/accounting/ \ndrwxr-xr-x. 2 root accounting 6 Jan 13 10:18 /home/accounting/\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 7147, "s": 7013, "text": "Now, everyone in the accounting group has read and execute permissions to /home/accounting. They will need write permissions as well." }, { "code": null, "e": 7351, "s": 7147, "text": "[root@localhost Downloads]# chmod g+w /home/accounting/\n\n[root@localhost Downloads]# ls -ld /home/accounting/ \ndrwxrwxr-x. 2 root accounting 6 Jan 13 10:18 /home/accounting/\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 7479, "s": 7351, "text": "Since the accounting group may deal with sensitive documents, we need to apply some restrictive permissions for other or world." }, { "code": null, "e": 7684, "s": 7479, "text": "[root@localhost Downloads]# chmod o-rx /home/accounting/\n\n[root@localhost Downloads]# ls -ld /home/accounting/ \ndrwxrwx---. 2 root accounting 6 Jan 13 10:18 /home/accounting/\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 7721, "s": 7684, "text": "groupadd − Used to make a new group." }, { "code": null, "e": 7856, "s": 7721, "text": "Let's make a new group called secret. We will add a password to the group, allowing the users to add themselves with a known password." }, { "code": null, "e": 8154, "s": 7856, "text": "[root@localhost]# groupadd secret\n\n[root@localhost]# gpasswd secret \nChanging the password for group secret \nNew Password: \nRe-enter new password:\n\n[root@localhost]# exit \nexit\n\n[centos@localhost ~]$ newgrp secret \nPassword:\n\n[centos@localhost ~]$ groups \nsecret wheel rdc\n\n[centos@localhost ~]$\n" }, { "code": null, "e": 8314, "s": 8154, "text": "In practice, passwords for groups are not used often. Secondary groups are adequate and sharing passwords amongst other users is not a great security practice." }, { "code": null, "e": 8445, "s": 8314, "text": "The groups command is used to show which group a user belongs to. We will use this, after making some changes to our current user." }, { "code": null, "e": 8491, "s": 8445, "text": "usermod is used to update account attributes." }, { "code": null, "e": 8534, "s": 8491, "text": "Following are the common usermod switches." } ]
Program for Perrin numbers
20 Apr, 2021 The Perrin numbers are the numbers in the following integer sequence. 3, 0, 2, 3, 2, 5, 5, 7, 10, 12, 17, 22, 29, 39 ... In mathematical terms, the sequence p(n) of Perrin numbers is defined by the recurrence relation P(n) = P(n-2) + P(n-3) for n > 2, with initial values P(0) = 3, P(1) = 0, P(2) = 2. Write a function int per(int n) that returns p(n). For example, if n = 0, then per() should return 3. If n = 1, then it should return 0 If n = 2, then it should return 2. For n > 2, it should return p(n-2) + p(n-3) Method 1 ( Use recursion : Exponential ) Below is simple recursive implementation of above formula. C++ C Java Python3 C# PHP Javascript // n'th perrin number using Recursion'#include <bits/stdc++.h>using namespace std; int per(int n){ if (n == 0) return 3; if (n == 1) return 0; if (n == 2) return 2; return per(n - 2) + per(n - 3);} // Driver codeint main(){ int n = 9; cout << per(n); return 0;} // This code is contributed// by Akanksha Rai // n'th perrin number using Recursion'#include <stdio.h>int per(int n){ if (n == 0) return 3; if (n == 1) return 0; if (n == 2) return 2; return per(n - 2) + per(n - 3);} // Driver codeint main(){ int n = 9; printf("%d", per(n)); return 0;} // Java code for n'th perrin number// using Recursion'import java.io.*; class GFG { static int per(int n) { if (n == 0) return 3; if (n == 1) return 0; if (n == 2) return 2; return per(n - 2) + per(n - 3); } // Driver code public static void main(String[] args) { int n = 9; System.out.println(per(n)); }} // This code is contributed by vt_m. # Python3 code for n'th perrin# number using Recursion' # function return n'th# perrin numberdef per(n): if (n == 0): return 3; if (n == 1): return 0; if (n == 2): return 2; return per(n - 2) + per(n - 3); # Driver Coden = 9;print(per(n)); # This code is contributed mits // C# code for n'th perrin number// using Recursion'using System; class GFG { static int per(int n) { if (n == 0) return 3; if (n == 1) return 0; if (n == 2) return 2; return per(n - 2) + per(n - 3); } // Driver code public static void Main() { int n = 9; Console.Write(per(n)); }} // This code is contributed by vt_m. <?php// PHP code for n'th perrin// number using Recursion' // function return n'th// perrin numberfunction per($n){ if ($n == 0) return 3; if ($n == 1) return 0; if ($n == 2) return 2; return per($n - 2) + per($n - 3);} // Driver Code $n = 9; echo per($n); #This code is contributed ajit.?> <script> // Javascript code for n'th perrin number// using Recursion' function per(n) { if (n == 0) return 3; if (n == 1) return 0; if (n == 2) return 2; return per(n - 2) + per(n - 3); } // Driver code let n = 9; document.write(per(n)); </script> Output: 12 We see that in this implementation a lot of repeated work in the following recursion tree. per(8) / \ per(6) per(5) / \ / \ per(4) per(3) per(3) per(2) / \ / \ / \ per(2) per(1) per(1) per(0) per(1) per(0) Method 2: ( Optimized : Linear) C++ C Java C# PHP Javascript // Optimized C++ program for n'th perrin number#include <bits/stdc++.h>using namespace std;int per(int n){ int a = 3, b = 0, c = 2, i; int m; if (n == 0) return a; if (n == 1) return b; if (n == 2) return c; while (n > 2) { m = a + b; a = b; b = c; c = m; n--; } return m;} // Driver codeint main(){ int n = 9; cout << per(n); return 0;} // This code is contributed// by Akanksha Rai // Optimized C program for n'th perrin number#include <stdio.h>int per(int n){ int a = 3, b = 0, c = 2, i; int m; if (n == 0) return a; if (n == 1) return b; if (n == 2) return c; while (n > 2) { m = a + b; a = b; b = c; c = m; n--; } return m;} // Driver codeint main(){ int n = 9; printf("%d", per(n)); return 0;} // Optimized Java program for n'th perrin numberimport java.io.*; class GFG { static int per(int n) { int a = 3, b = 0, c = 2, i; int m = 0; if (n == 0) return a; if (n == 1) return b; if (n == 2) return c; while (n > 2) { m = a + b; a = b; b = c; c = m; n--; } return m; } // Driver code public static void main(String[] args) { int n = 9; System.out.println(per(n)); }} // This code is contributed by vt_m. // Optimized C# program for n'th perrin numberusing System; class GFG { static int per(int n) { int a = 3, b = 0, c = 2; // int i; int m = 0; if (n == 0) return a; if (n == 1) return b; if (n == 2) return c; while (n > 2) { m = a + b; a = b; b = c; c = m; n--; } return m; } // Driver code public static void Main() { int n = 9; Console.WriteLine(per(n)); }} // This code is contributed by vt_m. <?php// Optimized PHP program for// n'th perrin number // function return the// n'th perrin numberfunction per($n){ $a = 3; $b = 0; $c = 2; $i; $m; if ($n == 0) return $a; if ($n == 1) return $b; if ($n == 2) return $c; while ($n > 2) { $m = $a + $b; $a = $b; $b = $c; $c = $m; $n--; } return $m;} // Driver code $n = 9; echo per($n); // This code is contributed by ajit?> <script>// Optimized Javascript program for// n'th perrin number // function return the// n'th perrin numberfunction per(n){ let a = 3; let b = 0; let c = 2; let i; let m; if (n == 0) return a; if (n == 1) return b; if (n == 2) return c; while (n > 2) { m = a + b; a = b; b = c; c = m; n--; } return m;} // Driver code n = 9; document.write(per(n)); // This code is contributed by _saurabh_jaiswal</script> Output: 12 Time Complexity : O(n) Auxiliary Space : O(1)Method 3: (Further Optimized : Logarithmic) We can further optimize using Matrix Exponentiation. The matrix power formula for n’th Perrin number is We can implement this method similar to implementation of method 5 of Fibonacci numbers. Since we can compute n’th power of a constant matrix in O(Log n), time complexity of this method is O(Log n)Application : The number of different maximal independent sets in an n-vertex cycle graph is counted by the nth Perrin number for n > 1Related Article : Sum of Perrin NumbersReference: https://en.wikipedia.org/wiki/Perrin_numberThis article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Mithun Kumar Akanksha_Rai splevel62 _saurabh_jaiswal series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Minimum number of jumps to reach end The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples Program for factorial of a number Merge two sorted arrays with O(1) extra space
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Apr, 2021" }, { "code": null, "e": 273, "s": 53, "text": "The Perrin numbers are the numbers in the following integer sequence. 3, 0, 2, 3, 2, 5, 5, 7, 10, 12, 17, 22, 29, 39 ... In mathematical terms, the sequence p(n) of Perrin numbers is defined by the recurrence relation " }, { "code": null, "e": 365, "s": 273, "text": " P(n) = P(n-2) + P(n-3) for n > 2, \n\nwith initial values\n P(0) = 3, P(1) = 0, P(2) = 2. " }, { "code": null, "e": 582, "s": 365, "text": "Write a function int per(int n) that returns p(n). For example, if n = 0, then per() should return 3. If n = 1, then it should return 0 If n = 2, then it should return 2. For n > 2, it should return p(n-2) + p(n-3) " }, { "code": null, "e": 683, "s": 582, "text": "Method 1 ( Use recursion : Exponential ) Below is simple recursive implementation of above formula. " }, { "code": null, "e": 687, "s": 683, "text": "C++" }, { "code": null, "e": 689, "s": 687, "text": "C" }, { "code": null, "e": 694, "s": 689, "text": "Java" }, { "code": null, "e": 702, "s": 694, "text": "Python3" }, { "code": null, "e": 705, "s": 702, "text": "C#" }, { "code": null, "e": 709, "s": 705, "text": "PHP" }, { "code": null, "e": 720, "s": 709, "text": "Javascript" }, { "code": "// n'th perrin number using Recursion'#include <bits/stdc++.h>using namespace std; int per(int n){ if (n == 0) return 3; if (n == 1) return 0; if (n == 2) return 2; return per(n - 2) + per(n - 3);} // Driver codeint main(){ int n = 9; cout << per(n); return 0;} // This code is contributed// by Akanksha Rai", "e": 1070, "s": 720, "text": null }, { "code": "// n'th perrin number using Recursion'#include <stdio.h>int per(int n){ if (n == 0) return 3; if (n == 1) return 0; if (n == 2) return 2; return per(n - 2) + per(n - 3);} // Driver codeint main(){ int n = 9; printf(\"%d\", per(n)); return 0;}", "e": 1353, "s": 1070, "text": null }, { "code": "// Java code for n'th perrin number// using Recursion'import java.io.*; class GFG { static int per(int n) { if (n == 0) return 3; if (n == 1) return 0; if (n == 2) return 2; return per(n - 2) + per(n - 3); } // Driver code public static void main(String[] args) { int n = 9; System.out.println(per(n)); }} // This code is contributed by vt_m.", "e": 1796, "s": 1353, "text": null }, { "code": "# Python3 code for n'th perrin# number using Recursion' # function return n'th# perrin numberdef per(n): if (n == 0): return 3; if (n == 1): return 0; if (n == 2): return 2; return per(n - 2) + per(n - 3); # Driver Coden = 9;print(per(n)); # This code is contributed mits", "e": 2106, "s": 1796, "text": null }, { "code": "// C# code for n'th perrin number// using Recursion'using System; class GFG { static int per(int n) { if (n == 0) return 3; if (n == 1) return 0; if (n == 2) return 2; return per(n - 2) + per(n - 3); } // Driver code public static void Main() { int n = 9; Console.Write(per(n)); }} // This code is contributed by vt_m.", "e": 2525, "s": 2106, "text": null }, { "code": "<?php// PHP code for n'th perrin// number using Recursion' // function return n'th// perrin numberfunction per($n){ if ($n == 0) return 3; if ($n == 1) return 0; if ($n == 2) return 2; return per($n - 2) + per($n - 3);} // Driver Code $n = 9; echo per($n); #This code is contributed ajit.?>", "e": 2873, "s": 2525, "text": null }, { "code": "<script> // Javascript code for n'th perrin number// using Recursion' function per(n) { if (n == 0) return 3; if (n == 1) return 0; if (n == 2) return 2; return per(n - 2) + per(n - 3); } // Driver code let n = 9; document.write(per(n)); </script>", "e": 3229, "s": 2873, "text": null }, { "code": null, "e": 3238, "s": 3229, "text": "Output: " }, { "code": null, "e": 3241, "s": 3238, "text": "12" }, { "code": null, "e": 3334, "s": 3241, "text": "We see that in this implementation a lot of repeated work in the following recursion tree. " }, { "code": null, "e": 3642, "s": 3334, "text": " per(8) \n / \\ \n per(6) per(5) \n / \\ / \\\n per(4) per(3) per(3) per(2)\n / \\ / \\ / \\ \n per(2) per(1) per(1) per(0) per(1) per(0)" }, { "code": null, "e": 3676, "s": 3642, "text": "Method 2: ( Optimized : Linear) " }, { "code": null, "e": 3680, "s": 3676, "text": "C++" }, { "code": null, "e": 3682, "s": 3680, "text": "C" }, { "code": null, "e": 3687, "s": 3682, "text": "Java" }, { "code": null, "e": 3690, "s": 3687, "text": "C#" }, { "code": null, "e": 3694, "s": 3690, "text": "PHP" }, { "code": null, "e": 3705, "s": 3694, "text": "Javascript" }, { "code": "// Optimized C++ program for n'th perrin number#include <bits/stdc++.h>using namespace std;int per(int n){ int a = 3, b = 0, c = 2, i; int m; if (n == 0) return a; if (n == 1) return b; if (n == 2) return c; while (n > 2) { m = a + b; a = b; b = c; c = m; n--; } return m;} // Driver codeint main(){ int n = 9; cout << per(n); return 0;} // This code is contributed// by Akanksha Rai", "e": 4178, "s": 3705, "text": null }, { "code": "// Optimized C program for n'th perrin number#include <stdio.h>int per(int n){ int a = 3, b = 0, c = 2, i; int m; if (n == 0) return a; if (n == 1) return b; if (n == 2) return c; while (n > 2) { m = a + b; a = b; b = c; c = m; n--; } return m;} // Driver codeint main(){ int n = 9; printf(\"%d\", per(n)); return 0;}", "e": 4583, "s": 4178, "text": null }, { "code": "// Optimized Java program for n'th perrin numberimport java.io.*; class GFG { static int per(int n) { int a = 3, b = 0, c = 2, i; int m = 0; if (n == 0) return a; if (n == 1) return b; if (n == 2) return c; while (n > 2) { m = a + b; a = b; b = c; c = m; n--; } return m; } // Driver code public static void main(String[] args) { int n = 9; System.out.println(per(n)); }} // This code is contributed by vt_m.", "e": 5174, "s": 4583, "text": null }, { "code": "// Optimized C# program for n'th perrin numberusing System; class GFG { static int per(int n) { int a = 3, b = 0, c = 2; // int i; int m = 0; if (n == 0) return a; if (n == 1) return b; if (n == 2) return c; while (n > 2) { m = a + b; a = b; b = c; c = m; n--; } return m; } // Driver code public static void Main() { int n = 9; Console.WriteLine(per(n)); }} // This code is contributed by vt_m.", "e": 5763, "s": 5174, "text": null }, { "code": "<?php// Optimized PHP program for// n'th perrin number // function return the// n'th perrin numberfunction per($n){ $a = 3; $b = 0; $c = 2; $i; $m; if ($n == 0) return $a; if ($n == 1) return $b; if ($n == 2) return $c; while ($n > 2) { $m = $a + $b; $a = $b; $b = $c; $c = $m; $n--; } return $m;} // Driver code $n = 9; echo per($n); // This code is contributed by ajit?>", "e": 6236, "s": 5763, "text": null }, { "code": "<script>// Optimized Javascript program for// n'th perrin number // function return the// n'th perrin numberfunction per(n){ let a = 3; let b = 0; let c = 2; let i; let m; if (n == 0) return a; if (n == 1) return b; if (n == 2) return c; while (n > 2) { m = a + b; a = b; b = c; c = m; n--; } return m;} // Driver code n = 9; document.write(per(n)); // This code is contributed by _saurabh_jaiswal</script>", "e": 6750, "s": 6236, "text": null }, { "code": null, "e": 6760, "s": 6750, "text": "Output: " }, { "code": null, "e": 6763, "s": 6760, "text": "12" }, { "code": null, "e": 7805, "s": 6763, "text": "Time Complexity : O(n) Auxiliary Space : O(1)Method 3: (Further Optimized : Logarithmic) We can further optimize using Matrix Exponentiation. The matrix power formula for n’th Perrin number is We can implement this method similar to implementation of method 5 of Fibonacci numbers. Since we can compute n’th power of a constant matrix in O(Log n), time complexity of this method is O(Log n)Application : The number of different maximal independent sets in an n-vertex cycle graph is counted by the nth Perrin number for n > 1Related Article : Sum of Perrin NumbersReference: https://en.wikipedia.org/wiki/Perrin_numberThis article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7811, "s": 7805, "text": "jit_t" }, { "code": null, "e": 7824, "s": 7811, "text": "Mithun Kumar" }, { "code": null, "e": 7837, "s": 7824, "text": "Akanksha_Rai" }, { "code": null, "e": 7847, "s": 7837, "text": "splevel62" }, { "code": null, "e": 7864, "s": 7847, "text": "_saurabh_jaiswal" }, { "code": null, "e": 7871, "s": 7864, "text": "series" }, { "code": null, "e": 7884, "s": 7871, "text": "Mathematical" }, { "code": null, "e": 7897, "s": 7884, "text": "Mathematical" }, { "code": null, "e": 7904, "s": 7897, "text": "series" }, { "code": null, "e": 8002, "s": 7904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8026, "s": 8002, "text": "Merge two sorted arrays" }, { "code": null, "e": 8047, "s": 8026, "text": "Operators in C / C++" }, { "code": null, "e": 8061, "s": 8047, "text": "Prime Numbers" }, { "code": null, "e": 8098, "s": 8061, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 8141, "s": 8098, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 8173, "s": 8141, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 8200, "s": 8173, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 8243, "s": 8200, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 8277, "s": 8243, "text": "Program for factorial of a number" } ]
What is SPA (Single page application) in AngularJS?
23 Jul, 2020 Traditionally, applications were Multi-Page Application (MPA) where with every click a new page would be loaded from the server. This was not only time consuming but also increased the server load and made the website slower. AngularJS is a JavaScript-based front-end web framework based on bidirectional UI data binding and is used to design Single Page Applications. Single Page Applications are web applications that load a single HTML page and only a part of the page instead of the entire page gets updated with every click of the mouse. The page does not reload or transfer control to another page during the process. This ensures high performance and loading pages faster. Most modern applications use the concept of SPA. In the SPA, the whole data is sent to the client from the server at the beginning. As the client clicks certain parts on the webpage, only the required part of the information is fetched from the server and the page is rewritten dynamically. This results in a lesser load on the server and is cost-efficient. SPAs use AJAX and HTML5 to create a fluid and responsive Web applications and most of the work happens on the client-side. Popular applications such as Facebook, Gmail, Twitter, Google Drive, Netflix, and many more are examples of SPA.Advantages: Team collaborationSingle-page applications are excellent when more than one developer is working on the same project. It allows backend developers to focus on the API, while the frontend developers can focus on creating the user interface based on the backend API. CachingThe application sends a single request to the server and stores all the received information in the cache. This proves beneficial when the client has poor network connectivity. Fast and responsiveAs only parts of the pages are loaded dynamically, it improves the website’s speed. Debugging is easierDebugging single page applications with chrome is easier since such applications are developed using like AngularJS Batarang and React developer tools. Linear user experienceBrowsing or navigating through the website is easy. Disadvantages: SEO optimizationSPAs provide poor SEO optimization. This is because single-page applications operate on JavaScript and load data at once server. The URL does not change and different pages do not have a unique URL. Hence it is hard for the search engines to index the SPA website as opposed to traditional server-rendered pages. Browser historyA SPA does not save the users’ transition of states within the website. A browser saves the previous pages only, not the state transition. Thus when users click the back button, they are not redirected to the previous state of the website. To solve this problem, developers can equip their SPA frameworks with the HTML5 History API. Security issuesSingle-page apps are less immune to cross-site scripting (XSS) and since no new pages are loaded, hackers can easily gain access to the website and inject new scripts on the client-side. Memory ConsumptionSince the SPA can run for a long time sometimes hours at a time, one needs to make sure the application does not consume more memory than it needs. Else, users with low memory devices may face serious performance issues. Disabled JavascriptDevelopers need to chalk out ideas for users to access the information on the website for browsers that have Javascript disabled. When to use SPASPAs are good when the volume of data is small and the website that needs a dynamic platform. It is also a good option for mobile applications. But businesses that depend largely on search engine optimizations such as e-commerce applications must avoid single-page applications and opt for MPAs. <!DOCTYPE html><!--ng-app directive tells AngularJS that myApp is the root element of the application --><html ng-app="myApp"> <head> <!--import the angularjs libraries--> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js"> </script> </head> <body> <!--hg-template indicates the pages that get loaded as per requirement--> <script type="text/ng-template" id="first.html"> <h1>First Page</h1> <h2 style="color:green"> Welcome to GeeksForGeeks </h2> <h3>{{message}}</h3> </script> <script type="text/ng-template" id="second.html"> <h1>Second Page</h1> <h2 style="color:green"> Start Learning With GFG </h2> <h3>{{message}}</h3> </script> <script type="text/ng-template" id="third.html"> <h1>Third Page</h1> <h2 style="color:green"> Know about us </h2> <h3>{{message}}</h3> </script> <!--hyperlinks to load different pages dynamically--> <a href="#/">First</a> <a href="#/second">Second</a> <a href="#/third">Third</a> <!--ng-view includes the rendered template of the current route into the main page--> <div ng-view></div> <script> var app = angular.module('myApp', []); var app = angular.module('myApp', ['ngRoute']); app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl : 'first.html', controller : 'FirstController' }) .when('/second', { templateUrl : 'second.html', controller : 'SecondController' }) .when('/third', { templateUrl : 'third.html', controller : 'ThirdController' }) .otherwise({redirectTo: '/'}); }); <!-- controller is a JS function that maintains application data and behavior using $scope object --> <!--properties and methods can be attached to the $scope object inside a controller function--> app.controller('FirstController', function($scope) { $scope.message = 'Hello from FirstController'; }); app.controller('SecondController', function($scope) { $scope.message = 'Hello from SecondController'; }); app.controller('ThirdController', function($scope) { $scope.message = 'Hello from ThirdController'; }); </script> </body></html> Output: AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jul, 2020" }, { "code": null, "e": 1313, "s": 28, "text": "Traditionally, applications were Multi-Page Application (MPA) where with every click a new page would be loaded from the server. This was not only time consuming but also increased the server load and made the website slower. AngularJS is a JavaScript-based front-end web framework based on bidirectional UI data binding and is used to design Single Page Applications. Single Page Applications are web applications that load a single HTML page and only a part of the page instead of the entire page gets updated with every click of the mouse. The page does not reload or transfer control to another page during the process. This ensures high performance and loading pages faster. Most modern applications use the concept of SPA. In the SPA, the whole data is sent to the client from the server at the beginning. As the client clicks certain parts on the webpage, only the required part of the information is fetched from the server and the page is rewritten dynamically. This results in a lesser load on the server and is cost-efficient. SPAs use AJAX and HTML5 to create a fluid and responsive Web applications and most of the work happens on the client-side. Popular applications such as Facebook, Gmail, Twitter, Google Drive, Netflix, and many more are examples of SPA.Advantages:" }, { "code": null, "e": 1578, "s": 1313, "text": "Team collaborationSingle-page applications are excellent when more than one developer is working on the same project. It allows backend developers to focus on the API, while the frontend developers can focus on creating the user interface based on the backend API." }, { "code": null, "e": 1762, "s": 1578, "text": "CachingThe application sends a single request to the server and stores all the received information in the cache. This proves beneficial when the client has poor network connectivity." }, { "code": null, "e": 1865, "s": 1762, "text": "Fast and responsiveAs only parts of the pages are loaded dynamically, it improves the website’s speed." }, { "code": null, "e": 2036, "s": 1865, "text": "Debugging is easierDebugging single page applications with chrome is easier since such applications are developed using like AngularJS Batarang and React developer tools." }, { "code": null, "e": 2110, "s": 2036, "text": "Linear user experienceBrowsing or navigating through the website is easy." }, { "code": null, "e": 2125, "s": 2110, "text": "Disadvantages:" }, { "code": null, "e": 2454, "s": 2125, "text": "SEO optimizationSPAs provide poor SEO optimization. This is because single-page applications operate on JavaScript and load data at once server. The URL does not change and different pages do not have a unique URL. Hence it is hard for the search engines to index the SPA website as opposed to traditional server-rendered pages." }, { "code": null, "e": 2802, "s": 2454, "text": "Browser historyA SPA does not save the users’ transition of states within the website. A browser saves the previous pages only, not the state transition. Thus when users click the back button, they are not redirected to the previous state of the website. To solve this problem, developers can equip their SPA frameworks with the HTML5 History API." }, { "code": null, "e": 3004, "s": 2802, "text": "Security issuesSingle-page apps are less immune to cross-site scripting (XSS) and since no new pages are loaded, hackers can easily gain access to the website and inject new scripts on the client-side." }, { "code": null, "e": 3243, "s": 3004, "text": "Memory ConsumptionSince the SPA can run for a long time sometimes hours at a time, one needs to make sure the application does not consume more memory than it needs. Else, users with low memory devices may face serious performance issues." }, { "code": null, "e": 3392, "s": 3243, "text": "Disabled JavascriptDevelopers need to chalk out ideas for users to access the information on the website for browsers that have Javascript disabled." }, { "code": null, "e": 3703, "s": 3392, "text": "When to use SPASPAs are good when the volume of data is small and the website that needs a dynamic platform. It is also a good option for mobile applications. But businesses that depend largely on search engine optimizations such as e-commerce applications must avoid single-page applications and opt for MPAs." }, { "code": "<!DOCTYPE html><!--ng-app directive tells AngularJS that myApp is the root element of the application --><html ng-app=\"myApp\"> <head> <!--import the angularjs libraries--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js\"> </script> </head> <body> <!--hg-template indicates the pages that get loaded as per requirement--> <script type=\"text/ng-template\" id=\"first.html\"> <h1>First Page</h1> <h2 style=\"color:green\"> Welcome to GeeksForGeeks </h2> <h3>{{message}}</h3> </script> <script type=\"text/ng-template\" id=\"second.html\"> <h1>Second Page</h1> <h2 style=\"color:green\"> Start Learning With GFG </h2> <h3>{{message}}</h3> </script> <script type=\"text/ng-template\" id=\"third.html\"> <h1>Third Page</h1> <h2 style=\"color:green\"> Know about us </h2> <h3>{{message}}</h3> </script> <!--hyperlinks to load different pages dynamically--> <a href=\"#/\">First</a> <a href=\"#/second\">Second</a> <a href=\"#/third\">Third</a> <!--ng-view includes the rendered template of the current route into the main page--> <div ng-view></div> <script> var app = angular.module('myApp', []); var app = angular.module('myApp', ['ngRoute']); app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl : 'first.html', controller : 'FirstController' }) .when('/second', { templateUrl : 'second.html', controller : 'SecondController' }) .when('/third', { templateUrl : 'third.html', controller : 'ThirdController' }) .otherwise({redirectTo: '/'}); }); <!-- controller is a JS function that maintains application data and behavior using $scope object --> <!--properties and methods can be attached to the $scope object inside a controller function--> app.controller('FirstController', function($scope) { $scope.message = 'Hello from FirstController'; }); app.controller('SecondController', function($scope) { $scope.message = 'Hello from SecondController'; }); app.controller('ThirdController', function($scope) { $scope.message = 'Hello from ThirdController'; }); </script> </body></html>", "e": 6586, "s": 3703, "text": null }, { "code": null, "e": 6594, "s": 6586, "text": "Output:" }, { "code": null, "e": 6609, "s": 6594, "text": "AngularJS-Misc" }, { "code": null, "e": 6616, "s": 6609, "text": "Picked" }, { "code": null, "e": 6626, "s": 6616, "text": "AngularJS" }, { "code": null, "e": 6643, "s": 6626, "text": "Web Technologies" }, { "code": null, "e": 6741, "s": 6643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6765, "s": 6741, "text": "Routing in Angular 9/10" }, { "code": null, "e": 6800, "s": 6765, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 6824, "s": 6800, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 6877, "s": 6824, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 6926, "s": 6877, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 6959, "s": 6926, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7021, "s": 6959, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7082, "s": 7021, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7132, "s": 7082, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Pandas Series.str.isalpha()
23 Aug, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.isalpha() method is used to check if all characters in each string in series are alphabetic(a-z/A-Z). Whitespace or any other character occurrence in the string would return false, but if there is a complete numeric value, then it would return NaN. Syntax: Series.str.isalpha() Return Type: Boolean series, Null values might be included too depending upon caller series. To download the CSV used in code, click here. In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example #1:In this example, the isalpha() method is applied on the College column. Before that, the Null rows are removed using .dropna() method to avoid errors. # importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # removing null values to avoid errorsdata.dropna(inplace = True) # creating bool seriesdata["bool_series"]= data["College"].str.isalpha() # displaydata Output:As shown in the output image, the bool_series can be matched with the College column and it can be clearly seen that if the string contains only alphabets, True is returned. Example #2:In this example, the isalpha() method is applied on Name column twice. First a bool series is created for the original name column, after that the white spaces are removed using str.replace() method and then a new bool_series is created again. # importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # removing null values to avoid errorsdata.dropna(inplace = True) # creating bool series with original columndata["bool_series1"]= data["Name"].str.isalpha() # removing white spacesdata["Name"]= data["Name"].str.replace(" ", "") # creating bool series with new columndata["bool_series2"]= data["Name"].str.isalpha() # displaydata.head(10) Output:As shown in the output image, the Bool series was false for all values until the strings had whitespace. After removing white spaces, the bool series in only false where the string is having special characters. Akanksha_Rai Python pandas-series Python pandas-series-methods Python-pandas Python-pandas-series-str Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 502, "s": 242, "text": "Pandas str.isalpha() method is used to check if all characters in each string in series are alphabetic(a-z/A-Z). Whitespace or any other character occurrence in the string would return false, but if there is a complete numeric value, then it would return NaN." }, { "code": null, "e": 531, "s": 502, "text": "Syntax: Series.str.isalpha()" }, { "code": null, "e": 624, "s": 531, "text": "Return Type: Boolean series, Null values might be included too depending upon caller series." }, { "code": null, "e": 670, "s": 624, "text": "To download the CSV used in code, click here." }, { "code": null, "e": 979, "s": 670, "text": "In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example #1:In this example, the isalpha() method is applied on the College column. Before that, the Null rows are removed using .dropna() method to avoid errors." }, { "code": "# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # removing null values to avoid errorsdata.dropna(inplace = True) # creating bool seriesdata[\"bool_series\"]= data[\"College\"].str.isalpha() # displaydata", "e": 1281, "s": 979, "text": null }, { "code": null, "e": 1717, "s": 1281, "text": "Output:As shown in the output image, the bool_series can be matched with the College column and it can be clearly seen that if the string contains only alphabets, True is returned. Example #2:In this example, the isalpha() method is applied on Name column twice. First a bool series is created for the original name column, after that the white spaces are removed using str.replace() method and then a new bool_series is created again." }, { "code": "# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # removing null values to avoid errorsdata.dropna(inplace = True) # creating bool series with original columndata[\"bool_series1\"]= data[\"Name\"].str.isalpha() # removing white spacesdata[\"Name\"]= data[\"Name\"].str.replace(\" \", \"\") # creating bool series with new columndata[\"bool_series2\"]= data[\"Name\"].str.isalpha() # displaydata.head(10)", "e": 2207, "s": 1717, "text": null }, { "code": null, "e": 2425, "s": 2207, "text": "Output:As shown in the output image, the Bool series was false for all values until the strings had whitespace. After removing white spaces, the bool series in only false where the string is having special characters." }, { "code": null, "e": 2438, "s": 2425, "text": "Akanksha_Rai" }, { "code": null, "e": 2459, "s": 2438, "text": "Python pandas-series" }, { "code": null, "e": 2488, "s": 2459, "text": "Python pandas-series-methods" }, { "code": null, "e": 2502, "s": 2488, "text": "Python-pandas" }, { "code": null, "e": 2527, "s": 2502, "text": "Python-pandas-series-str" }, { "code": null, "e": 2534, "s": 2527, "text": "Python" }, { "code": null, "e": 2632, "s": 2534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2664, "s": 2632, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2691, "s": 2664, "text": "Python Classes and Objects" }, { "code": null, "e": 2712, "s": 2691, "text": "Python OOPs Concepts" }, { "code": null, "e": 2735, "s": 2712, "text": "Introduction To PYTHON" }, { "code": null, "e": 2791, "s": 2735, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2822, "s": 2791, "text": "Python | os.path.join() method" }, { "code": null, "e": 2864, "s": 2822, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2906, "s": 2864, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2945, "s": 2906, "text": "Python | Get unique values from a list" } ]
transform() in C++
The transform function is present in the C++ STL. To use it, we have to include the algorithm header file. This is used to perform an operation on all elements. For an example if we want to perform square of each element of an array, and store it into other, then we can use the transform() function. The transform function works in two modes. These modes are − Unary operation mode Binary operation mode In this mode the function takes only one operator (or function) and convert into output. #include <iostream> #include <algorithm> using namespace std; int square(int x) { //define square function return x*x; } int main(int argc, char **argv) { int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int res[10]; transform(arr, arr+10, res, square); for(int i = 0; i<10; i++) { cout >> res[i] >> "\n"; } } 1 4 9 16 25 36 49 64 81 100 In this mode the it can perform binary operation on the given data. If we want to add elements of two different array, then we have to use binary operator mode. #include <iostream> #include <algorithm> using namespace std; int multiply(int x, int y) { //define multiplication function return x*y; } int main(int argc, char **argv) { int arr1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int arr2[10] = {54, 21, 32, 65, 58, 74, 21, 84, 20, 35}; int res[10]; transform(arr1, arr1+10, arr2, res, multiply); for(int i = 0; i<10; i++) { cout >> res[i] >> "\n"; } } 54 42 96 260 290 444 147 672 180 350
[ { "code": null, "e": 1488, "s": 1187, "text": "The transform function is present in the C++ STL. To use it, we have to include the algorithm header file. This is used to perform an operation on all elements. For an example if we want to perform square of each element of an array, and store it into other, then we can use the transform() function." }, { "code": null, "e": 1549, "s": 1488, "text": "The transform function works in two modes. These modes are −" }, { "code": null, "e": 1570, "s": 1549, "text": "Unary operation mode" }, { "code": null, "e": 1592, "s": 1570, "text": "Binary operation mode" }, { "code": null, "e": 1681, "s": 1592, "text": "In this mode the function takes only one operator (or function) and convert into output." }, { "code": null, "e": 2016, "s": 1681, "text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nint square(int x) {\n //define square function\n return x*x;\n}\nint main(int argc, char **argv) {\n int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n int res[10];\n transform(arr, arr+10, res, square);\n for(int i = 0; i<10; i++) {\n cout >> res[i] >> \"\\n\";\n }\n}" }, { "code": null, "e": 2044, "s": 2016, "text": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100" }, { "code": null, "e": 2205, "s": 2044, "text": "In this mode the it can perform binary operation on the given data. If we want to add elements of two different array, then we have to use binary operator mode." }, { "code": null, "e": 2628, "s": 2205, "text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nint multiply(int x, int y) {\n //define multiplication function\n return x*y;\n}\nint main(int argc, char **argv) {\n int arr1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n int arr2[10] = {54, 21, 32, 65, 58, 74, 21, 84, 20, 35};\n int res[10];\n transform(arr1, arr1+10, arr2, res, multiply);\n for(int i = 0; i<10; i++) {\n cout >> res[i] >> \"\\n\";\n }\n}" }, { "code": null, "e": 2665, "s": 2628, "text": "54\n42\n96\n260\n290\n444\n147\n672\n180\n350" } ]
Python | Pandas Timestamp.isocalendar
14 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.isocalendar() function return a 3-tuple containing ISO year, week number, and weekday for the given Timestamp object. Syntax :Timestamp.isocalendar() Parameters : None Return : Tuple Example #1: Use Timestamp.isocalendar() function to return the date of the given Timestamp object based on ISO calendar. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.isocalendar() function to return the date in ts object based on ISO calendar. # return the date as an ISO calendarts.isocalendar() Output : As we can see in the output, the Timestamp.isocalendar() function has returned a tuple containing the year, week number and the week day for the given Timestamp object. Example #2: Use Timestamp.isocalendar() function to return the date of the given Timestamp object based on ISO calendar. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.isocalendar() function to return the date in ts object based on ISO calendar # return the date as an ISO calendarts.isocalendar() Output : As we can see in the output, the Timestamp.isocalendar() function has returned a tuple containing the year, week number and the week day for the given Timestamp object. Python Pandas-Timestamp Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 377, "s": 242, "text": "Pandas Timestamp.isocalendar() function return a 3-tuple containing ISO year, week number, and weekday for the given Timestamp object." }, { "code": null, "e": 409, "s": 377, "text": "Syntax :Timestamp.isocalendar()" }, { "code": null, "e": 427, "s": 409, "text": "Parameters : None" }, { "code": null, "e": 442, "s": 427, "text": "Return : Tuple" }, { "code": null, "e": 563, "s": 442, "text": "Example #1: Use Timestamp.isocalendar() function to return the date of the given Timestamp object based on ISO calendar." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)", "e": 790, "s": 563, "text": null }, { "code": null, "e": 799, "s": 790, "text": "Output :" }, { "code": null, "e": 907, "s": 799, "text": "Now we will use the Timestamp.isocalendar() function to return the date in ts object based on ISO calendar." }, { "code": "# return the date as an ISO calendarts.isocalendar()", "e": 960, "s": 907, "text": null }, { "code": null, "e": 969, "s": 960, "text": "Output :" }, { "code": null, "e": 1138, "s": 969, "text": "As we can see in the output, the Timestamp.isocalendar() function has returned a tuple containing the year, week number and the week day for the given Timestamp object." }, { "code": null, "e": 1259, "s": 1138, "text": "Example #2: Use Timestamp.isocalendar() function to return the date of the given Timestamp object based on ISO calendar." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)", "e": 1486, "s": 1259, "text": null }, { "code": null, "e": 1495, "s": 1486, "text": "Output :" }, { "code": null, "e": 1602, "s": 1495, "text": "Now we will use the Timestamp.isocalendar() function to return the date in ts object based on ISO calendar" }, { "code": "# return the date as an ISO calendarts.isocalendar()", "e": 1655, "s": 1602, "text": null }, { "code": null, "e": 1664, "s": 1655, "text": "Output :" }, { "code": null, "e": 1833, "s": 1664, "text": "As we can see in the output, the Timestamp.isocalendar() function has returned a tuple containing the year, week number and the week day for the given Timestamp object." }, { "code": null, "e": 1857, "s": 1833, "text": "Python Pandas-Timestamp" }, { "code": null, "e": 1871, "s": 1857, "text": "Python-pandas" }, { "code": null, "e": 1878, "s": 1871, "text": "Python" } ]
Convert timestamp to readable date/time in PHP
01 Aug, 2021 Problem: Convert timestamp to readable date/time in PHPSolution: This can be achieved with the help of date() function, which is an inbuilt function in PHP can be used to format the timestamp given by time() function. This function returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. Example 1: <?phpecho date('m/d/Y H:i:s', 1541843467);?> Output: 11/10/2018 09:51:07 Example 2: <?phpecho date('m/d/Y H:i:s', time());?> Output: Current Time in formatted form Reference: http://php.net/manual/en/function.date.php PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. date-time-program PHP-date-time Picked Technical Scripter 2018 PHP Technical Scripter PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Aug, 2021" }, { "code": null, "e": 430, "s": 54, "text": "Problem: Convert timestamp to readable date/time in PHPSolution: This can be achieved with the help of date() function, which is an inbuilt function in PHP can be used to format the timestamp given by time() function. This function returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given." }, { "code": null, "e": 441, "s": 430, "text": "Example 1:" }, { "code": "<?phpecho date('m/d/Y H:i:s', 1541843467);?>", "e": 486, "s": 441, "text": null }, { "code": null, "e": 494, "s": 486, "text": "Output:" }, { "code": null, "e": 515, "s": 494, "text": "11/10/2018 09:51:07\n" }, { "code": null, "e": 526, "s": 515, "text": "Example 2:" }, { "code": "<?phpecho date('m/d/Y H:i:s', time());?>", "e": 567, "s": 526, "text": null }, { "code": null, "e": 575, "s": 567, "text": "Output:" }, { "code": null, "e": 607, "s": 575, "text": "Current Time in formatted form\n" }, { "code": null, "e": 661, "s": 607, "text": "Reference: http://php.net/manual/en/function.date.php" }, { "code": null, "e": 830, "s": 661, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 848, "s": 830, "text": "date-time-program" }, { "code": null, "e": 862, "s": 848, "text": "PHP-date-time" }, { "code": null, "e": 869, "s": 862, "text": "Picked" }, { "code": null, "e": 893, "s": 869, "text": "Technical Scripter 2018" }, { "code": null, "e": 897, "s": 893, "text": "PHP" }, { "code": null, "e": 916, "s": 897, "text": "Technical Scripter" }, { "code": null, "e": 920, "s": 916, "text": "PHP" } ]
Puzzle | Set 35 (2 Eggs and 100 Floors)
09 Jun, 2022 The following is a description of the instance of this famous puzzle involving 2 eggs and a building with 100 floors. Suppose that we wish to know which stories in a 100-storey building are safe to drop eggs from, and which will cause the eggs to break on landing. What strategy should be used to drop eggs such that a total number of drops in the worst case is minimized and we find the required floor We may make a few assumptions: An egg that survives a fall can be used again. A broken egg must be discarded. The effect of a fall is the same for all eggs. If an egg breaks when dropped, then it would break if dropped from a higher floor. If an egg survives a fall then it would survive a shorter fall. We strongly recommend you to minimize your browser and try this yourself first If only one egg is available and we wish to be sure of obtaining the right result, the experiment can be carried out in only one way. Drop the egg from the first-floor window; if it survives, drop it from the second-floor window. Continue upward until it breaks. In the worst case, this method may require 100 droppings. Suppose 2 eggs are available. What is the least number of egg droppings that are guaranteed to work in all cases? The problem is not actually to find the critical floor, but merely to decide floors from which eggs should be dropped so that the total number of trials is minimized. If we use Binary Search Method to find the floor and we start from the 50’th floor, then we end up doing 50 comparisons in the worst case. The worst-case happens when the required floor is 49’th floor. Optimized Method: The idea is to do optimize the solution using the below equation: Let us make our first attempt on x'th floor. If it breaks, we try remaining (x-1) floors one by one. So in worst case, we make x trials. If it doesn't break, we jump (x-1) floors (Because we have already made one attempt and we don't want to go beyond x attempts. Therefore (x-1) attempts are available), Next floor we try is floor x + (x-1) Similarly, if this drop does not break, next need to jump up to floor x + (x-1) + (x-2), then x + (x-1) + (x-2) + (x-3) and so on. Since the last floor to be tried is 100'th floor, sum of series should be 100 for optimal value of x. x + (x-1) + (x-2) + (x-3) + .... + 1 = 100 x(x+1)/2 = 100 x = 13.651 Therefore, we start trying from 14'th floor. If Egg breaks on 14th floor we one by one try remaining 13 floors, starting from 1st floor. If egg doesn't break we go to 27th floor. If egg breaks on 27'th floor, we try floors form 15 to 26. If egg doesn't break on 27'th floor, we go to 39'th floor. An so on... The optimal number of trials is 14 in the worst case. See below for a programming solution for general k eggs and n floors. https://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/ This article is contributed by Rachit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above tawpcoder797 aashwintripathi muskansaxena361518 mitalibhola94 Egg-Dropping VMWare Puzzles VMWare Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Top 20 Puzzles Commonly Asked During SDE Interviews Puzzle 18 | (Torch and Bridge) Puzzle 8 | (Find the Jar with contaminated pills) Puzzle 16 | (100 Doors) Puzzle 11 | (1000 Coins and 10 Bags) Puzzle 10 | (A Man with Medical Condition and 2 Pills) Puzzle 13 | (100 Prisoners with Red/Black Hats) Container with Most Water Puzzle 19 | (Poison and Rat)
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2022" }, { "code": null, "e": 171, "s": 52, "text": "The following is a description of the instance of this famous puzzle involving 2 eggs and a building with 100 floors. " }, { "code": null, "e": 457, "s": 171, "text": "Suppose that we wish to know which stories in a 100-storey building are safe to drop eggs from, and which will cause the eggs to break on landing. What strategy should be used to drop eggs such that a total number of drops in the worst case is minimized and we find the required floor " }, { "code": null, "e": 489, "s": 457, "text": "We may make a few assumptions: " }, { "code": null, "e": 536, "s": 489, "text": "An egg that survives a fall can be used again." }, { "code": null, "e": 568, "s": 536, "text": "A broken egg must be discarded." }, { "code": null, "e": 615, "s": 568, "text": "The effect of a fall is the same for all eggs." }, { "code": null, "e": 698, "s": 615, "text": "If an egg breaks when dropped, then it would break if dropped from a higher floor." }, { "code": null, "e": 762, "s": 698, "text": "If an egg survives a fall then it would survive a shorter fall." }, { "code": null, "e": 842, "s": 762, "text": "We strongly recommend you to minimize your browser and try this yourself first " }, { "code": null, "e": 1445, "s": 842, "text": "If only one egg is available and we wish to be sure of obtaining the right result, the experiment can be carried out in only one way. Drop the egg from the first-floor window; if it survives, drop it from the second-floor window. Continue upward until it breaks. In the worst case, this method may require 100 droppings. Suppose 2 eggs are available. What is the least number of egg droppings that are guaranteed to work in all cases? The problem is not actually to find the critical floor, but merely to decide floors from which eggs should be dropped so that the total number of trials is minimized. " }, { "code": null, "e": 1648, "s": 1445, "text": "If we use Binary Search Method to find the floor and we start from the 50’th floor, then we end up doing 50 comparisons in the worst case. The worst-case happens when the required floor is 49’th floor. " }, { "code": null, "e": 1733, "s": 1648, "text": "Optimized Method: The idea is to do optimize the solution using the below equation: " }, { "code": null, "e": 2717, "s": 1733, "text": "Let us make our first attempt on x'th floor. \n\nIf it breaks, we try remaining (x-1) floors one by one. \nSo in worst case, we make x trials.\n\nIf it doesn't break, we jump (x-1) floors (Because we have\nalready made one attempt and we don't want to go beyond \nx attempts. Therefore (x-1) attempts are available),\n Next floor we try is floor x + (x-1)\n\nSimilarly, if this drop does not break, next need to jump \nup to floor x + (x-1) + (x-2), then x + (x-1) + (x-2) + (x-3)\nand so on.\n\nSince the last floor to be tried is 100'th floor, sum of\nseries should be 100 for optimal value of x.\n\n x + (x-1) + (x-2) + (x-3) + .... + 1 = 100\n\n x(x+1)/2 = 100\n x = 13.651\n\nTherefore, we start trying from 14'th floor. If Egg breaks on 14th floor\nwe one by one try remaining 13 floors, starting from 1st floor. If egg doesn't break\nwe go to 27th floor.\nIf egg breaks on 27'th floor, we try floors form 15 to 26.\nIf egg doesn't break on 27'th floor, we go to 39'th floor.\n\nAn so on..." }, { "code": null, "e": 2772, "s": 2717, "text": "The optimal number of trials is 14 in the worst case. " }, { "code": null, "e": 2921, "s": 2772, "text": "See below for a programming solution for general k eggs and n floors. https://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/ " }, { "code": null, "e": 3085, "s": 2921, "text": "This article is contributed by Rachit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 3098, "s": 3085, "text": "tawpcoder797" }, { "code": null, "e": 3114, "s": 3098, "text": "aashwintripathi" }, { "code": null, "e": 3133, "s": 3114, "text": "muskansaxena361518" }, { "code": null, "e": 3147, "s": 3133, "text": "mitalibhola94" }, { "code": null, "e": 3160, "s": 3147, "text": "Egg-Dropping" }, { "code": null, "e": 3167, "s": 3160, "text": "VMWare" }, { "code": null, "e": 3175, "s": 3167, "text": "Puzzles" }, { "code": null, "e": 3182, "s": 3175, "text": "VMWare" }, { "code": null, "e": 3190, "s": 3182, "text": "Puzzles" }, { "code": null, "e": 3288, "s": 3190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3320, "s": 3288, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 3372, "s": 3320, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 3403, "s": 3372, "text": "Puzzle 18 | (Torch and Bridge)" }, { "code": null, "e": 3453, "s": 3403, "text": "Puzzle 8 | (Find the Jar with contaminated pills)" }, { "code": null, "e": 3477, "s": 3453, "text": "Puzzle 16 | (100 Doors)" }, { "code": null, "e": 3514, "s": 3477, "text": "Puzzle 11 | (1000 Coins and 10 Bags)" }, { "code": null, "e": 3569, "s": 3514, "text": "Puzzle 10 | (A Man with Medical Condition and 2 Pills)" }, { "code": null, "e": 3617, "s": 3569, "text": "Puzzle 13 | (100 Prisoners with Red/Black Hats)" }, { "code": null, "e": 3643, "s": 3617, "text": "Container with Most Water" } ]
Plotly - 3D Scatter and Surface Plot
This chapter will give information about the three-dimensional (3D) Scatter Plot and 3D Surface Plot and how to make them with the help of Plotly. A three-dimensional (3D) scatter plot is like a scatter plot, but with three variables - x, y, and z or f(x, y) are real numbers. The graph can be represented as dots in a three-dimensional Cartesian coordinate system. It is typically drawn on a two-dimensional page or screen using perspective methods (isometric or perspective), so that one of the dimensions appears to be coming out of the page. 3D scatter plots are used to plot data points on three axes in an attempt to show the relationship between three variables. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X, Y, and Z axes. A fourth variable can be set to correspond to the color or size of the markers, thus, adding yet another dimension to the plot. The relationship between different variables is called correlation. A Scatter3D trace is a graph object returned by go.Scatter3D() function. Mandatory arguments to this function are x, y and z each of them is a list or array object. For example − import plotly.graph_objs as go import numpy as np z = np.linspace(0, 10, 50) x = np.cos(z) y = np.sin(z) trace = go.Scatter3d( x = x, y = y, z = z,mode = 'markers', marker = dict( size = 12, color = z, # set color to an array/list of desired values colorscale = 'Viridis' ) ) layout = go.Layout(title = '3D Scatter plot') fig = go.Figure(data = [trace], layout = layout) iplot(fig) The output of the code is given below − Surface plots are diagrams of three-dimensional data. In a surface plot, each point is defined by 3 points: its latitude, longitude, and altitude (X, Y and Z). Rather than showing the individual data points, surface plots show a functional relationship between a designated dependent variable (Y), and two independent variables (X and Z). This plot is a companion plot to the contour plot. Here, is a Python script to render simple surface plot where y array is transpose of x and z is calculated as cos(x2+y2) import numpy as np x = np.outer(np.linspace(-2, 2, 30), np.ones(30)) y = x.copy().T # transpose z = np.cos(x ** 2 + y ** 2) trace = go.Surface(x = x, y = y, z =z ) data = [trace] layout = go.Layout(title = '3D Surface plot') fig = go.Figure(data = data) iplot(fig) Below mentioned is the output of the code which is explained above −
[ { "code": null, "e": 2641, "s": 2494, "text": "This chapter will give information about the three-dimensional (3D) Scatter Plot and 3D Surface Plot and how to make them with the help of Plotly." }, { "code": null, "e": 3040, "s": 2641, "text": "A three-dimensional (3D) scatter plot is like a scatter plot, but with three variables - x, y, and z or f(x, y) are real numbers. The graph can be represented as dots in a three-dimensional Cartesian coordinate system. It is typically drawn on a two-dimensional page or screen using perspective methods (isometric or perspective), so that one of the dimensions appears to be coming out of the page." }, { "code": null, "e": 3299, "s": 3040, "text": "3D scatter plots are used to plot data points on three axes in an attempt to show the relationship between three variables. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X, Y, and Z axes." }, { "code": null, "e": 3495, "s": 3299, "text": "A fourth variable can be set to correspond to the color or size of the markers, thus, adding yet another dimension to the plot. The relationship between different variables is called correlation." }, { "code": null, "e": 3660, "s": 3495, "text": "A Scatter3D trace is a graph object returned by go.Scatter3D() function. Mandatory arguments to this function are x, y and z each of them is a list or array object." }, { "code": null, "e": 3674, "s": 3660, "text": "For example −" }, { "code": null, "e": 4086, "s": 3674, "text": "import plotly.graph_objs as go\nimport numpy as np\nz = np.linspace(0, 10, 50)\nx = np.cos(z)\ny = np.sin(z)\ntrace = go.Scatter3d(\n x = x, y = y, z = z,mode = 'markers', marker = dict(\n size = 12,\n color = z, # set color to an array/list of desired values\n colorscale = 'Viridis'\n )\n )\nlayout = go.Layout(title = '3D Scatter plot')\nfig = go.Figure(data = [trace], layout = layout)\niplot(fig)" }, { "code": null, "e": 4126, "s": 4086, "text": "The output of the code is given below −" }, { "code": null, "e": 4516, "s": 4126, "text": "Surface plots are diagrams of three-dimensional data. In a surface plot, each point is defined by 3 points: its latitude, longitude, and altitude (X, Y and Z). Rather than showing the individual data points, surface plots show a functional relationship between a designated dependent variable (Y), and two independent variables (X and Z). This plot is a companion plot to the contour plot." }, { "code": null, "e": 4637, "s": 4516, "text": "Here, is a Python script to render simple surface plot where y array is transpose of x and z is calculated as cos(x2+y2)" }, { "code": null, "e": 4902, "s": 4637, "text": "import numpy as np\nx = np.outer(np.linspace(-2, 2, 30), np.ones(30))\ny = x.copy().T # transpose\nz = np.cos(x ** 2 + y ** 2)\ntrace = go.Surface(x = x, y = y, z =z )\ndata = [trace]\nlayout = go.Layout(title = '3D Surface plot')\nfig = go.Figure(data = data)\niplot(fig)" } ]
Java Swing | JColorChooser Class
26 Jul, 2021 JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color. This class provides three levels of API: A static convenience method that shows a modal color-chooser dialog and returns the color selected by the user.A static convenience method for creating a color-chooser dialog where ActionListeners can be specified to be invoked when the user presses one of the dialog buttons.The ability to create instances of JColorChooser panes directly (within any container). PropertyChange listeners can be added to detect when the current “color” property changes. A static convenience method that shows a modal color-chooser dialog and returns the color selected by the user. A static convenience method for creating a color-chooser dialog where ActionListeners can be specified to be invoked when the user presses one of the dialog buttons. The ability to create instances of JColorChooser panes directly (within any container). PropertyChange listeners can be added to detect when the current “color” property changes. Constructors of the class: JColorChooser(): Creates a color chooser pane with an initial color of white.JColorChooser(Color initialColor): Creates a color chooser pane with the specified initial color.JColorChooser(ColorSelectionModel model): Creates a color chooser pane with the specified ColorSelectionModel. JColorChooser(): Creates a color chooser pane with an initial color of white. JColorChooser(Color initialColor): Creates a color chooser pane with the specified initial color. JColorChooser(ColorSelectionModel model): Creates a color chooser pane with the specified ColorSelectionModel. Commonly Used Methods: Creating a Custom Chooser Panel: The default color chooser provides five chooser panels: Swatches: For choosing a color from a collection of swatches.HSV: For choosing a color using the Hue-Saturation-Value color representation. Prior to JDK 7, It was known as HSB, for Hue-Saturation-Brightness.HSL: For choosing a color using the Hue-Saturation-Lightness color representation.RGB: For choosing a color using the Red-Green-Blue color model.CMYK: For choosing a color using the process color or four color model. Swatches: For choosing a color from a collection of swatches. HSV: For choosing a color using the Hue-Saturation-Value color representation. Prior to JDK 7, It was known as HSB, for Hue-Saturation-Brightness. HSL: For choosing a color using the Hue-Saturation-Lightness color representation. RGB: For choosing a color using the Red-Green-Blue color model. CMYK: For choosing a color using the process color or four color model. Below programs illustrate the use of JColorChooser class: 1. Java program to implement JColorChooser class using ChangeListener: In this program, we first create a label at the top of the window where some text is shown in which we will apply color changes. Set the foreground and background color. Set the size and type of the font. Create a Panel and set its layout. Now set up the color chooser for setting text color. Using stateChanged() method, event is generated for change in color of the text by using getColor() method. Now create the GUI, create a setup window. Set the default close operation of the window. Create and set up the content Pane and add content to the frame and display the window. Java // Java program to implement JColorChooser// class using ChangeListenerimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.colorchooser.*; public class ColorChooserDemo extends JPanel implements ChangeListener { protected JColorChooser Jcc; protected JLabel label; public ColorChooserDemo() { super(new BorderLayout()); // Set up the Label at the top of the window label = new JLabel("Welcome to GeeksforGeeks", JLabel.CENTER); // set the foreground color of the text label.setForeground(Color.green); // set background color of the field label.setBackground(Color.WHITE); label.setOpaque(true); // set font type and size of the text label.setFont(new Font("SansSerif", Font.BOLD, 30)); // set size of the label label.setPreferredSize(new Dimension(100, 65)); // create a Panel and set its layout JPanel bannerPanel = new JPanel(new BorderLayout()); bannerPanel.add(label, BorderLayout.CENTER); bannerPanel.setBorder(BorderFactory.createTitledBorder("Label")); // Set up color chooser for setting text color Jcc = new JColorChooser(label.getForeground()); Jcc.getSelectionModel().addChangeListener(this); Jcc.setBorder(BorderFactory.createTitledBorder( "Choose Text Color")); add(bannerPanel, BorderLayout.CENTER); add(Jcc, BorderLayout.PAGE_END); } public void stateChanged(ChangeEvent e) { Color newColor = Jcc.getColor(); label.setForeground(newColor); } // Create the GUI and show it. For thread safety, // this method should be invoked from the // event-dispatching thread. private static void createAndShowGUI() { // Create and set up the window. JFrame frame = new JFrame("ColorChooserDemo"); // set default close operation of the window. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create and set up the content pane. JComponent newContentPane = new ColorChooserDemo(); // content panes must be opaque newContentPane.setOpaque(true); // add content pane to the frame frame.setContentPane(newContentPane); // Display the window. frame.pack(); frame.setVisible(true); } // Main Method public static void main(String[] args) { // Schedule a job for the event-dispatching thread: // creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }} Output: 2. Java program to implement JColorChooser class using ActionListener: Create a button and a container and set the Layout of the container. Add ActionListener() to the button and add a button to the container. ActionListerner() has one method actionPerformed() which is implemented as soon as the button is clicked. Choose the color and set the background color of the container. Java // Java program to implement JColorChooser// class using ActionListenerimport java.awt.event.*;import java.awt.*;import javax.swing.*; public class ColorChooserExample extends JFrame implements ActionListener { // create a button JButton b = new JButton("color"); Container c = getContentPane(); // Constructor ColorChooserExample() { // set Layout c.setLayout(new FlowLayout()); // add Listener b.addActionListener(this); // add button to the Container c.add(b); } public void actionPerformed(ActionEvent e) { Color initialcolor = Color.RED; // color chooser Dialog Box Color color = JColorChooser.showDialog(this, "Select a color", initialcolor); // set Background color of the Container c.setBackground(color); } // Main Method public static void main(String[] args) { ColorChooserExample ch = new ColorChooserExample(); ch.setSize(400, 400); ch.setVisible(true); ch.setDefaultCloseOperation(EXIT_ON_CLOSE); }} Output: Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/JColorChooser.html kalrap615 java-swing Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2021" }, { "code": null, "e": 170, "s": 28, "text": "JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color. This class provides three levels of API:" }, { "code": null, "e": 625, "s": 170, "text": "A static convenience method that shows a modal color-chooser dialog and returns the color selected by the user.A static convenience method for creating a color-chooser dialog where ActionListeners can be specified to be invoked when the user presses one of the dialog buttons.The ability to create instances of JColorChooser panes directly (within any container). PropertyChange listeners can be added to detect when the current “color” property changes." }, { "code": null, "e": 737, "s": 625, "text": "A static convenience method that shows a modal color-chooser dialog and returns the color selected by the user." }, { "code": null, "e": 903, "s": 737, "text": "A static convenience method for creating a color-chooser dialog where ActionListeners can be specified to be invoked when the user presses one of the dialog buttons." }, { "code": null, "e": 1082, "s": 903, "text": "The ability to create instances of JColorChooser panes directly (within any container). PropertyChange listeners can be added to detect when the current “color” property changes." }, { "code": null, "e": 1111, "s": 1082, "text": "Constructors of the class: " }, { "code": null, "e": 1396, "s": 1111, "text": "JColorChooser(): Creates a color chooser pane with an initial color of white.JColorChooser(Color initialColor): Creates a color chooser pane with the specified initial color.JColorChooser(ColorSelectionModel model): Creates a color chooser pane with the specified ColorSelectionModel." }, { "code": null, "e": 1474, "s": 1396, "text": "JColorChooser(): Creates a color chooser pane with an initial color of white." }, { "code": null, "e": 1572, "s": 1474, "text": "JColorChooser(Color initialColor): Creates a color chooser pane with the specified initial color." }, { "code": null, "e": 1683, "s": 1572, "text": "JColorChooser(ColorSelectionModel model): Creates a color chooser pane with the specified ColorSelectionModel." }, { "code": null, "e": 1707, "s": 1683, "text": "Commonly Used Methods: " }, { "code": null, "e": 1797, "s": 1707, "text": "Creating a Custom Chooser Panel: The default color chooser provides five chooser panels: " }, { "code": null, "e": 2221, "s": 1797, "text": "Swatches: For choosing a color from a collection of swatches.HSV: For choosing a color using the Hue-Saturation-Value color representation. Prior to JDK 7, It was known as HSB, for Hue-Saturation-Brightness.HSL: For choosing a color using the Hue-Saturation-Lightness color representation.RGB: For choosing a color using the Red-Green-Blue color model.CMYK: For choosing a color using the process color or four color model." }, { "code": null, "e": 2283, "s": 2221, "text": "Swatches: For choosing a color from a collection of swatches." }, { "code": null, "e": 2430, "s": 2283, "text": "HSV: For choosing a color using the Hue-Saturation-Value color representation. Prior to JDK 7, It was known as HSB, for Hue-Saturation-Brightness." }, { "code": null, "e": 2513, "s": 2430, "text": "HSL: For choosing a color using the Hue-Saturation-Lightness color representation." }, { "code": null, "e": 2577, "s": 2513, "text": "RGB: For choosing a color using the Red-Green-Blue color model." }, { "code": null, "e": 2649, "s": 2577, "text": "CMYK: For choosing a color using the process color or four color model." }, { "code": null, "e": 2708, "s": 2649, "text": "Below programs illustrate the use of JColorChooser class: " }, { "code": null, "e": 3358, "s": 2708, "text": "1. Java program to implement JColorChooser class using ChangeListener: In this program, we first create a label at the top of the window where some text is shown in which we will apply color changes. Set the foreground and background color. Set the size and type of the font. Create a Panel and set its layout. Now set up the color chooser for setting text color. Using stateChanged() method, event is generated for change in color of the text by using getColor() method. Now create the GUI, create a setup window. Set the default close operation of the window. Create and set up the content Pane and add content to the frame and display the window." }, { "code": null, "e": 3363, "s": 3358, "text": "Java" }, { "code": "// Java program to implement JColorChooser// class using ChangeListenerimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.colorchooser.*; public class ColorChooserDemo extends JPanel implements ChangeListener { protected JColorChooser Jcc; protected JLabel label; public ColorChooserDemo() { super(new BorderLayout()); // Set up the Label at the top of the window label = new JLabel(\"Welcome to GeeksforGeeks\", JLabel.CENTER); // set the foreground color of the text label.setForeground(Color.green); // set background color of the field label.setBackground(Color.WHITE); label.setOpaque(true); // set font type and size of the text label.setFont(new Font(\"SansSerif\", Font.BOLD, 30)); // set size of the label label.setPreferredSize(new Dimension(100, 65)); // create a Panel and set its layout JPanel bannerPanel = new JPanel(new BorderLayout()); bannerPanel.add(label, BorderLayout.CENTER); bannerPanel.setBorder(BorderFactory.createTitledBorder(\"Label\")); // Set up color chooser for setting text color Jcc = new JColorChooser(label.getForeground()); Jcc.getSelectionModel().addChangeListener(this); Jcc.setBorder(BorderFactory.createTitledBorder( \"Choose Text Color\")); add(bannerPanel, BorderLayout.CENTER); add(Jcc, BorderLayout.PAGE_END); } public void stateChanged(ChangeEvent e) { Color newColor = Jcc.getColor(); label.setForeground(newColor); } // Create the GUI and show it. For thread safety, // this method should be invoked from the // event-dispatching thread. private static void createAndShowGUI() { // Create and set up the window. JFrame frame = new JFrame(\"ColorChooserDemo\"); // set default close operation of the window. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create and set up the content pane. JComponent newContentPane = new ColorChooserDemo(); // content panes must be opaque newContentPane.setOpaque(true); // add content pane to the frame frame.setContentPane(newContentPane); // Display the window. frame.pack(); frame.setVisible(true); } // Main Method public static void main(String[] args) { // Schedule a job for the event-dispatching thread: // creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }}", "e": 6135, "s": 3363, "text": null }, { "code": null, "e": 6143, "s": 6135, "text": "Output:" }, { "code": null, "e": 6523, "s": 6143, "text": "2. Java program to implement JColorChooser class using ActionListener: Create a button and a container and set the Layout of the container. Add ActionListener() to the button and add a button to the container. ActionListerner() has one method actionPerformed() which is implemented as soon as the button is clicked. Choose the color and set the background color of the container." }, { "code": null, "e": 6528, "s": 6523, "text": "Java" }, { "code": "// Java program to implement JColorChooser// class using ActionListenerimport java.awt.event.*;import java.awt.*;import javax.swing.*; public class ColorChooserExample extends JFrame implements ActionListener { // create a button JButton b = new JButton(\"color\"); Container c = getContentPane(); // Constructor ColorChooserExample() { // set Layout c.setLayout(new FlowLayout()); // add Listener b.addActionListener(this); // add button to the Container c.add(b); } public void actionPerformed(ActionEvent e) { Color initialcolor = Color.RED; // color chooser Dialog Box Color color = JColorChooser.showDialog(this, \"Select a color\", initialcolor); // set Background color of the Container c.setBackground(color); } // Main Method public static void main(String[] args) { ColorChooserExample ch = new ColorChooserExample(); ch.setSize(400, 400); ch.setVisible(true); ch.setDefaultCloseOperation(EXIT_ON_CLOSE); }}", "e": 7625, "s": 6528, "text": null }, { "code": null, "e": 7633, "s": 7625, "text": "Output:" }, { "code": null, "e": 7806, "s": 7633, "text": "Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/JColorChooser.html " }, { "code": null, "e": 7816, "s": 7806, "text": "kalrap615" }, { "code": null, "e": 7827, "s": 7816, "text": "java-swing" }, { "code": null, "e": 7832, "s": 7827, "text": "Java" }, { "code": null, "e": 7837, "s": 7832, "text": "Java" }, { "code": null, "e": 7935, "s": 7837, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7950, "s": 7935, "text": "Stream In Java" }, { "code": null, "e": 7971, "s": 7950, "text": "Introduction to Java" }, { "code": null, "e": 7992, "s": 7971, "text": "Constructors in Java" }, { "code": null, "e": 8011, "s": 7992, "text": "Exceptions in Java" }, { "code": null, "e": 8028, "s": 8011, "text": "Generics in Java" }, { "code": null, "e": 8058, "s": 8028, "text": "Functional Interfaces in Java" }, { "code": null, "e": 8084, "s": 8058, "text": "Java Programming Examples" }, { "code": null, "e": 8100, "s": 8084, "text": "Strings in Java" }, { "code": null, "e": 8137, "s": 8100, "text": "Differences between JDK, JRE and JVM" } ]
ScapeGoat Tree | Set 1 (Introduction and Insertion)
07 Jul, 2022 A ScapeGoat tree is a self-balancing Binary Search Tree like AVL Tree, Red-Black Tree, Splay Tree, ..etc. Search time is O(Log n) in worst case. Time taken by deletion and insertion is amortized O(Log n) The balancing idea is to make sure that nodes are α size balanced. Α size balanced means sizes of left and right subtrees are at most α * (Size of node). The idea is based on the fact that if a node is Α weight balanced, then it is also height balanced: height <= log1/&aplpha;(size) + 1 Unlike other self-balancing BSTs, ScapeGoat tree doesn’t require extra space per node. For example, Red Black Tree nodes are required to have color. In below implementation of ScapeGoat Tree, we only have left, right and parent pointers in Node class. Use of parent is done for simplicity of implementation and can be avoided. Insertion (Assuming α = 2/3): To insert value x in a Scapegoat Tree: Create a new node u and insert x using the BST insert algorithm. If the depth of u is greater than log3/2n where n is number of nodes in tree then we need to make tree balanced. To make balanced, we use below step to find a scapegoat.Walk up from u until we reach a node w with size(w) > (2/3)*size(w.parent). This node is scapegoatRebuild the subtree rooted at w.parent. Walk up from u until we reach a node w with size(w) > (2/3)*size(w.parent). This node is scapegoat Rebuild the subtree rooted at w.parent. What does rebuilding the subtree mean? In rebuilding, we simply convert the subtree to the most possible balanced BST. We first store inorder traversal of BST in an array, then we build a new BST from array by recursively dividing it into two halves. 60 50 / / \ 40 42 58 \ Rebuild / \ / \ 50 ---------> 40 47 55 60 \ 55 / \ 47 58 / 42 Below is C++ implementation of insert operation on Scapegoat Tree. C++ // C++ program to implement insertion in// ScapeGoat Tree#include<bits/stdc++.h>using namespace std; // Utility function to get value of log32(n)static int const log32(int n){ double const log23 = 2.4663034623764317; return (int)ceil(log23 * log(n));} // A ScapeGoat Tree nodeclass Node{public: Node *left, *right, *parent; float value; Node() { value = 0; left = right = parent = NULL; } Node (float v) { value = v; left = right = parent = NULL; }}; // This functions stores inorder traversal// of tree rooted with ptr in an array arr[]int storeInArray(Node *ptr, Node *arr[], int i){ if (ptr == NULL) return i; i = storeInArray(ptr->left, arr, i); arr[i++] = ptr; return storeInArray(ptr->right, arr, i);} // Class to represent a ScapeGoat Treeclass SGTree{private: Node *root; int n; // Number of nodes in Treepublic: void preorder(Node *); int size(Node *); bool insert(float x); void rebuildTree(Node *u); SGTree() { root = NULL; n = 0; } void preorder() { preorder(root); } // Function to built tree with balanced nodes Node *buildBalancedFromArray(Node **a, int i, int n); // Height at which element is to be added int BSTInsertAndFindDepth(Node *u);}; // Preorder traversal of the treevoid SGTree::preorder(Node *node){ if (node != NULL) { cout << node->value << " "; preorder(node -> left); preorder(node -> right); }} // To count number of nodes in the treeint SGTree::size(Node *node){ if (node == NULL) return 0; return 1 + size(node->left) + size(node->right);} // To insert new element in the treebool SGTree::insert(float x){ // Create a new node Node *node = new Node(x); // Perform BST insertion and find depth of // the inserted node. int h = BSTInsertAndFindDepth(node); // If tree becomes unbalanced if (h > log32(n)) { // Find Scapegoat Node *p = node->parent; while (3*size(p) <= 2*size(p->parent)) p = p->parent; // Rebuild tree rooted under scapegoat rebuildTree(p->parent); } return h >= 0;} // Function to rebuilt tree from new node. This// function basically uses storeInArray() to// first store inorder traversal of BST rooted// with u in an array.// Then it converts array to the most possible// balanced BST using buildBalancedFromArray()void SGTree::rebuildTree(Node *u){ int n = size(u); Node *p = u->parent; Node **a = new Node* [n]; storeInArray(u, a, 0); if (p == NULL) { root = buildBalancedFromArray(a, 0, n); root->parent = NULL; } else if (p->right == u) { p->right = buildBalancedFromArray(a, 0, n); p->right->parent = p; } else { p->left = buildBalancedFromArray(a, 0, n); p->left->parent = p; }} // Function to built tree with balanced nodesNode * SGTree::buildBalancedFromArray(Node **a, int i, int n){ if (n== 0) return NULL; int m = n / 2; // Now a[m] becomes the root of the new // subtree a[0],.....,a[m-1] a[i+m]->left = buildBalancedFromArray(a, i, m); // elements a[0],...a[m-1] gets stored // in the left subtree if (a[i+m]->left != NULL) a[i+m]->left->parent = a[i+m]; // elements a[m+1],....a[n-1] gets stored // in the right subtree a[i+m]->right = buildBalancedFromArray(a, i+m+1, n-m-1); if (a[i+m]->right != NULL) a[i+m]->right->parent = a[i+m]; return a[i+m];} // Performs standard BST insert and returns// depth of the inserted node.int SGTree::BSTInsertAndFindDepth(Node *u){ // If tree is empty Node *w = root; if (w == NULL) { root = u; n++; return 0; } // While the node is not inserted // or a node with same key exists. bool done = false; int d = 0; do { if (u->value < w->value) { if (w->left == NULL) { w->left = u; u->parent = w; done = true; } else w = w->left; } else if (u->value > w->value) { if (w->right == NULL) { w->right = u; u->parent = w; done = true; } else w = w->right; } else return -1; d++; } while (!done); n++; return d;} // Driver codeint main(){ SGTree sgt; sgt.insert(7); sgt.insert(6); sgt.insert(3); sgt.insert(1); sgt.insert(0); sgt.insert(8); sgt.insert(9); sgt.insert(4); sgt.insert(5); sgt.insert(2); sgt.insert(3.5); printf("Preorder traversal of the" " constructed ScapeGoat tree is \n"); sgt.preorder(); return 0;} Preorder traversal of the constructed ScapeGoat tree is 7 6 3 1 0 2 4 3.5 5 8 9 Example to illustrate insertion: A scapegoat tree with 10 nodes and height 5. 7 / \ 6 8 / \ 5 9 / 2 / \ 1 4 / / 0 3 Let’s insert 3.5 in the below scapegoat tree. Initially d = 5 < log3/2n where n = 10; Since, d > log3/2n i.e., 6 > log3/2n, so we have to find the scapegoat in order to solve the problem of exceeding height. Now we find a ScapeGoat. We start with newly added node 3.5 and check whether size(3.5)/size(3) >2/3. Since, size(3.5) = 1 and size(3) = 2, so size(3.5)/size(3) = 1⁄2 which is less than 2/3. So, this is not the scapegoat and we move up . Since 3 is not the scapegoat, we move and check the same condition for node 4. Since size(3) = 2 and size(4) = 3, so size(3)/size(4) = 2/3 which is not greater than 2/3. So, this is not the scapegoat and we move up . Since 3 is not the scapegoat, we move and check the same condition for node 4. Since, size(3) = 2 and size(4) = 3, so size(3)/size(4) = 2/3 which is not greater than 2/3. So, this is not the scapegoat and we move up . Now, size(4)/size(2) = 3/6. Since, size(4)= 3 and size(2) = 6 but 3/6 is still less than 2/3, which does not fulfill the condition of scapegoat so we again move up. Now, size(2)/size(5) = 6/7. Since, size(2) = 6 and size(5) = 7. 6/7 >2/3 which fulfills the condition of scapegoat, so we stop here and hence node 5 is a scapegoat Finally, after finding the scapegoat, rebuilding will be taken at the subtree rooted at scapegoat i.e., at 5. Final tree: Comparison with other self-balancing BSTs Red-Black and AVL : Time complexity of search, insert and delete is O(Log n) Splay Tree : Worst case time complexities of search, insert and delete is O(n). But amortized time complexity of these operations is O(Log n). ScapeGoat Tree: Like Splay Tree, it is easy to implement and has worst case time complexity of search as O(Log n). Worst case and amortized time complexities of insert and delete are same as Splay Tree for Scapegoat tree. This article is contributed by Rahul Aggarwal and Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Self-Balancing-BST Advanced Data Structure Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Trie | (Insert and Search) LRU Cache Implementation Introduction of B-Tree Agents in Artificial Intelligence Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 158, "s": 52, "text": "A ScapeGoat tree is a self-balancing Binary Search Tree like AVL Tree, Red-Black Tree, Splay Tree, ..etc." }, { "code": null, "e": 256, "s": 158, "text": "Search time is O(Log n) in worst case. Time taken by deletion and insertion is amortized O(Log n)" }, { "code": null, "e": 544, "s": 256, "text": "The balancing idea is to make sure that nodes are α size balanced. Α size balanced means sizes of left and right subtrees are at most α * (Size of node). The idea is based on the fact that if a node is Α weight balanced, then it is also height balanced: height <= log1/&aplpha;(size) + 1" }, { "code": null, "e": 871, "s": 544, "text": "Unlike other self-balancing BSTs, ScapeGoat tree doesn’t require extra space per node. For example, Red Black Tree nodes are required to have color. In below implementation of ScapeGoat Tree, we only have left, right and parent pointers in Node class. Use of parent is done for simplicity of implementation and can be avoided." }, { "code": null, "e": 940, "s": 871, "text": "Insertion (Assuming α = 2/3): To insert value x in a Scapegoat Tree:" }, { "code": null, "e": 1005, "s": 940, "text": "Create a new node u and insert x using the BST insert algorithm." }, { "code": null, "e": 1312, "s": 1005, "text": "If the depth of u is greater than log3/2n where n is number of nodes in tree then we need to make tree balanced. To make balanced, we use below step to find a scapegoat.Walk up from u until we reach a node w with size(w) > (2/3)*size(w.parent). This node is scapegoatRebuild the subtree rooted at w.parent." }, { "code": null, "e": 1411, "s": 1312, "text": "Walk up from u until we reach a node w with size(w) > (2/3)*size(w.parent). This node is scapegoat" }, { "code": null, "e": 1451, "s": 1411, "text": "Rebuild the subtree rooted at w.parent." }, { "code": null, "e": 1702, "s": 1451, "text": "What does rebuilding the subtree mean? In rebuilding, we simply convert the subtree to the most possible balanced BST. We first store inorder traversal of BST in an array, then we build a new BST from array by recursively dividing it into two halves." }, { "code": null, "e": 2014, "s": 1702, "text": " 60 50\n / / \\\n 40 42 58\n \\ Rebuild / \\ / \\\n 50 ---------> 40 47 55 60\n \\\n 55\n / \\\n 47 58\n /\n 42 " }, { "code": null, "e": 2082, "s": 2014, "text": "Below is C++ implementation of insert operation on Scapegoat Tree. " }, { "code": null, "e": 2086, "s": 2082, "text": "C++" }, { "code": "// C++ program to implement insertion in// ScapeGoat Tree#include<bits/stdc++.h>using namespace std; // Utility function to get value of log32(n)static int const log32(int n){ double const log23 = 2.4663034623764317; return (int)ceil(log23 * log(n));} // A ScapeGoat Tree nodeclass Node{public: Node *left, *right, *parent; float value; Node() { value = 0; left = right = parent = NULL; } Node (float v) { value = v; left = right = parent = NULL; }}; // This functions stores inorder traversal// of tree rooted with ptr in an array arr[]int storeInArray(Node *ptr, Node *arr[], int i){ if (ptr == NULL) return i; i = storeInArray(ptr->left, arr, i); arr[i++] = ptr; return storeInArray(ptr->right, arr, i);} // Class to represent a ScapeGoat Treeclass SGTree{private: Node *root; int n; // Number of nodes in Treepublic: void preorder(Node *); int size(Node *); bool insert(float x); void rebuildTree(Node *u); SGTree() { root = NULL; n = 0; } void preorder() { preorder(root); } // Function to built tree with balanced nodes Node *buildBalancedFromArray(Node **a, int i, int n); // Height at which element is to be added int BSTInsertAndFindDepth(Node *u);}; // Preorder traversal of the treevoid SGTree::preorder(Node *node){ if (node != NULL) { cout << node->value << \" \"; preorder(node -> left); preorder(node -> right); }} // To count number of nodes in the treeint SGTree::size(Node *node){ if (node == NULL) return 0; return 1 + size(node->left) + size(node->right);} // To insert new element in the treebool SGTree::insert(float x){ // Create a new node Node *node = new Node(x); // Perform BST insertion and find depth of // the inserted node. int h = BSTInsertAndFindDepth(node); // If tree becomes unbalanced if (h > log32(n)) { // Find Scapegoat Node *p = node->parent; while (3*size(p) <= 2*size(p->parent)) p = p->parent; // Rebuild tree rooted under scapegoat rebuildTree(p->parent); } return h >= 0;} // Function to rebuilt tree from new node. This// function basically uses storeInArray() to// first store inorder traversal of BST rooted// with u in an array.// Then it converts array to the most possible// balanced BST using buildBalancedFromArray()void SGTree::rebuildTree(Node *u){ int n = size(u); Node *p = u->parent; Node **a = new Node* [n]; storeInArray(u, a, 0); if (p == NULL) { root = buildBalancedFromArray(a, 0, n); root->parent = NULL; } else if (p->right == u) { p->right = buildBalancedFromArray(a, 0, n); p->right->parent = p; } else { p->left = buildBalancedFromArray(a, 0, n); p->left->parent = p; }} // Function to built tree with balanced nodesNode * SGTree::buildBalancedFromArray(Node **a, int i, int n){ if (n== 0) return NULL; int m = n / 2; // Now a[m] becomes the root of the new // subtree a[0],.....,a[m-1] a[i+m]->left = buildBalancedFromArray(a, i, m); // elements a[0],...a[m-1] gets stored // in the left subtree if (a[i+m]->left != NULL) a[i+m]->left->parent = a[i+m]; // elements a[m+1],....a[n-1] gets stored // in the right subtree a[i+m]->right = buildBalancedFromArray(a, i+m+1, n-m-1); if (a[i+m]->right != NULL) a[i+m]->right->parent = a[i+m]; return a[i+m];} // Performs standard BST insert and returns// depth of the inserted node.int SGTree::BSTInsertAndFindDepth(Node *u){ // If tree is empty Node *w = root; if (w == NULL) { root = u; n++; return 0; } // While the node is not inserted // or a node with same key exists. bool done = false; int d = 0; do { if (u->value < w->value) { if (w->left == NULL) { w->left = u; u->parent = w; done = true; } else w = w->left; } else if (u->value > w->value) { if (w->right == NULL) { w->right = u; u->parent = w; done = true; } else w = w->right; } else return -1; d++; } while (!done); n++; return d;} // Driver codeint main(){ SGTree sgt; sgt.insert(7); sgt.insert(6); sgt.insert(3); sgt.insert(1); sgt.insert(0); sgt.insert(8); sgt.insert(9); sgt.insert(4); sgt.insert(5); sgt.insert(2); sgt.insert(3.5); printf(\"Preorder traversal of the\" \" constructed ScapeGoat tree is \\n\"); sgt.preorder(); return 0;}", "e": 6440, "s": 2086, "text": null }, { "code": null, "e": 6522, "s": 6440, "text": "Preorder traversal of the constructed ScapeGoat tree is \n7 6 3 1 0 2 4 3.5 5 8 9 " }, { "code": null, "e": 6555, "s": 6522, "text": "Example to illustrate insertion:" }, { "code": null, "e": 6600, "s": 6555, "text": "A scapegoat tree with 10 nodes and height 5." }, { "code": null, "e": 6809, "s": 6600, "text": " \n 7\n / \\\n 6 8\n / \\\n 5 9\n /\n 2\n / \\\n 1 4\n / / \n 0 3 \n\nLet’s insert 3.5 in the below scapegoat tree." }, { "code": null, "e": 6849, "s": 6809, "text": "Initially d = 5 < log3/2n where n = 10;" }, { "code": null, "e": 6973, "s": 6851, "text": "Since, d > log3/2n i.e., 6 > log3/2n, so we have to find the scapegoat in order to solve the problem of exceeding height." }, { "code": null, "e": 7075, "s": 6973, "text": "Now we find a ScapeGoat. We start with newly added node 3.5 and check whether size(3.5)/size(3) >2/3." }, { "code": null, "e": 7211, "s": 7075, "text": "Since, size(3.5) = 1 and size(3) = 2, so size(3.5)/size(3) = 1⁄2 which is less than 2/3. So, this is not the scapegoat and we move up ." }, { "code": null, "e": 7428, "s": 7211, "text": "Since 3 is not the scapegoat, we move and check the same condition for node 4. Since size(3) = 2 and size(4) = 3, so size(3)/size(4) = 2/3 which is not greater than 2/3. So, this is not the scapegoat and we move up ." }, { "code": null, "e": 7648, "s": 7430, "text": "Since 3 is not the scapegoat, we move and check the same condition for node 4. Since, size(3) = 2 and size(4) = 3, so size(3)/size(4) = 2/3 which is not greater than 2/3. So, this is not the scapegoat and we move up ." }, { "code": null, "e": 7813, "s": 7648, "text": "Now, size(4)/size(2) = 3/6. Since, size(4)= 3 and size(2) = 6 but 3/6 is still less than 2/3, which does not fulfill the condition of scapegoat so we again move up." }, { "code": null, "e": 7977, "s": 7813, "text": "Now, size(2)/size(5) = 6/7. Since, size(2) = 6 and size(5) = 7. 6/7 >2/3 which fulfills the condition of scapegoat, so we stop here and hence node 5 is a scapegoat" }, { "code": null, "e": 8101, "s": 7979, "text": "Finally, after finding the scapegoat, rebuilding will be taken at the subtree rooted at scapegoat i.e., at 5. Final tree:" }, { "code": null, "e": 8147, "s": 8104, "text": "Comparison with other self-balancing BSTs " }, { "code": null, "e": 8225, "s": 8147, "text": "Red-Black and AVL : Time complexity of search, insert and delete is O(Log n) " }, { "code": null, "e": 8369, "s": 8225, "text": "Splay Tree : Worst case time complexities of search, insert and delete is O(n). But amortized time complexity of these operations is O(Log n). " }, { "code": null, "e": 8592, "s": 8369, "text": "ScapeGoat Tree: Like Splay Tree, it is easy to implement and has worst case time complexity of search as O(Log n). Worst case and amortized time complexities of insert and delete are same as Splay Tree for Scapegoat tree. " }, { "code": null, "e": 8886, "s": 8592, "text": "This article is contributed by Rahul Aggarwal and Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 8905, "s": 8886, "text": "Self-Balancing-BST" }, { "code": null, "e": 8929, "s": 8905, "text": "Advanced Data Structure" }, { "code": null, "e": 8934, "s": 8929, "text": "Tree" }, { "code": null, "e": 8939, "s": 8934, "text": "Tree" }, { "code": null, "e": 9037, "s": 8939, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9066, "s": 9037, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 9093, "s": 9066, "text": "Trie | (Insert and Search)" }, { "code": null, "e": 9118, "s": 9093, "text": "LRU Cache Implementation" }, { "code": null, "e": 9141, "s": 9118, "text": "Introduction of B-Tree" }, { "code": null, "e": 9175, "s": 9141, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 9225, "s": 9175, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 9260, "s": 9225, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 9294, "s": 9260, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 9323, "s": 9294, "text": "AVL Tree | Set 1 (Insertion)" } ]
Python – Filter Tuples with All Even Elements
02 Sep, 2020 Given List of tuples, filter only those with all even elements. Input : test_list = [(6, 4, 2, 8), (5, 6, 7, 6), (8, 1, 2), (7, )]Output : [(6, 4, 2, 8)]Explanation : Only 1 tuple with all even elements. Input : test_list = [(6, 4, 2, 9), (5, 6, 7, 6), (8, 1, 2), (7, )]Output : []Explanation : No tuple with all even elements. Method #1 : Using loop In this, we iterate each tuple, and check for all even elements using % operator and if even one element is odd, tuple is flagged and not added in result list. Python3 # Python3 code to demonstrate working of # Filter Tuples with All Even Elements# Using loop # initializing listtest_list = [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )] # printing original listprint("The original list is : " + str(test_list)) res_list = []for sub in test_list: res = True # check if all are even for ele in sub: if ele % 2 != 0: res = False break if res: res_list.append(sub) # printing resultsprint("Filtered Tuples : " + str(res_list)) The original list is : [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )] Filtered Tuples : [(6, 4, 2, 8), (8, 0, 2)] Method #2 : Using all() + list comprehension In this, the task of checking for all elements to be even is done using all(), and list comprehension is used for task of filtering post checking. Python3 # Python3 code to demonstrate working of # Filter Tuples with All Even Elements# Using all() + list comprehension # initializing listtest_list = [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )] # printing original listprint("The original list is : " + str(test_list)) # testing for tuple to be even using all()res = [sub for sub in test_list if all(ele % 2 == 0 for ele in sub)] # printing resultsprint("Filtered Tuples : " + str(res)) The original list is : [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )] Filtered Tuples : [(6, 4, 2, 8), (8, 0, 2)] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 92, "s": 28, "text": "Given List of tuples, filter only those with all even elements." }, { "code": null, "e": 232, "s": 92, "text": "Input : test_list = [(6, 4, 2, 8), (5, 6, 7, 6), (8, 1, 2), (7, )]Output : [(6, 4, 2, 8)]Explanation : Only 1 tuple with all even elements." }, { "code": null, "e": 356, "s": 232, "text": "Input : test_list = [(6, 4, 2, 9), (5, 6, 7, 6), (8, 1, 2), (7, )]Output : []Explanation : No tuple with all even elements." }, { "code": null, "e": 379, "s": 356, "text": "Method #1 : Using loop" }, { "code": null, "e": 539, "s": 379, "text": "In this, we iterate each tuple, and check for all even elements using % operator and if even one element is odd, tuple is flagged and not added in result list." }, { "code": null, "e": 547, "s": 539, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Filter Tuples with All Even Elements# Using loop # initializing listtest_list = [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )] # printing original listprint(\"The original list is : \" + str(test_list)) res_list = []for sub in test_list: res = True # check if all are even for ele in sub: if ele % 2 != 0: res = False break if res: res_list.append(sub) # printing resultsprint(\"Filtered Tuples : \" + str(res_list))", "e": 1062, "s": 547, "text": null }, { "code": null, "e": 1177, "s": 1062, "text": "The original list is : [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )]\nFiltered Tuples : [(6, 4, 2, 8), (8, 0, 2)]\n" }, { "code": null, "e": 1222, "s": 1177, "text": "Method #2 : Using all() + list comprehension" }, { "code": null, "e": 1369, "s": 1222, "text": "In this, the task of checking for all elements to be even is done using all(), and list comprehension is used for task of filtering post checking." }, { "code": null, "e": 1377, "s": 1369, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Filter Tuples with All Even Elements# Using all() + list comprehension # initializing listtest_list = [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )] # printing original listprint(\"The original list is : \" + str(test_list)) # testing for tuple to be even using all()res = [sub for sub in test_list if all(ele % 2 == 0 for ele in sub)] # printing resultsprint(\"Filtered Tuples : \" + str(res))", "e": 1815, "s": 1377, "text": null }, { "code": null, "e": 1930, "s": 1815, "text": "The original list is : [(6, 4, 2, 8), (5, 6, 7, 6), (8, 0, 2), (7, )]\nFiltered Tuples : [(6, 4, 2, 8), (8, 0, 2)]\n" }, { "code": null, "e": 1953, "s": 1930, "text": "Python string-programs" }, { "code": null, "e": 1960, "s": 1953, "text": "Python" }, { "code": null, "e": 1976, "s": 1960, "text": "Python Programs" }, { "code": null, "e": 2074, "s": 1976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2106, "s": 2074, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2133, "s": 2106, "text": "Python Classes and Objects" }, { "code": null, "e": 2164, "s": 2133, "text": "Python | os.path.join() method" }, { "code": null, "e": 2187, "s": 2164, "text": "Introduction To PYTHON" }, { "code": null, "e": 2208, "s": 2187, "text": "Python OOPs Concepts" }, { "code": null, "e": 2230, "s": 2208, "text": "Defaultdict in Python" }, { "code": null, "e": 2269, "s": 2230, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2307, "s": 2269, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2356, "s": 2307, "text": "Python | Convert string dictionary to dictionary" } ]
How to update the value stored in a Dictionary in C#?
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. In Dictionary, the key cannot be null, but value can be. A key must be unique. Duplicate keys are not allowed if we try to use duplicate key then compiler will throw an exception. As mentioned above a value in a dictionary can be updated by using its key as the key is unique for every value. myDictionary[myKey] = myNewValue; Let’s take a dictionary of students having id and name. Now if we want to change the name of the student having id 2 from "Mrk" to "Mark". Live Demo using System; using System.Collections.Generic; namespace DemoApplication{ class Program{ static void Main(string[] args){ Dictionary<int, string> students = new Dictionary<int, string>{ { 1, "John" }, { 2, "Mrk" }, { 3, "Bill" } }; Console.WriteLine($"Name of student having id 2: {students[2]}"); students[2] = "Mark"; Console.WriteLine($"Updated Name of student having id 2: {students[2]}"); Console.ReadLine(); } } } The output of the above code is − Name of student having id 2: Mrk Updated Name of student having id 2: Mark
[ { "code": null, "e": 1459, "s": 1187, "text": "In C#, Dictionary is a generic collection which is generally used to store key/value pairs. In Dictionary, the key cannot be null, but value can be. A key must be unique. Duplicate keys are not allowed if we try to use duplicate key then compiler will throw an exception." }, { "code": null, "e": 1572, "s": 1459, "text": "As mentioned above a value in a dictionary can be updated by using its key as the key is unique for every value." }, { "code": null, "e": 1606, "s": 1572, "text": "myDictionary[myKey] = myNewValue;" }, { "code": null, "e": 1745, "s": 1606, "text": "Let’s take a dictionary of students having id and name. Now if we want to change the name of the student having id 2 from \"Mrk\" to \"Mark\"." }, { "code": null, "e": 1756, "s": 1745, "text": " Live Demo" }, { "code": null, "e": 2285, "s": 1756, "text": "using System;\nusing System.Collections.Generic;\nnamespace DemoApplication{\n class Program{\n static void Main(string[] args){\n Dictionary<int, string> students = new Dictionary<int, string>{\n { 1, \"John\" },\n { 2, \"Mrk\" },\n { 3, \"Bill\" }\n };\n Console.WriteLine($\"Name of student having id 2: {students[2]}\");\n students[2] = \"Mark\";\n Console.WriteLine($\"Updated Name of student having id 2: {students[2]}\");\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2319, "s": 2285, "text": "The output of the above code is −" }, { "code": null, "e": 2394, "s": 2319, "text": "Name of student having id 2: Mrk\nUpdated Name of student having id 2: Mark" } ]
Python Program for Number of elements with odd factors in given range
03 Dec, 2018 Given a range [n,m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples: Input : n = 5, m = 100 Output : 8 The numbers with odd factors are 9, 16, 25, 36, 49, 64, 81 and 100 Input : n = 8, m = 65 Output : 6 Input : n = 10, m = 23500 Output : 150 A Simple Solution is to loop through all numbers starting from n. For every number, check if it has an even number of factors. If it has an even number of factors then increment count of such numbers and finally print the number of such elements. To find all divisors of a natural number efficiently, refer All divisors of a natural number An Efficient Solution is to observe the pattern. Only those numbers, which are perfect Squares have an odd number of factors. Let us analyze this pattern through an example. For example, 9 has odd number of factors, 1, 3 and 9. 16 also has odd number of factors, 1, 2, 4, 8, 16. The reason for this is, for numbers other than perfect squares, all factors are in the form of pairs, but for perfect squares, one factor is single and makes the total as odd. How to find number of perfect squares in a range?The answer is difference between square root of m and n-1 (not n)There is a little caveat. As both n and m are inclusive, if n is a perfect square, we will get an answer which is less than one the actual answer. To understand this, consider range [4, 36]. Answer is 5 i.e., numbers 4, 9, 16, 25 and 36.But if we do (36**0.5) – (4**0.5) we get 4. So to avoid this semantic error, we take n-1. # Python program to count number of odd squares# in given range [n, m] def countOddSquares(n, m): return int(m**0.5) - int((n-1)**0.5) # Driver coden = 5m = 100print("Count is", countOddSquares(n, m)) # This code is contributed by# Mohit Gupta_OMG <0_o> Output: Count is 8 Time Complexity: O(1) Please refer complete article on Number of elements with odd factors in given range for more details! Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary Python program to add two numbers Python Program for Binary Search (Recursive and Iterative) Python Program for factorial of a number Python program to find second largest number in a list Iterate over characters of a string in Python Python program to interchange first and last elements in a list Python | Convert set into a list Appending to list in Python dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2018" }, { "code": null, "e": 149, "s": 28, "text": "Given a range [n,m], find the number of elements that have odd number of factors in the given range (n and m inclusive)." }, { "code": null, "e": 159, "s": 149, "text": "Examples:" }, { "code": null, "e": 339, "s": 159, "text": "Input : n = 5, m = 100\nOutput : 8\nThe numbers with odd factors are 9, 16, 25, \n36, 49, 64, 81 and 100\n\nInput : n = 8, m = 65\nOutput : 6\n\nInput : n = 10, m = 23500\nOutput : 150\n" }, { "code": null, "e": 679, "s": 339, "text": "A Simple Solution is to loop through all numbers starting from n. For every number, check if it has an even number of factors. If it has an even number of factors then increment count of such numbers and finally print the number of such elements. To find all divisors of a natural number efficiently, refer All divisors of a natural number" }, { "code": null, "e": 853, "s": 679, "text": "An Efficient Solution is to observe the pattern. Only those numbers, which are perfect Squares have an odd number of factors. Let us analyze this pattern through an example." }, { "code": null, "e": 1134, "s": 853, "text": "For example, 9 has odd number of factors, 1, 3 and 9. 16 also has odd number of factors, 1, 2, 4, 8, 16. The reason for this is, for numbers other than perfect squares, all factors are in the form of pairs, but for perfect squares, one factor is single and makes the total as odd." }, { "code": null, "e": 1575, "s": 1134, "text": "How to find number of perfect squares in a range?The answer is difference between square root of m and n-1 (not n)There is a little caveat. As both n and m are inclusive, if n is a perfect square, we will get an answer which is less than one the actual answer. To understand this, consider range [4, 36]. Answer is 5 i.e., numbers 4, 9, 16, 25 and 36.But if we do (36**0.5) – (4**0.5) we get 4. So to avoid this semantic error, we take n-1." }, { "code": "# Python program to count number of odd squares# in given range [n, m] def countOddSquares(n, m): return int(m**0.5) - int((n-1)**0.5) # Driver coden = 5m = 100print(\"Count is\", countOddSquares(n, m)) # This code is contributed by# Mohit Gupta_OMG <0_o>", "e": 1835, "s": 1575, "text": null }, { "code": null, "e": 1843, "s": 1835, "text": "Output:" }, { "code": null, "e": 1855, "s": 1843, "text": "Count is 8\n" }, { "code": null, "e": 1877, "s": 1855, "text": "Time Complexity: O(1)" }, { "code": null, "e": 1979, "s": 1877, "text": "Please refer complete article on Number of elements with odd factors in given range for more details!" }, { "code": null, "e": 1995, "s": 1979, "text": "Python Programs" }, { "code": null, "e": 2093, "s": 1995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2130, "s": 2093, "text": "Python Program for Fibonacci numbers" }, { "code": null, "e": 2179, "s": 2130, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 2213, "s": 2179, "text": "Python program to add two numbers" }, { "code": null, "e": 2272, "s": 2213, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 2313, "s": 2272, "text": "Python Program for factorial of a number" }, { "code": null, "e": 2368, "s": 2313, "text": "Python program to find second largest number in a list" }, { "code": null, "e": 2414, "s": 2368, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 2478, "s": 2414, "text": "Python program to interchange first and last elements in a list" }, { "code": null, "e": 2511, "s": 2478, "text": "Python | Convert set into a list" } ]
Python | sympy.factor() method
12 Jun, 2019 With the help of sympy.factor() method, we can find the factors of mathematical expressions in the form of variables by using sympy.factor() method. Syntax : sympy.factor(expression)Return : Return factor of mathematical expression. Example #1 :In this example we can see that by using sympy.factor() method, we can find the factors of mathematical expression with variables. Here we use symbols() method also to declare a variable as symbol. # import sympyfrom sympy import expand, symbols, factor x, y = symbols('x y')gfg_exp = x + yexp = sympy.expand(gfg_exp**2) # Use sympy.factor() methodfact = factor(exp) print(fact) Output : (x + y)**2 Example #2 : # import sympyfrom sympy import expand, symbols, factor x, y, z = symbols('x y z')gfg_exp = x + y + zexp = sympy.expand(gfg_exp**2) # Use sympy.factor() methodfact = factor(exp) print(fact) Output : (x + y + z)**2 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2019" }, { "code": null, "e": 177, "s": 28, "text": "With the help of sympy.factor() method, we can find the factors of mathematical expressions in the form of variables by using sympy.factor() method." }, { "code": null, "e": 261, "s": 177, "text": "Syntax : sympy.factor(expression)Return : Return factor of mathematical expression." }, { "code": null, "e": 471, "s": 261, "text": "Example #1 :In this example we can see that by using sympy.factor() method, we can find the factors of mathematical expression with variables. Here we use symbols() method also to declare a variable as symbol." }, { "code": "# import sympyfrom sympy import expand, symbols, factor x, y = symbols('x y')gfg_exp = x + yexp = sympy.expand(gfg_exp**2) # Use sympy.factor() methodfact = factor(exp) print(fact)", "e": 655, "s": 471, "text": null }, { "code": null, "e": 664, "s": 655, "text": "Output :" }, { "code": null, "e": 675, "s": 664, "text": "(x + y)**2" }, { "code": null, "e": 688, "s": 675, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import expand, symbols, factor x, y, z = symbols('x y z')gfg_exp = x + y + zexp = sympy.expand(gfg_exp**2) # Use sympy.factor() methodfact = factor(exp) print(fact)", "e": 881, "s": 688, "text": null }, { "code": null, "e": 890, "s": 881, "text": "Output :" }, { "code": null, "e": 905, "s": 890, "text": "(x + y + z)**2" }, { "code": null, "e": 911, "s": 905, "text": "SymPy" }, { "code": null, "e": 918, "s": 911, "text": "Python" } ]
Duplicates in an array in O(n) time and by using O(1) extra space | Set-3 - GeeksforGeeks
01 Mar, 2021 Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. It is required that the order in which elements repeat should be maintained. If there is no repeating element present then print -1.Examples: Input : arr[] = {1, 2, 3, 1, 3, 6, 6} Output : 1, 3, 6 Elements 1, 3 and 6 are repeating. Second occurrence of 1 is found first followed by repeated occurrence of 3 and 6. Input : arr[] = {0, 3, 1, 3, 0} Output : 3, 0 Second occurrence of 3 is found first followed by second occurrence of 0. We have discussed two approaches for this question in below posts: Find duplicates in O(n) time and O(1) extra space | Set 1 Duplicates in an array in O(n) time and by using O(1) extra space | Set-2There is a problem in first approach. It prints the repeated number more than once. For example: {1, 6, 3, 1, 3, 6, 6} it will give output as : 3 6 6. In second approach although each repeated item is printed only once, the order in which their repetition occurs is not maintained. To print elements in order in which they are repeating, the second approach is modified. To mark the presence of an element size of the array, n is added to the index position arr[i] corresponding to array element arr[i]. Before adding n, check if value at index arr[i] is greater than or equal to n or not. If it is greater than or equal to, then this means that element arr[i] is repeating. To avoid printing repeating element multiple times, check if it is the first repetition of arr[i] or not. It is first repetition if value at index position arr[i] is less than 2*n. This is because, if element arr[i] has occurred only once before then n is added to index arr[i] only once and thus value at index arr[i] is less than 2*n. Add n to index arr[i] so that value becomes greater than or equal to 2*n and it will prevent further printing of current repeating element. Also if value at index arr[i] is less than n then it is first occurrence (not repetition) of element arr[i]. So to mark this add n to element at index arr[i].Below is the implementation of above approach: C++ Java Python 3 C# PHP Javascript // C++ program to print all elements that// appear more than once.#include <bits/stdc++.h>using namespace std; // Function to find repeating elementsvoid printDuplicates(int arr[], int n){ int i; // Flag variable used to // represent whether repeating // element is found or not. int fl = 0; for (i = 0; i < n; i++) { // Check if current element is // repeating or not. If it is // repeating then value will // be greater than or equal to n. if (arr[arr[i] % n] >= n) { // Check if it is first // repetition or not. If it is // first repetition then value // at index arr[i] is less than // 2*n. Print arr[i] if it is // first repetition. if (arr[arr[i] % n] < 2 * n) { cout << arr[i] % n << " "; fl = 1; } } // Add n to index arr[i] to mark // presence of arr[i] or to // mark repetition of arr[i]. arr[arr[i] % n] += n; } // If flag variable is not set // then no repeating element is // found. So print -1. if (!fl) cout << "-1";} // Driver Functionint main(){ int arr[] = { 1, 6, 3, 1, 3, 6, 6 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printDuplicates(arr, arr_size); return 0;} // Java program to print all elements// that appear more than once.import java.io.*; class GFG{ // Function to find repeating elementsstatic void printDuplicates(int arr[], int n){ int i; // Flag variable used to // represent whether repeating // element is found or not. int fl = 0; for (i = 0; i < n; i++) { // Check if current element is // repeating or not. If it is // repeating then value will // be greater than or equal to n. if (arr[arr[i] % n] >= n) { // Check if it is first // repetition or not. If it is // first repetition then value // at index arr[i] is less than // 2*n. Print arr[i] if it is // first repetition. if (arr[arr[i] % n] < 2 * n) { System.out.print( arr[i] % n + " "); fl = 1; } } // Add n to index arr[i] to mark // presence of arr[i] or to // mark repetition of arr[i]. arr[arr[i] % n] += n; } // If flag variable is not set // then no repeating element is // found. So print -1. if (!(fl > 0)) System.out.println("-1");} // Driver Codepublic static void main (String[] args){ int arr[] = { 1, 6, 3, 1, 3, 6, 6 }; int arr_size = arr.length; printDuplicates(arr, arr_size);}} // This code is contributed by anuj_67. # Python 3 program to print all elements that# appear more than once. # Function to find repeating elementsdef printDuplicates(arr, n): # Flag variable used to # represent whether repeating # element is found or not. fl = 0; for i in range (0, n): # Check if current element is # repeating or not. If it is # repeating then value will # be greater than or equal to n. if (arr[arr[i] % n] >= n): # Check if it is first # repetition or not. If it is # first repetition then value # at index arr[i] is less than # 2*n. Print arr[i] if it is # first repetition. if (arr[arr[i] % n] < 2 * n): print(arr[i] % n, end = " ") fl = 1; # Add n to index arr[i] to mark # presence of arr[i] or to # mark repetition of arr[i]. arr[arr[i] % n] += n; # If flag variable is not set # then no repeating element is # found. So print -1. if (fl == 0): print("-1") # Driver Functionarr = [ 1, 6, 3, 1, 3, 6, 6 ];arr_size = len(arr);printDuplicates(arr, arr_size); # This code is contributed# by Akanksha Rai // C# program to print all elements// that appear more than once.using System; class GFG{ // Function to find repeating elementsstatic void printDuplicates(int []arr, int n){ int i; // Flag variable used to // represent whether repeating // element is found or not. int fl = 0; for (i = 0; i < n; i++) { // Check if current element is // repeating or not. If it is // repeating then value will // be greater than or equal to n. if (arr[arr[i] % n] >= n) { // Check if it is first // repetition or not. If it is // first repetition then value // at index arr[i] is less than // 2*n. Print arr[i] if it is // first repetition. if (arr[arr[i] % n] < 2 * n) { Console.Write( arr[i] % n + " "); fl = 1; } } // Add n to index arr[i] to mark // presence of arr[i] or to // mark repetition of arr[i]. arr[arr[i] % n] += n; } // If flag variable is not set // then no repeating element is // found. So print -1. if (!(fl > 0)) Console.Write("-1");} // Driver Codepublic static void Main (){ int []arr = { 1, 6, 3, 1, 3, 6, 6 }; int arr_size = arr.Length; printDuplicates(arr, arr_size);}} // This code is contributed// by 29AjayKumar <?php// PHP program to print all elements that// appear more than once. // Function to find repeating elementsfunction printDuplicates($arr, $n){ $i; // Flag variable used to // represent whether repeating // element is found or not. $fl = 0; for ($i = 0; $i < $n; $i++) { // Check if current element is // repeating or not. If it is // repeating then value will // be greater than or equal to n. if ($arr[$arr[$i] % $n] >= $n) { // Check if it is first // repetition or not. If it is // first repetition then value // at index arr[i] is less than // 2*n. Print arr[i] if it is // first repetition. if ($arr[$arr[$i] % $n] < 2 * $n) { echo $arr[$i] % $n . " "; $fl = 1; } } // Add n to index arr[i] to mark // presence of arr[i] or to // mark repetition of arr[i]. $arr[$arr[$i] % $n] += $n; } // If flag variable is not set // then no repeating element is // found. So print -1. if (!$fl) echo "-1";} // Driver Function$arr = array(1, 6, 3, 1, 3, 6, 6);$arr_size = sizeof($arr);printDuplicates($arr, $arr_size); // This code is contributed// by Mukul Singh <script> // JavaScript program to print all elements that// appear more than once. // Function to find repeating elementsfunction printDuplicates(arr, n){ let i; // Flag variable used to // represent whether repeating // element is found or not. let fl = 0; for (i = 0; i < n; i++) { // Check if current element is // repeating or not. If it is // repeating then value will // be greater than or equal to n. if (arr[arr[i] % n] >= n) { // Check if it is first // repetition or not. If it is // first repetition then value // at index arr[i] is less than // 2*n. Print arr[i] if it is // first repetition. if (arr[arr[i] % n] < 2 * n) { document.write(arr[i] % n + " "); fl = 1; } } // Add n to index arr[i] to mark // presence of arr[i] or to // mark repetition of arr[i]. arr[arr[i] % n] += n; } // If flag variable is not set // then no repeating element is // found. So print -1. if (!fl) document.write("-1");} // Driver Function let arr = [ 1, 6, 3, 1, 3, 6, 6 ]; let arr_size = arr.length; printDuplicates(arr, arr_size); // This code is contributed by Surbhi Tyagi. </script> 1 3 6 Time Complexity: O(n) Auxiliary Space: O(1) vt_m 29AjayKumar Code_Mech Akanksha_Rai surbhityagi15 limited-range-elements Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Binary Search Linear Search Maximum and minimum of an array using minimum number of comparisons Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 25258, "s": 25230, "text": "\n01 Mar, 2021" }, { "code": null, "e": 25602, "s": 25258, "text": "Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. It is required that the order in which elements repeat should be maintained. If there is no repeating element present then print -1.Examples: " }, { "code": null, "e": 25896, "s": 25602, "text": "Input : arr[] = {1, 2, 3, 1, 3, 6, 6}\nOutput : 1, 3, 6\nElements 1, 3 and 6 are repeating.\nSecond occurrence of 1 is found\nfirst followed by repeated occurrence\nof 3 and 6.\n\nInput : arr[] = {0, 3, 1, 3, 0}\nOutput : 3, 0\nSecond occurrence of 3 is found\nfirst followed by second occurrence \nof 0." }, { "code": null, "e": 27455, "s": 25898, "text": "We have discussed two approaches for this question in below posts: Find duplicates in O(n) time and O(1) extra space | Set 1 Duplicates in an array in O(n) time and by using O(1) extra space | Set-2There is a problem in first approach. It prints the repeated number more than once. For example: {1, 6, 3, 1, 3, 6, 6} it will give output as : 3 6 6. In second approach although each repeated item is printed only once, the order in which their repetition occurs is not maintained. To print elements in order in which they are repeating, the second approach is modified. To mark the presence of an element size of the array, n is added to the index position arr[i] corresponding to array element arr[i]. Before adding n, check if value at index arr[i] is greater than or equal to n or not. If it is greater than or equal to, then this means that element arr[i] is repeating. To avoid printing repeating element multiple times, check if it is the first repetition of arr[i] or not. It is first repetition if value at index position arr[i] is less than 2*n. This is because, if element arr[i] has occurred only once before then n is added to index arr[i] only once and thus value at index arr[i] is less than 2*n. Add n to index arr[i] so that value becomes greater than or equal to 2*n and it will prevent further printing of current repeating element. Also if value at index arr[i] is less than n then it is first occurrence (not repetition) of element arr[i]. So to mark this add n to element at index arr[i].Below is the implementation of above approach: " }, { "code": null, "e": 27459, "s": 27455, "text": "C++" }, { "code": null, "e": 27464, "s": 27459, "text": "Java" }, { "code": null, "e": 27473, "s": 27464, "text": "Python 3" }, { "code": null, "e": 27476, "s": 27473, "text": "C#" }, { "code": null, "e": 27480, "s": 27476, "text": "PHP" }, { "code": null, "e": 27491, "s": 27480, "text": "Javascript" }, { "code": "// C++ program to print all elements that// appear more than once.#include <bits/stdc++.h>using namespace std; // Function to find repeating elementsvoid printDuplicates(int arr[], int n){ int i; // Flag variable used to // represent whether repeating // element is found or not. int fl = 0; for (i = 0; i < n; i++) { // Check if current element is // repeating or not. If it is // repeating then value will // be greater than or equal to n. if (arr[arr[i] % n] >= n) { // Check if it is first // repetition or not. If it is // first repetition then value // at index arr[i] is less than // 2*n. Print arr[i] if it is // first repetition. if (arr[arr[i] % n] < 2 * n) { cout << arr[i] % n << \" \"; fl = 1; } } // Add n to index arr[i] to mark // presence of arr[i] or to // mark repetition of arr[i]. arr[arr[i] % n] += n; } // If flag variable is not set // then no repeating element is // found. So print -1. if (!fl) cout << \"-1\";} // Driver Functionint main(){ int arr[] = { 1, 6, 3, 1, 3, 6, 6 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printDuplicates(arr, arr_size); return 0;}", "e": 28826, "s": 27491, "text": null }, { "code": "// Java program to print all elements// that appear more than once.import java.io.*; class GFG{ // Function to find repeating elementsstatic void printDuplicates(int arr[], int n){ int i; // Flag variable used to // represent whether repeating // element is found or not. int fl = 0; for (i = 0; i < n; i++) { // Check if current element is // repeating or not. If it is // repeating then value will // be greater than or equal to n. if (arr[arr[i] % n] >= n) { // Check if it is first // repetition or not. If it is // first repetition then value // at index arr[i] is less than // 2*n. Print arr[i] if it is // first repetition. if (arr[arr[i] % n] < 2 * n) { System.out.print( arr[i] % n + \" \"); fl = 1; } } // Add n to index arr[i] to mark // presence of arr[i] or to // mark repetition of arr[i]. arr[arr[i] % n] += n; } // If flag variable is not set // then no repeating element is // found. So print -1. if (!(fl > 0)) System.out.println(\"-1\");} // Driver Codepublic static void main (String[] args){ int arr[] = { 1, 6, 3, 1, 3, 6, 6 }; int arr_size = arr.length; printDuplicates(arr, arr_size);}} // This code is contributed by anuj_67.", "e": 30241, "s": 28826, "text": null }, { "code": "# Python 3 program to print all elements that# appear more than once. # Function to find repeating elementsdef printDuplicates(arr, n): # Flag variable used to # represent whether repeating # element is found or not. fl = 0; for i in range (0, n): # Check if current element is # repeating or not. If it is # repeating then value will # be greater than or equal to n. if (arr[arr[i] % n] >= n): # Check if it is first # repetition or not. If it is # first repetition then value # at index arr[i] is less than # 2*n. Print arr[i] if it is # first repetition. if (arr[arr[i] % n] < 2 * n): print(arr[i] % n, end = \" \") fl = 1; # Add n to index arr[i] to mark # presence of arr[i] or to # mark repetition of arr[i]. arr[arr[i] % n] += n; # If flag variable is not set # then no repeating element is # found. So print -1. if (fl == 0): print(\"-1\") # Driver Functionarr = [ 1, 6, 3, 1, 3, 6, 6 ];arr_size = len(arr);printDuplicates(arr, arr_size); # This code is contributed# by Akanksha Rai", "e": 31438, "s": 30241, "text": null }, { "code": "// C# program to print all elements// that appear more than once.using System; class GFG{ // Function to find repeating elementsstatic void printDuplicates(int []arr, int n){ int i; // Flag variable used to // represent whether repeating // element is found or not. int fl = 0; for (i = 0; i < n; i++) { // Check if current element is // repeating or not. If it is // repeating then value will // be greater than or equal to n. if (arr[arr[i] % n] >= n) { // Check if it is first // repetition or not. If it is // first repetition then value // at index arr[i] is less than // 2*n. Print arr[i] if it is // first repetition. if (arr[arr[i] % n] < 2 * n) { Console.Write( arr[i] % n + \" \"); fl = 1; } } // Add n to index arr[i] to mark // presence of arr[i] or to // mark repetition of arr[i]. arr[arr[i] % n] += n; } // If flag variable is not set // then no repeating element is // found. So print -1. if (!(fl > 0)) Console.Write(\"-1\");} // Driver Codepublic static void Main (){ int []arr = { 1, 6, 3, 1, 3, 6, 6 }; int arr_size = arr.Length; printDuplicates(arr, arr_size);}} // This code is contributed// by 29AjayKumar", "e": 32827, "s": 31438, "text": null }, { "code": "<?php// PHP program to print all elements that// appear more than once. // Function to find repeating elementsfunction printDuplicates($arr, $n){ $i; // Flag variable used to // represent whether repeating // element is found or not. $fl = 0; for ($i = 0; $i < $n; $i++) { // Check if current element is // repeating or not. If it is // repeating then value will // be greater than or equal to n. if ($arr[$arr[$i] % $n] >= $n) { // Check if it is first // repetition or not. If it is // first repetition then value // at index arr[i] is less than // 2*n. Print arr[i] if it is // first repetition. if ($arr[$arr[$i] % $n] < 2 * $n) { echo $arr[$i] % $n . \" \"; $fl = 1; } } // Add n to index arr[i] to mark // presence of arr[i] or to // mark repetition of arr[i]. $arr[$arr[$i] % $n] += $n; } // If flag variable is not set // then no repeating element is // found. So print -1. if (!$fl) echo \"-1\";} // Driver Function$arr = array(1, 6, 3, 1, 3, 6, 6);$arr_size = sizeof($arr);printDuplicates($arr, $arr_size); // This code is contributed// by Mukul Singh", "e": 34140, "s": 32827, "text": null }, { "code": "<script> // JavaScript program to print all elements that// appear more than once. // Function to find repeating elementsfunction printDuplicates(arr, n){ let i; // Flag variable used to // represent whether repeating // element is found or not. let fl = 0; for (i = 0; i < n; i++) { // Check if current element is // repeating or not. If it is // repeating then value will // be greater than or equal to n. if (arr[arr[i] % n] >= n) { // Check if it is first // repetition or not. If it is // first repetition then value // at index arr[i] is less than // 2*n. Print arr[i] if it is // first repetition. if (arr[arr[i] % n] < 2 * n) { document.write(arr[i] % n + \" \"); fl = 1; } } // Add n to index arr[i] to mark // presence of arr[i] or to // mark repetition of arr[i]. arr[arr[i] % n] += n; } // If flag variable is not set // then no repeating element is // found. So print -1. if (!fl) document.write(\"-1\");} // Driver Function let arr = [ 1, 6, 3, 1, 3, 6, 6 ]; let arr_size = arr.length; printDuplicates(arr, arr_size); // This code is contributed by Surbhi Tyagi. </script>", "e": 35468, "s": 34140, "text": null }, { "code": null, "e": 35474, "s": 35468, "text": "1 3 6" }, { "code": null, "e": 35521, "s": 35476, "text": "Time Complexity: O(n) Auxiliary Space: O(1) " }, { "code": null, "e": 35526, "s": 35521, "text": "vt_m" }, { "code": null, "e": 35538, "s": 35526, "text": "29AjayKumar" }, { "code": null, "e": 35548, "s": 35538, "text": "Code_Mech" }, { "code": null, "e": 35561, "s": 35548, "text": "Akanksha_Rai" }, { "code": null, "e": 35575, "s": 35561, "text": "surbhityagi15" }, { "code": null, "e": 35598, "s": 35575, "text": "limited-range-elements" }, { "code": null, "e": 35605, "s": 35598, "text": "Arrays" }, { "code": null, "e": 35615, "s": 35605, "text": "Searching" }, { "code": null, "e": 35622, "s": 35615, "text": "Arrays" }, { "code": null, "e": 35632, "s": 35622, "text": "Searching" }, { "code": null, "e": 35730, "s": 35632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35778, "s": 35730, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 35822, "s": 35778, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 35854, "s": 35822, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35877, "s": 35854, "text": "Introduction to Arrays" }, { "code": null, "e": 35891, "s": 35877, "text": "Linear Search" }, { "code": null, "e": 35905, "s": 35891, "text": "Binary Search" }, { "code": null, "e": 35919, "s": 35905, "text": "Linear Search" }, { "code": null, "e": 35987, "s": 35919, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36011, "s": 35987, "text": "Find the Missing Number" } ]
logical Operators - Java | Practice | GeeksforGeeks
Logical operators are used when we want to check the truth value of certain statements. Logical operators help us in checking multiple statements together for their truthness. Here we will learn logical operators like AND(&&), OR(||), NOT(!). These operators produce either a true or a false as an output. Example 1: Input: true false Output: false true false Explanation: true&&false=>false true||false=>true !(true) && !(false)=>false Example 2: Input: true true Output: true true false Your Task: Your task is to complete the function logicOp() which takes a and b as a parameter and prints (a AND b), (a OR b), (a NOT b) in separated by space. Constraints: a, b = {true, false} 0 knhashasPremium2 weeks ago System.out.print((a&&b)+" "+(a || b)+" "+((!a)&&(!b))); 0 arpandutta5033 weeks ago static void logicOp(boolean a,boolean b){ System.out.print(a&&b); System.out.print(" "); System.out.print(a || b); System.out.print(" "); System.out.print((!a)&&(!b)); }} 0 sharsimran20023 weeks ago class Geeks{ static void logicOp(boolean a,boolean b){ System.out.print(a&&b); System.out.print(" "); System.out.print(a || b); System.out.print(" "); System.out.print((!a)&&(!b)); }} 0 shrutidhongade161 month ago class Geeks{ static void logicOp(boolean a, boolean b){ /*output (a&&b), (a||b), and ((!a)&&(!b))separated by spaces*/ System.out.printf("%s %s %s", a&&b, a||b, (!a && !b)); } } 0 badgujarsachin831 month ago static void logicOp(boolean a, boolean b){ /*output (a&&b), (a||b), and ((!a)&&(!b))separated by spaces*/ System.out.print((a&& b)+" "); System.out.print((a||b)+" "); System.out.print(!a && !b); } -1 ravi119033852 months ago System.out.print((a&&b)+" "); System.out.print((a||b)+" "); System.out.print(!a && !b); -3 nagaajayk2 months ago System.out.print((a&&b)+" "+(a||b)+" "+(!a && !b)); -2 katwakrishna9502 months ago class Geeks{ static void logicOp(boolean a, boolean b){ /*output (a&&b), (a||b), and ((!a)&&(!b))separated by spaces*/ System.out.print( (a&&b)+" " ); System.out.print( (a||b)+" " ); System.out.print( ((!a)&&(!b)) ); } } -1 hitentandon3 months ago System.out.print((a&&b)+" "+(a||b)+" "+((!(a||b)))); -1 ritukapadiya20023 months ago static void logicOp(boolean a, boolean b){ /*output (a&&b), (a||b), and ((!a)&&(!b))separated by spaces*/ System.out.print(a&&b); System.out.print(" "); System.out.print(a||b); System.out.print(" "); System.out.print((!a)&&(!b)); } 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": 402, "s": 226, "text": "Logical operators are used when we want to check the truth value of certain statements. Logical operators help us in checking multiple statements together for their truthness." }, { "code": null, "e": 532, "s": 402, "text": "Here we will learn logical operators like AND(&&), OR(||), NOT(!). These operators produce either a true or a false as an output." }, { "code": null, "e": 543, "s": 532, "text": "Example 1:" }, { "code": null, "e": 669, "s": 543, "text": "Input:\ntrue false\n\nOutput:\nfalse true false\n\n\nExplanation:\n\ntrue&&false=>false\n\ntrue||false=>true\n\n!(true) && !(false)=>false" }, { "code": null, "e": 680, "s": 669, "text": "Example 2:" }, { "code": null, "e": 723, "s": 680, "text": "Input:\ntrue true\n\nOutput:\ntrue true false\n" }, { "code": null, "e": 917, "s": 723, "text": "Your Task:\nYour task is to complete the function logicOp() which takes a and b as a parameter and prints (a AND b), (a OR b), (a NOT b) in separated by space.\n\nConstraints:\na, b = {true, false}" }, { "code": null, "e": 919, "s": 917, "text": "0" }, { "code": null, "e": 946, "s": 919, "text": "knhashasPremium2 weeks ago" }, { "code": null, "e": 1002, "s": 946, "text": "System.out.print((a&&b)+\" \"+(a || b)+\" \"+((!a)&&(!b)));" }, { "code": null, "e": 1004, "s": 1002, "text": "0" }, { "code": null, "e": 1029, "s": 1004, "text": "arpandutta5033 weeks ago" }, { "code": null, "e": 1225, "s": 1029, "text": "static void logicOp(boolean a,boolean b){ System.out.print(a&&b); System.out.print(\" \"); System.out.print(a || b); System.out.print(\" \"); System.out.print((!a)&&(!b)); }}" }, { "code": null, "e": 1227, "s": 1225, "text": "0" }, { "code": null, "e": 1253, "s": 1227, "text": "sharsimran20023 weeks ago" }, { "code": null, "e": 1467, "s": 1253, "text": "class Geeks{ static void logicOp(boolean a,boolean b){ System.out.print(a&&b); System.out.print(\" \"); System.out.print(a || b); System.out.print(\" \"); System.out.print((!a)&&(!b)); }}" }, { "code": null, "e": 1469, "s": 1467, "text": "0" }, { "code": null, "e": 1497, "s": 1469, "text": "shrutidhongade161 month ago" }, { "code": null, "e": 1713, "s": 1497, "text": "class Geeks{\n \n static void logicOp(boolean a, boolean b){\n /*output (a&&b), (a||b), and ((!a)&&(!b))separated by spaces*/\n \n System.out.printf(\"%s %s %s\", a&&b, a||b, (!a && !b));\n }\n}" }, { "code": null, "e": 1715, "s": 1713, "text": "0" }, { "code": null, "e": 1743, "s": 1715, "text": "badgujarsachin831 month ago" }, { "code": null, "e": 1977, "s": 1743, "text": " static void logicOp(boolean a, boolean b){\n /*output (a&&b), (a||b), and ((!a)&&(!b))separated by spaces*/\n System.out.print((a&& b)+\" \");\n System.out.print((a||b)+\" \");\n System.out.print(!a && !b);\n }" }, { "code": null, "e": 1980, "s": 1977, "text": "-1" }, { "code": null, "e": 2005, "s": 1980, "text": "ravi119033852 months ago" }, { "code": null, "e": 2105, "s": 2005, "text": "System.out.print((a&&b)+\" \"); System.out.print((a||b)+\" \"); System.out.print(!a && !b);" }, { "code": null, "e": 2108, "s": 2105, "text": "-3" }, { "code": null, "e": 2130, "s": 2108, "text": "nagaajayk2 months ago" }, { "code": null, "e": 2191, "s": 2130, "text": " System.out.print((a&&b)+\" \"+(a||b)+\" \"+(!a && !b));\n" }, { "code": null, "e": 2194, "s": 2191, "text": "-2" }, { "code": null, "e": 2222, "s": 2194, "text": "katwakrishna9502 months ago" }, { "code": null, "e": 2506, "s": 2222, "text": "class Geeks{\n \n static void logicOp(boolean a, boolean b){\n /*output (a&&b), (a||b), and ((!a)&&(!b))separated by spaces*/\n \n System.out.print( (a&&b)+\" \" );\n System.out.print( (a||b)+\" \" );\n System.out.print( ((!a)&&(!b)) );\n \n }\n}" }, { "code": null, "e": 2509, "s": 2506, "text": "-1" }, { "code": null, "e": 2533, "s": 2509, "text": "hitentandon3 months ago" }, { "code": null, "e": 2586, "s": 2533, "text": "System.out.print((a&&b)+\" \"+(a||b)+\" \"+((!(a||b))));" }, { "code": null, "e": 2589, "s": 2586, "text": "-1" }, { "code": null, "e": 2618, "s": 2589, "text": "ritukapadiya20023 months ago" }, { "code": null, "e": 2895, "s": 2618, "text": "static void logicOp(boolean a, boolean b){ /*output (a&&b), (a||b), and ((!a)&&(!b))separated by spaces*/ System.out.print(a&&b); System.out.print(\" \"); System.out.print(a||b); System.out.print(\" \"); System.out.print((!a)&&(!b)); }" }, { "code": null, "e": 3041, "s": 2895, "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": 3077, "s": 3041, "text": " Login to access your submissions. " }, { "code": null, "e": 3087, "s": 3077, "text": "\nProblem\n" }, { "code": null, "e": 3097, "s": 3087, "text": "\nContest\n" }, { "code": null, "e": 3160, "s": 3097, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3308, "s": 3160, "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": 3516, "s": 3308, "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": 3622, "s": 3516, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
A Quick Introduction to CMIP6. How to easily access the next... | by Willy Hagi | Towards Data Science
The Coupled Model Intercomparison Project (CMIP) is a huge international collaborative effort to improve the knowledge about climate change and its impacts on the Earth System and on our society. It’s been going around since the 90s and today we are heading to its sixth phase (CMIP6), which will provide a wealth of information for the next Assessment Report (AR6) of the Intergovernmental Panel on Climate Change (IPCC). CMIP6 is sponsoring several different groups working on several different scientific questions, from the climates of the distant past to the impacts of deforestation and land-use changes. When finished, the entire project is estimated to release about 20 to 40 petabytes of data from more than 20 climate models. This is what you could call Big Data by excellence, but how could you give a try to all this information? import intakeimport xarray as xr import proplot as plot import matplotlib.pyplot as plt Apart from Matplotlib, these packages are not what you usually see around in data science tutorials. On the other hand, these packages are absolutely vital if you want to work with meteorological datasets. Intake: a package to share and load datasets. Here this will be your connection to the Cloud via the intake-esm catalog. Xarray: it’s Pandas for n-dimensional datasets, like the outputs from climate models. Proplot: the next big thing for data visualization in Python. Seriously. Matplotlib: the old and good standard package for data visualization in any Python ecosystem. # necessary urlurl = "https://raw.githubusercontent.com/NCAR/intake-esm-datastore/master/catalogs/pangeo-cmip6.json"# open the catalog>>> dataframe = intake.open_esm_datastore(url) Thanks to the Pangeo efforts, now you got access to all the CMIP6 datasets available by taking advantage of the intake-esmpackage. The df variable above works essentially as a common DataFrame you might be familiar with from Pandas, so you can easily check important information like the names of the columns. >>> dataframe.df.columns Index(['activity_id', 'institution_id', 'source_id', 'experiment_id', 'member_id', 'table_id', 'variable_id', 'grid_label', 'zstore', 'dcpp_init_year'],dtype='object') Each one of these columns is named after the controlled vocabulary from the CMIP project and this kind of organization ensures that millions of datasets will be kept neatly, like in a gigantic library. You can read a bit more about this here. After meddling with the vocabulary, it’s very simple to get the dataset you want. Here you’ll go straight to the NCAR’s model monthly near-surface air temperature output of the Historical experiment. A query for this looks like: >>> models = dataframe.search(experiment_id='historical', table_id='Amon', variable_id='tas', institution_id='NCAR', member_id='r11i1p1f1') This search yields an intake_esm.core.esm_datastore data type, which you can use to finally get the dataset you searched for. The variable models give you more information about it, which is basically a dictionary-like structure. >>> models pangeo-cmip6-ESM Collection with 1 entries: > 1 activity_id(s) > 1 institution_id(s) > 1 source_id(s) > 1 experiment_id(s) > 1 member_id(s) > 1 table_id(s) > 1 variable_id(s) > 1 grid_label(s) > 1 zstore(s) > 0 dcpp_init_year(s) To do so, you need first to get the dataset out of the dictionary: >>> datasets = models.to_dataset_dict()Progress: |███████████████████████████████████████████████████████████████████████████████| 100.0% --> The keys in the returned dictionary of datasets are constructed as follows: 'activity_id.institution_id.source_id.experiment_id.table_id.grid_label' --> There are 1 group(s) This yields another dict but with the difference that now you can get the keys to the dataset with datasets.keys() : >>> datasets.keys()dict_keys(['CMIP.NCAR.CESM2.historical.Amon.gn'])>>> dset = datasets['CMIP.NCAR.CESM2.historical.Amon.gn'] The good news is that dset is an xarray.core.dataset.Dataset straight away, so you can readily use it for anything you might want to do with the powerful Xarray package, which is especially suited to work with gridded meteorological data. Plotting is always the fun part and you might be familiar with the Cartopy package for geospatial projections and several other applications. However, here you’ll use the new Proplot package for its simplicity and great ease of use. A quick and neat plot looks like: fig, ax = plot.subplots(axwidth=4.5, tight=True, proj='robin', proj_kw={'lon_0': 180},)# format optionsax.format(land=False, coast=True, innerborders=True, borders=True, labels=True, geogridlinewidth=0,)map1 = ax.contourf(dset['lon'], dset['lat'], dset['tas'][0,0,:,:], cmap='IceFire', extend='both')ax.colorbar(map1, loc='b', shrink=0.5, extendrect=True)plt.show() And Voilà! A map of near-surface air temperature in a good-looking Robinson projection. CMIP6 is, more than ever, readily available for anyone who wants to give a try thanks to the efforts of the Pangeo community. The complex climate models are now accessible to any student, citizen-scientist or full-time scientist with a relatively decent internet connection. This has a great potential to open new contributions, improve knowledge and help the efforts towards climate resilience and mitigation strategies. PS: a Jupyter Notebook with the code above is available in this repository.
[ { "code": null, "e": 595, "s": 172, "text": "The Coupled Model Intercomparison Project (CMIP) is a huge international collaborative effort to improve the knowledge about climate change and its impacts on the Earth System and on our society. It’s been going around since the 90s and today we are heading to its sixth phase (CMIP6), which will provide a wealth of information for the next Assessment Report (AR6) of the Intergovernmental Panel on Climate Change (IPCC)." }, { "code": null, "e": 1014, "s": 595, "text": "CMIP6 is sponsoring several different groups working on several different scientific questions, from the climates of the distant past to the impacts of deforestation and land-use changes. When finished, the entire project is estimated to release about 20 to 40 petabytes of data from more than 20 climate models. This is what you could call Big Data by excellence, but how could you give a try to all this information?" }, { "code": null, "e": 1102, "s": 1014, "text": "import intakeimport xarray as xr import proplot as plot import matplotlib.pyplot as plt" }, { "code": null, "e": 1308, "s": 1102, "text": "Apart from Matplotlib, these packages are not what you usually see around in data science tutorials. On the other hand, these packages are absolutely vital if you want to work with meteorological datasets." }, { "code": null, "e": 1429, "s": 1308, "text": "Intake: a package to share and load datasets. Here this will be your connection to the Cloud via the intake-esm catalog." }, { "code": null, "e": 1515, "s": 1429, "text": "Xarray: it’s Pandas for n-dimensional datasets, like the outputs from climate models." }, { "code": null, "e": 1588, "s": 1515, "text": "Proplot: the next big thing for data visualization in Python. Seriously." }, { "code": null, "e": 1682, "s": 1588, "text": "Matplotlib: the old and good standard package for data visualization in any Python ecosystem." }, { "code": null, "e": 1863, "s": 1682, "text": "# necessary urlurl = \"https://raw.githubusercontent.com/NCAR/intake-esm-datastore/master/catalogs/pangeo-cmip6.json\"# open the catalog>>> dataframe = intake.open_esm_datastore(url)" }, { "code": null, "e": 2173, "s": 1863, "text": "Thanks to the Pangeo efforts, now you got access to all the CMIP6 datasets available by taking advantage of the intake-esmpackage. The df variable above works essentially as a common DataFrame you might be familiar with from Pandas, so you can easily check important information like the names of the columns." }, { "code": null, "e": 2369, "s": 2173, "text": ">>> dataframe.df.columns Index(['activity_id', 'institution_id', 'source_id', 'experiment_id', 'member_id', 'table_id', 'variable_id', 'grid_label', 'zstore', 'dcpp_init_year'],dtype='object')" }, { "code": null, "e": 2612, "s": 2369, "text": "Each one of these columns is named after the controlled vocabulary from the CMIP project and this kind of organization ensures that millions of datasets will be kept neatly, like in a gigantic library. You can read a bit more about this here." }, { "code": null, "e": 2841, "s": 2612, "text": "After meddling with the vocabulary, it’s very simple to get the dataset you want. Here you’ll go straight to the NCAR’s model monthly near-surface air temperature output of the Historical experiment. A query for this looks like:" }, { "code": null, "e": 3097, "s": 2841, "text": ">>> models = dataframe.search(experiment_id='historical', table_id='Amon', variable_id='tas', institution_id='NCAR', member_id='r11i1p1f1')" }, { "code": null, "e": 3327, "s": 3097, "text": "This search yields an intake_esm.core.esm_datastore data type, which you can use to finally get the dataset you searched for. The variable models give you more information about it, which is basically a dictionary-like structure." }, { "code": null, "e": 3567, "s": 3327, "text": ">>> models pangeo-cmip6-ESM Collection with 1 entries:\t> 1 activity_id(s)\t> 1 institution_id(s)\t> 1 source_id(s)\t> 1 experiment_id(s)\t> 1 member_id(s)\t> 1 table_id(s)\t> 1 variable_id(s)\t> 1 grid_label(s)\t> 1 zstore(s)\t> 0 dcpp_init_year(s)" }, { "code": null, "e": 3634, "s": 3567, "text": "To do so, you need first to get the dataset out of the dictionary:" }, { "code": null, "e": 3962, "s": 3634, "text": ">>> datasets = models.to_dataset_dict()Progress: |███████████████████████████████████████████████████████████████████████████████| 100.0% --> The keys in the returned dictionary of datasets are constructed as follows:\t'activity_id.institution_id.source_id.experiment_id.table_id.grid_label' --> There are 1 group(s)" }, { "code": null, "e": 4079, "s": 3962, "text": "This yields another dict but with the difference that now you can get the keys to the dataset with datasets.keys() :" }, { "code": null, "e": 4205, "s": 4079, "text": ">>> datasets.keys()dict_keys(['CMIP.NCAR.CESM2.historical.Amon.gn'])>>> dset = datasets['CMIP.NCAR.CESM2.historical.Amon.gn']" }, { "code": null, "e": 4444, "s": 4205, "text": "The good news is that dset is an xarray.core.dataset.Dataset straight away, so you can readily use it for anything you might want to do with the powerful Xarray package, which is especially suited to work with gridded meteorological data." }, { "code": null, "e": 4711, "s": 4444, "text": "Plotting is always the fun part and you might be familiar with the Cartopy package for geospatial projections and several other applications. However, here you’ll use the new Proplot package for its simplicity and great ease of use. A quick and neat plot looks like:" }, { "code": null, "e": 5127, "s": 4711, "text": "fig, ax = plot.subplots(axwidth=4.5, tight=True, proj='robin', proj_kw={'lon_0': 180},)# format optionsax.format(land=False, coast=True, innerborders=True, borders=True, labels=True, geogridlinewidth=0,)map1 = ax.contourf(dset['lon'], dset['lat'], dset['tas'][0,0,:,:], cmap='IceFire', extend='both')ax.colorbar(map1, loc='b', shrink=0.5, extendrect=True)plt.show()" }, { "code": null, "e": 5216, "s": 5127, "text": "And Voilà! A map of near-surface air temperature in a good-looking Robinson projection." }, { "code": null, "e": 5491, "s": 5216, "text": "CMIP6 is, more than ever, readily available for anyone who wants to give a try thanks to the efforts of the Pangeo community. The complex climate models are now accessible to any student, citizen-scientist or full-time scientist with a relatively decent internet connection." }, { "code": null, "e": 5638, "s": 5491, "text": "This has a great potential to open new contributions, improve knowledge and help the efforts towards climate resilience and mitigation strategies." } ]
Spring Boot - Google Cloud Platform
Google Cloud Platform provides a cloud computing services that run the Spring Boot application in the cloud environment. In this chapter, we are going to see how to deploy the Spring Boot application in GCP app engine platform. First, download the Gradle build Spring Boot application from Spring Initializer page www.start.spring.io. Observe the following screenshot. Now, in build.gradle file, add the Google Cloud appengine plugin and appengine classpath dependency. The code for build.gradle file is given below − buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath 'com.google.cloud.tools:appengine-gradle-plugin:1.3.3' } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'com.google.cloud.tools.appengine' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') } Now, write a simple HTTP Endpoint and it returns the String success as shown − package com.tutorialspoint.appenginedemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class AppengineDemoApplication { public static void main(String[] args) { SpringApplication.run(AppengineDemoApplication.class, args); } @RequestMapping(value = "/") public String success() { return "APP Engine deployment success"; } } Next, add the app.yml file under src/main/appengine directory as shown − runtime: java env: flex handlers: - url: /.* script: this field is required, but ignored Now, go to the Google Cloud console and click the Activate Google cloud shell at the top of the page. Now, move your source files and Gradle file into home directory of your google cloud machine by using google cloud shell. Now, execute the command gradle appengineDeploy and it will deploy your application into the Google Cloud appengine. Note − GCP should be billing enabled and before deploying your application into appengine, you should create appengine platform in GCP. It will take few minutes to deploy your application into GCP appengine platform. After build successful you can see the Service URL in console window. Now, hit the service URL and see the output. To connect the Google Cloud SQL into your Spring Boot application, you should add the following properties into your application.properties file. jdbc:mysql://google/<DATABASE-NAME>?cloudSqlInstance = <GOOGLE_CLOUD_SQL_INSTANCE_NAME> &socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = <USERNAME>&password = <PASSWORD> Note − The Spring Boot application and Google Cloud SQL should be in same GCP project. The application.properties file is given below. spring.dbProductService.driverClassName = com.mysql.jdbc.Driver spring.dbProductService.url = jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance = springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = root&password = rootspring.dbProductService.username = root spring.dbProductService.password = root spring.dbProductService.testOnBorrow = true spring.dbProductService.testWhileIdle = true spring.dbProductService.timeBetweenEvictionRunsMillis = 60000 spring.dbProductService.minEvictableIdleTimeMillis = 30000 spring.dbProductService.validationQuery = SELECT 1 spring.dbProductService.max-active = 15 spring.dbProductService.max-idle = 10 spring.dbProductService.max-wait = 8000 YAML file users can add the below properties to your application.yml file. spring: datasource: driverClassName: com.mysql.jdbc.Driver url: "jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance=springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=root&password=root" password: "root" username: "root" testOnBorrow: true testWhileIdle: true validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 3253, "s": 3025, "text": "Google Cloud Platform provides a cloud computing services that run the Spring Boot application in the cloud environment. In this chapter, we are going to see how to deploy the Spring Boot application in GCP app engine platform." }, { "code": null, "e": 3394, "s": 3253, "text": "First, download the Gradle build Spring Boot application from Spring Initializer page www.start.spring.io. Observe the following screenshot." }, { "code": null, "e": 3495, "s": 3394, "text": "Now, in build.gradle file, add the Google Cloud appengine plugin and appengine classpath dependency." }, { "code": null, "e": 3543, "s": 3495, "text": "The code for build.gradle file is given below −" }, { "code": null, "e": 4248, "s": 3543, "text": "buildscript {\n ext {\n springBootVersion = '1.5.9.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n classpath 'com.google.cloud.tools:appengine-gradle-plugin:1.3.3'\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\napply plugin: 'com.google.cloud.tools.appengine'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\ndependencies {\n compile('org.springframework.boot:spring-boot-starter-web')\n testCompile('org.springframework.boot:spring-boot-starter-test')\n} " }, { "code": null, "e": 4327, "s": 4248, "text": "Now, write a simple HTTP Endpoint and it returns the String success as shown −" }, { "code": null, "e": 4927, "s": 4327, "text": "package com.tutorialspoint.appenginedemo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@SpringBootApplication\n@RestController\npublic class AppengineDemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(AppengineDemoApplication.class, args);\n }\n @RequestMapping(value = \"/\")\n public String success() {\n return \"APP Engine deployment success\";\n }\n} " }, { "code": null, "e": 5000, "s": 4927, "text": "Next, add the app.yml file under src/main/appengine directory as shown −" }, { "code": null, "e": 5094, "s": 5000, "text": "runtime: java\nenv: flex\n\nhandlers:\n- url: /.*\n script: this field is required, but ignored " }, { "code": null, "e": 5196, "s": 5094, "text": "Now, go to the Google Cloud console and click the Activate Google cloud shell at the top of the page." }, { "code": null, "e": 5318, "s": 5196, "text": "Now, move your source files and Gradle file into home directory of your google cloud machine by using google cloud shell." }, { "code": null, "e": 5435, "s": 5318, "text": "Now, execute the command gradle appengineDeploy and it will deploy your application into the Google Cloud appengine." }, { "code": null, "e": 5571, "s": 5435, "text": "Note − GCP should be billing enabled and before deploying your application into appengine, you should create appengine platform in GCP." }, { "code": null, "e": 5652, "s": 5571, "text": "It will take few minutes to deploy your application into GCP appengine platform." }, { "code": null, "e": 5722, "s": 5652, "text": "After build successful you can see the Service URL in console window." }, { "code": null, "e": 5767, "s": 5722, "text": "Now, hit the service URL and see the output." }, { "code": null, "e": 5913, "s": 5767, "text": "To connect the Google Cloud SQL into your Spring Boot application, you should add the following properties into your application.properties file." }, { "code": null, "e": 6100, "s": 5913, "text": "jdbc:mysql://google/<DATABASE-NAME>?cloudSqlInstance = <GOOGLE_CLOUD_SQL_INSTANCE_NAME> &socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = <USERNAME>&password = <PASSWORD>\n" }, { "code": null, "e": 6187, "s": 6100, "text": "Note − The Spring Boot application and Google Cloud SQL should be in same GCP project." }, { "code": null, "e": 6235, "s": 6187, "text": "The application.properties file is given below." }, { "code": null, "e": 7000, "s": 6235, "text": "spring.dbProductService.driverClassName = com.mysql.jdbc.Driver\nspring.dbProductService.url = jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance = springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = root&password = rootspring.dbProductService.username = root\n\nspring.dbProductService.password = root\nspring.dbProductService.testOnBorrow = true\nspring.dbProductService.testWhileIdle = true\nspring.dbProductService.timeBetweenEvictionRunsMillis = 60000\nspring.dbProductService.minEvictableIdleTimeMillis = 30000\nspring.dbProductService.validationQuery = SELECT 1\nspring.dbProductService.max-active = 15\nspring.dbProductService.max-idle = 10\nspring.dbProductService.max-wait = 8000" }, { "code": null, "e": 7075, "s": 7000, "text": "YAML file users can add the below properties to your application.yml file." }, { "code": null, "e": 7558, "s": 7075, "text": "spring:\n datasource: \n driverClassName: com.mysql.jdbc.Driver\n url: \"jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance=springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=root&password=root\"\n password: \"root\"\n username: \"root\"\n testOnBorrow: true\n testWhileIdle: true\n validationQuery: SELECT 1\n \n max-active: 15\n max-idle: 10\n max-wait: 8000" }, { "code": null, "e": 7592, "s": 7558, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 7606, "s": 7592, "text": " Karthikeya T" }, { "code": null, "e": 7639, "s": 7606, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 7654, "s": 7639, "text": " Chaand Sheikh" }, { "code": null, "e": 7689, "s": 7654, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7701, "s": 7689, "text": " Senol Atac" }, { "code": null, "e": 7736, "s": 7701, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7748, "s": 7736, "text": " Senol Atac" }, { "code": null, "e": 7783, "s": 7748, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7795, "s": 7783, "text": " Senol Atac" }, { "code": null, "e": 7828, "s": 7795, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 7840, "s": 7828, "text": " Senol Atac" }, { "code": null, "e": 7847, "s": 7840, "text": " Print" }, { "code": null, "e": 7858, "s": 7847, "text": " Add Notes" } ]
Floating Action type button in kivy - Python - GeeksforGeeks
24 Dec, 2021 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.Now in this article, we will learn about how can we create the type of button similar to floating action button using kivy python. What is Floating Action Button ?? A floating action button (FAB) performs the primary, or most common, action on a screen. It appears in front of all screen content, typically as a circular shape with an icon in its center. To learn how to create this you must have the good knowledge about the Layouts, Button, canvas and Ellipse in canvas. These all we are going to use to create the button. So We are creating a button like the one we see on gmail on the right side i.e for writing a new email in mobile Application (not on website) sign. Basic Approach: 1) import kivy 2) import kivyApp 3) import Boxlayout 4) Set minimum version(optional) 5) create Layout class 6) create App class 7) Set up .kv file : 1) Add Floating Button Properties 2) Create Main Window 3) Add Float Button 8) return Layout/widget/Class(according to requirement) 9) Run an instance of the class Kivy Tutorial – Learn Kivy with Examples. Implementation of the Approach –main.py Python3 ## Sample Python application demonstrating that## How to create a button like floating Action Button## in Kivy using .kv file #################################################### import modules import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # BoxLayout arranges widgets in either# in a vertical fashion that# is one on top of another or in a horizontal# fashion that is one after another.from kivy.uix.boxlayout import BoxLayout # To change the kivy default settings # we use this module config from kivy.config import Config # 0 being off 1 being on as in true / false # you can use 0 or 1 && True or False Config.set('graphics', 'resizable', True) # creating the root widget used in .kv fileclass MainWindow(BoxLayout): pass # creating the App class in which name#.kv file is to be named main.kvclass MainApp(App): # defining build() def build(self): # returning the instance of root class return MainWindow() # run the appif __name__ == '__main__': MainApp().run() .kv file implementationmain.kv Python3 #.kv file implementation of Float Button # using Float Layout for the creation of Floatbutton# Here we are creating the properties of button# Button will be created in Main window Box Layout <FloatButton@FloatLayout> id: float_root # Giving id to button size_hint: (None, None) text: '' btn_size: (70, 70) size: (70, 70) bg_color: (0.404, 0.227, 0.718, 1.0) pos_hint: {'x': .6} # Adding shape and all, size, position to button Button: text: float_root.text markup: True font_size: 40 size_hint: (None, None) size: float_root.btn_size pos_hint: {'x': 5.5, 'y': 3.8} background_normal: '' background_color: (0, 0, 0, 0) canvas.before: Color: rgba: (0.404, 0.227, 0.718, 1.0) Ellipse: size: self.size pos: self.pos # Creation of main window<MainWindow>: BoxLayout: # Creating the Float button FloatButton: text: '+' markup: True background_color: 1, 0, 1, 0 Output: sweetyty rkbhola5 Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24366, "s": 24338, "text": "\n24 Dec, 2021" }, { "code": null, "e": 24733, "s": 24366, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.Now in this article, we will learn about how can we create the type of button similar to floating action button using kivy python. " }, { "code": null, "e": 24957, "s": 24733, "text": "What is Floating Action Button ?? A floating action button (FAB) performs the primary, or most common, action on a screen. It appears in front of all screen content, typically as a circular shape with an icon in its center." }, { "code": null, "e": 25276, "s": 24957, "text": "To learn how to create this you must have the good knowledge about the Layouts, Button, canvas and Ellipse in canvas. These all we are going to use to create the button. So We are creating a button like the one we see on gmail on the right side i.e for writing a new email in mobile Application (not on website) sign. " }, { "code": null, "e": 25630, "s": 25278, "text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n3) import Boxlayout\n4) Set minimum version(optional)\n5) create Layout class\n6) create App class\n7) Set up .kv file :\n 1) Add Floating Button Properties\n 2) Create Main Window\n 3) Add Float Button\n8) return Layout/widget/Class(according to requirement)\n9) Run an instance of the class" }, { "code": null, "e": 25674, "s": 25632, "text": "Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 25714, "s": 25674, "text": "Implementation of the Approach –main.py" }, { "code": null, "e": 25722, "s": 25714, "text": "Python3" }, { "code": "## Sample Python application demonstrating that## How to create a button like floating Action Button## in Kivy using .kv file #################################################### import modules import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # BoxLayout arranges widgets in either# in a vertical fashion that# is one on top of another or in a horizontal# fashion that is one after another.from kivy.uix.boxlayout import BoxLayout # To change the kivy default settings # we use this module config from kivy.config import Config # 0 being off 1 being on as in true / false # you can use 0 or 1 && True or False Config.set('graphics', 'resizable', True) # creating the root widget used in .kv fileclass MainWindow(BoxLayout): pass # creating the App class in which name#.kv file is to be named main.kvclass MainApp(App): # defining build() def build(self): # returning the instance of root class return MainWindow() # run the appif __name__ == '__main__': MainApp().run()", "e": 26838, "s": 25722, "text": null }, { "code": null, "e": 26871, "s": 26838, "text": ".kv file implementationmain.kv " }, { "code": null, "e": 26879, "s": 26871, "text": "Python3" }, { "code": "#.kv file implementation of Float Button # using Float Layout for the creation of Floatbutton# Here we are creating the properties of button# Button will be created in Main window Box Layout <FloatButton@FloatLayout> id: float_root # Giving id to button size_hint: (None, None) text: '' btn_size: (70, 70) size: (70, 70) bg_color: (0.404, 0.227, 0.718, 1.0) pos_hint: {'x': .6} # Adding shape and all, size, position to button Button: text: float_root.text markup: True font_size: 40 size_hint: (None, None) size: float_root.btn_size pos_hint: {'x': 5.5, 'y': 3.8} background_normal: '' background_color: (0, 0, 0, 0) canvas.before: Color: rgba: (0.404, 0.227, 0.718, 1.0) Ellipse: size: self.size pos: self.pos # Creation of main window<MainWindow>: BoxLayout: # Creating the Float button FloatButton: text: '+' markup: True background_color: 1, 0, 1, 0 ", "e": 27978, "s": 26879, "text": null }, { "code": null, "e": 27988, "s": 27978, "text": "Output: " }, { "code": null, "e": 28001, "s": 27992, "text": "sweetyty" }, { "code": null, "e": 28010, "s": 28001, "text": "rkbhola5" }, { "code": null, "e": 28021, "s": 28010, "text": "Python-gui" }, { "code": null, "e": 28033, "s": 28021, "text": "Python-kivy" }, { "code": null, "e": 28040, "s": 28033, "text": "Python" }, { "code": null, "e": 28138, "s": 28040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28156, "s": 28138, "text": "Python Dictionary" }, { "code": null, "e": 28191, "s": 28156, "text": "Read a file line by line in Python" }, { "code": null, "e": 28213, "s": 28191, "text": "Enumerate() in Python" }, { "code": null, "e": 28245, "s": 28213, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28275, "s": 28245, "text": "Iterate over a list in Python" }, { "code": null, "e": 28317, "s": 28275, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28343, "s": 28317, "text": "Python String | replace()" }, { "code": null, "e": 28386, "s": 28343, "text": "Python program to convert a list to string" }, { "code": null, "e": 28423, "s": 28386, "text": "Create a Pandas DataFrame from Lists" } ]
C++ Tutorial
C++ is a popular programming language. C++ is used to create computer programs, and is one of the most used language in game development. Our "Try it Yourself" editor makes it easy to learn C++. You can edit C++ code and view the result in your browser. Click on the "Run example" button to see how it works. We recommend reading this tutorial, in the sequence listed in the left menu. C++ is an object oriented language and some concepts may be new. Take breaks when needed, and go over the examples as many times as needed. Insert the missing part of the code below to output "Hello World". int main() { << "Hello World!"; return 0; } Start the Exercise Learn by examples! This tutorial supplements all explanations with clarifying examples. See All C++ Examples Learn by taking a quiz! The quiz will give you a signal of how much you know, or do not know, about C++. Start C++ Quiz Get certified by completing the C++ course 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 39, "s": 0, "text": "C++ is a popular programming language." }, { "code": null, "e": 138, "s": 39, "text": "C++ is used to create computer programs, and is one of the most used language in game development." }, { "code": null, "e": 254, "s": 138, "text": "Our \"Try it Yourself\" editor makes it easy to learn C++. You can edit C++ code and view the result in your browser." }, { "code": null, "e": 309, "s": 254, "text": "Click on the \"Run example\" button to see how it works." }, { "code": null, "e": 386, "s": 309, "text": "We recommend reading this tutorial, in the sequence listed in the left menu." }, { "code": null, "e": 526, "s": 386, "text": "C++ is an object oriented language and some concepts may be new. Take breaks when needed, and go\nover the examples as many times as needed." }, { "code": null, "e": 593, "s": 526, "text": "Insert the missing part of the code below to output \"Hello World\"." }, { "code": null, "e": 643, "s": 593, "text": "int main() {\n << \"Hello World!\";\n return 0;\n}\n" }, { "code": null, "e": 662, "s": 643, "text": "Start the Exercise" }, { "code": null, "e": 750, "s": 662, "text": "Learn by examples! This tutorial supplements all explanations with clarifying examples." }, { "code": null, "e": 771, "s": 750, "text": "See All C++ Examples" }, { "code": null, "e": 876, "s": 771, "text": "Learn by taking a quiz! The quiz will give you a signal of how much you know, or do not know, about C++." }, { "code": null, "e": 891, "s": 876, "text": "Start C++ Quiz" }, { "code": null, "e": 934, "s": 891, "text": "Get certified by completing the C++ course" }, { "code": null, "e": 967, "s": 934, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1009, "s": 967, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1116, "s": 1009, "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": 1135, "s": 1116, "text": "[email protected]" } ]
Building and Deploying a Login System backend using Flask, SQLAlchemy and Heroku | by Aakanksha NS | Towards Data Science
Almost all websites these days have a login system, where you can register if you’re a new user or sign in if you’re an existing one. There can be a lot of moving pieces if you’re trying to build this system from scratch for your application. This article gives a step-by-step overview to create and deploy REST APIs for a login system but can be extended to any REST API in general. All the code related to this article can be found in the following repo: github.com The first thing you’d need to do is create an account on Heroku if you don’t already have one. Sign in to your account and select the Create new app option to create a new Heroku application. Now you need to add Postgres to the application. Navigate to the page of the application you just created, select the Configure Add-ons option, search for Postgres and provision it. To be able to interact with Heroku from the command line, you’d have to install Heroku CLI using the following command (assuming you have Homebrew already installed): $ brew tap heroku/brew && brew install heroku Why we need them: You could create your database’s tables from your Flask app. In my implementation, however, I’ve created the database and tables locally using PostgreSQL and pushed that to Heroku because I found it more straightforward creating tables using a normal SQL editor (I used PopSQL) as compared to SQLAlachemy. I’ve used Flask and SQLAlchemy only to add elements to the database or retrieve elements from it. Install Postgres: brew install postgres Start PostgreSQL server: pg_ctl -D /usr/local/var/postgres start Creating database and user: Postgres sets up a set of default users but they are super user accounts — they can do anything, including delete databases. It’s best to create new users with access only to a particular database: $ psql postgresCREATE ROLE aakanksha WITH LOGIN PASSWORD ‘blah’;CREATE DATABASE bookstore;GRANT ALL PRIVILEGES ON DATABASE bookstore TO aakanksha; Install PopSQL: PopSQL is a very popular and easy to use SQL editor. Download the application from https://popsql.com/ and install it. Connect PopSQL to database: You’ll have to provide details like port number (postgres uses 5432 by default), database name etc. for PopSQL to be able to access your PostgreSQL database. You can just enter the following details: Create Tables on the PopSQL scratchpad: Push to Heroku: $ heroku pg:push bookstore DATABASE --app example-app-medium Now that the database is set up, we can move on to the API part. Make sure you install all the required libraries. You can just store the following list of libraries I’ve used into a text file ( requirements.txt ) and execute the command following it: certifi==2020.4.5.1click==7.1.1Flask==1.1.2flask-heroku==0.1.9Flask-SQLAlchemy==2.4.1itsdangerous==1.1.0Jinja2==2.11.1MarkupSafe==1.1.1psycopg2==2.8.5SQLAlchemy==1.3.16Werkzeug==1.0.1gunicorn==19.5.0flask_cors pip install -r requirements.txt Since you have to access the remote database on Heroku through your flask app, to establish a connection to it, you’d need the database URL. Because the remote database’s URL can change due to many reasons, It is best practice to always fetch the database URL config var from the corresponding Heroku app when your application starts. You can do this by setting an environment variable. Since this URL is particular to a particular project which is limited to a particular directory, it wouldn’t make sense to add it to your global environment variables. This is where direnv comes in. It is an environment switcher that allows to load/unload environment variables depending on the present working directory. To set the variable for your Flask application you’d have to add the following command to a new file called .envrc and place it in the root directory of your project: export DATABASE_URL=$(heroku config:get DATABASE_URL -a example-app-medium) After creating the .envrc file, run $ direnv allow to activate the variables. Here’s some basic config you need in your config.py file in the root directory: import osclass Config(object):SQLALCHEMY_TRACK_MODIFICATIONS = TrueSECRET_KEY = os.urandom(24)SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] Here’s what my folder structure looks like: Flask names an app 'application’ by default, so you’d need an application.py file for the app to run. You can change the name of your app if you want to (using $ export FLASK_APP = ‘your file name'.py) I like putting all Flask related code into a subdirectory called app instead of the root. My application.py looks like: from app import application And within the app subdirectory, here’s my __init__.py (initialization script that marks directories on disk as Python package directories): from flask import Flaskfrom config import Configfrom flask_sqlalchemy import SQLAlchemyfrom sqlalchemy import create_engine# Initializationapplication = Flask(__name__)application.config.from_object(Config)DB_URI = application.config['SQLALCHEMY_DATABASE_URI']engine = create_engine(DB_URI)from app import routes The API code lies in the routes.py file. To see the full routes.py code, follow this link: https://github.com/aakanksha-ns/flask-heroku-login/blob/master/app/routes.py For a login system, you’d need two methods: This method creates an entry in the account table for a new user. You can do an additional check to make sure the username or email does not already exist in the table. Since it’s not safe to store the raw password in a database due to security concerns, you can generate a password hash using the werkzeug library and store the hash instead of the real password. This method just checks if the password entered matches with the original password for the given username Once done, you can use $ flask run to start the flask server and test your API using Postman: Procfile is a mechanism for declaring what commands are run by your application’s dynos on the Heroku platform. You can use gunicorn that takes care of running multiple instances of your web application, making sure they are healthy and restart them as needed, distributing incoming requests across those instances and communicate with the web server. web: gunicorn application:application To deploy the APIs you just created, the easiest way is to push your code to Github repository and connect this repo to your Heroku application: You can set up an automatic deployment or deploy the Flask app manually from the Heroku dashboard. If there are any errors during deployment, they’ll show up in the build log. Once deployed, you can hit the API using Postman and see that it’s working as expected. If there’s an error after deployment, you can view the log this way: In case you’re interested in creating a frontend for your login system, you can check out my React and Redux based UI: github.com Here are a few screenshots of the application I’ve built:
[ { "code": null, "e": 556, "s": 172, "text": "Almost all websites these days have a login system, where you can register if you’re a new user or sign in if you’re an existing one. There can be a lot of moving pieces if you’re trying to build this system from scratch for your application. This article gives a step-by-step overview to create and deploy REST APIs for a login system but can be extended to any REST API in general." }, { "code": null, "e": 629, "s": 556, "text": "All the code related to this article can be found in the following repo:" }, { "code": null, "e": 640, "s": 629, "text": "github.com" }, { "code": null, "e": 735, "s": 640, "text": "The first thing you’d need to do is create an account on Heroku if you don’t already have one." }, { "code": null, "e": 832, "s": 735, "text": "Sign in to your account and select the Create new app option to create a new Heroku application." }, { "code": null, "e": 1014, "s": 832, "text": "Now you need to add Postgres to the application. Navigate to the page of the application you just created, select the Configure Add-ons option, search for Postgres and provision it." }, { "code": null, "e": 1181, "s": 1014, "text": "To be able to interact with Heroku from the command line, you’d have to install Heroku CLI using the following command (assuming you have Homebrew already installed):" }, { "code": null, "e": 1227, "s": 1181, "text": "$ brew tap heroku/brew && brew install heroku" }, { "code": null, "e": 1649, "s": 1227, "text": "Why we need them: You could create your database’s tables from your Flask app. In my implementation, however, I’ve created the database and tables locally using PostgreSQL and pushed that to Heroku because I found it more straightforward creating tables using a normal SQL editor (I used PopSQL) as compared to SQLAlachemy. I’ve used Flask and SQLAlchemy only to add elements to the database or retrieve elements from it." }, { "code": null, "e": 1689, "s": 1649, "text": "Install Postgres: brew install postgres" }, { "code": null, "e": 1754, "s": 1689, "text": "Start PostgreSQL server: pg_ctl -D /usr/local/var/postgres start" }, { "code": null, "e": 1980, "s": 1754, "text": "Creating database and user: Postgres sets up a set of default users but they are super user accounts — they can do anything, including delete databases. It’s best to create new users with access only to a particular database:" }, { "code": null, "e": 2127, "s": 1980, "text": "$ psql postgresCREATE ROLE aakanksha WITH LOGIN PASSWORD ‘blah’;CREATE DATABASE bookstore;GRANT ALL PRIVILEGES ON DATABASE bookstore TO aakanksha;" }, { "code": null, "e": 2262, "s": 2127, "text": "Install PopSQL: PopSQL is a very popular and easy to use SQL editor. Download the application from https://popsql.com/ and install it." }, { "code": null, "e": 2490, "s": 2262, "text": "Connect PopSQL to database: You’ll have to provide details like port number (postgres uses 5432 by default), database name etc. for PopSQL to be able to access your PostgreSQL database. You can just enter the following details:" }, { "code": null, "e": 2530, "s": 2490, "text": "Create Tables on the PopSQL scratchpad:" }, { "code": null, "e": 2546, "s": 2530, "text": "Push to Heroku:" }, { "code": null, "e": 2607, "s": 2546, "text": "$ heroku pg:push bookstore DATABASE --app example-app-medium" }, { "code": null, "e": 2859, "s": 2607, "text": "Now that the database is set up, we can move on to the API part. Make sure you install all the required libraries. You can just store the following list of libraries I’ve used into a text file ( requirements.txt ) and execute the command following it:" }, { "code": null, "e": 3069, "s": 2859, "text": "certifi==2020.4.5.1click==7.1.1Flask==1.1.2flask-heroku==0.1.9Flask-SQLAlchemy==2.4.1itsdangerous==1.1.0Jinja2==2.11.1MarkupSafe==1.1.1psycopg2==2.8.5SQLAlchemy==1.3.16Werkzeug==1.0.1gunicorn==19.5.0flask_cors" }, { "code": null, "e": 3101, "s": 3069, "text": "pip install -r requirements.txt" }, { "code": null, "e": 3488, "s": 3101, "text": "Since you have to access the remote database on Heroku through your flask app, to establish a connection to it, you’d need the database URL. Because the remote database’s URL can change due to many reasons, It is best practice to always fetch the database URL config var from the corresponding Heroku app when your application starts. You can do this by setting an environment variable." }, { "code": null, "e": 3810, "s": 3488, "text": "Since this URL is particular to a particular project which is limited to a particular directory, it wouldn’t make sense to add it to your global environment variables. This is where direnv comes in. It is an environment switcher that allows to load/unload environment variables depending on the present working directory." }, { "code": null, "e": 3977, "s": 3810, "text": "To set the variable for your Flask application you’d have to add the following command to a new file called .envrc and place it in the root directory of your project:" }, { "code": null, "e": 4053, "s": 3977, "text": "export DATABASE_URL=$(heroku config:get DATABASE_URL -a example-app-medium)" }, { "code": null, "e": 4131, "s": 4053, "text": "After creating the .envrc file, run $ direnv allow to activate the variables." }, { "code": null, "e": 4211, "s": 4131, "text": "Here’s some basic config you need in your config.py file in the root directory:" }, { "code": null, "e": 4358, "s": 4211, "text": "import osclass Config(object):SQLALCHEMY_TRACK_MODIFICATIONS = TrueSECRET_KEY = os.urandom(24)SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']" }, { "code": null, "e": 4402, "s": 4358, "text": "Here’s what my folder structure looks like:" }, { "code": null, "e": 4604, "s": 4402, "text": "Flask names an app 'application’ by default, so you’d need an application.py file for the app to run. You can change the name of your app if you want to (using $ export FLASK_APP = ‘your file name'.py)" }, { "code": null, "e": 4694, "s": 4604, "text": "I like putting all Flask related code into a subdirectory called app instead of the root." }, { "code": null, "e": 4724, "s": 4694, "text": "My application.py looks like:" }, { "code": null, "e": 4752, "s": 4724, "text": "from app import application" }, { "code": null, "e": 4893, "s": 4752, "text": "And within the app subdirectory, here’s my __init__.py (initialization script that marks directories on disk as Python package directories):" }, { "code": null, "e": 5206, "s": 4893, "text": "from flask import Flaskfrom config import Configfrom flask_sqlalchemy import SQLAlchemyfrom sqlalchemy import create_engine# Initializationapplication = Flask(__name__)application.config.from_object(Config)DB_URI = application.config['SQLALCHEMY_DATABASE_URI']engine = create_engine(DB_URI)from app import routes" }, { "code": null, "e": 5247, "s": 5206, "text": "The API code lies in the routes.py file." }, { "code": null, "e": 5297, "s": 5247, "text": "To see the full routes.py code, follow this link:" }, { "code": null, "e": 5374, "s": 5297, "text": "https://github.com/aakanksha-ns/flask-heroku-login/blob/master/app/routes.py" }, { "code": null, "e": 5418, "s": 5374, "text": "For a login system, you’d need two methods:" }, { "code": null, "e": 5587, "s": 5418, "text": "This method creates an entry in the account table for a new user. You can do an additional check to make sure the username or email does not already exist in the table." }, { "code": null, "e": 5782, "s": 5587, "text": "Since it’s not safe to store the raw password in a database due to security concerns, you can generate a password hash using the werkzeug library and store the hash instead of the real password." }, { "code": null, "e": 5888, "s": 5782, "text": "This method just checks if the password entered matches with the original password for the given username" }, { "code": null, "e": 5982, "s": 5888, "text": "Once done, you can use $ flask run to start the flask server and test your API using Postman:" }, { "code": null, "e": 6094, "s": 5982, "text": "Procfile is a mechanism for declaring what commands are run by your application’s dynos on the Heroku platform." }, { "code": null, "e": 6334, "s": 6094, "text": "You can use gunicorn that takes care of running multiple instances of your web application, making sure they are healthy and restart them as needed, distributing incoming requests across those instances and communicate with the web server." }, { "code": null, "e": 6372, "s": 6334, "text": "web: gunicorn application:application" }, { "code": null, "e": 6517, "s": 6372, "text": "To deploy the APIs you just created, the easiest way is to push your code to Github repository and connect this repo to your Heroku application:" }, { "code": null, "e": 6850, "s": 6517, "text": "You can set up an automatic deployment or deploy the Flask app manually from the Heroku dashboard. If there are any errors during deployment, they’ll show up in the build log. Once deployed, you can hit the API using Postman and see that it’s working as expected. If there’s an error after deployment, you can view the log this way:" }, { "code": null, "e": 6969, "s": 6850, "text": "In case you’re interested in creating a frontend for your login system, you can check out my React and Redux based UI:" }, { "code": null, "e": 6980, "s": 6969, "text": "github.com" } ]
SQL Tryit Editor v1.6
SELECT * FROM Customers ORDER BY CustomerName ASC; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 24, "s": 0, "text": "SELECT * FROM Customers" }, { "code": null, "e": 51, "s": 24, "text": "ORDER BY CustomerName ASC;" }, { "code": null, "e": 53, "s": 51, "text": "​" }, { "code": null, "e": 116, "s": 53, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 176, "s": 116, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 244, "s": 176, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 282, "s": 244, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 367, "s": 282, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 541, "s": 367, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 592, "s": 541, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 660, "s": 592, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 831, "s": 660, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 931, "s": 831, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 991, "s": 931, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]