title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to run a function when the page is loaded in JavaScript ?
21 Jul, 2021 A function can be executed when the page loaded successfully. This can be used for various purposes like checking for cookies or setting the correct version of the page depending on the user browser. Method 1: Using onload method: The body of a webpage contains the actual content that is to be displayed. The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded. The function that is required to be executed is given here. Syntax: <body onload="functionToBeExecuted"> Example: <!DOCTYPE html><html> <head> <title> How to run a function when the page is loaded in javascript ? </title></head> <body onload="console.log('The Script will load now.')"> <h1 style="color: green">GeeksforGeeks</h1> <b> How to run a function when the page is loaded in javascript ? </b> <p> The script has been executed. Check the console for the output. </p></body> </html> Output:Console Output: Method 2: The window object represents the browser window. The onload property processes load events after the element has finished loading. This is used with the window element to execute a script after the webpage has completely loaded. The function that is required to be executed is assigned as the handler function to this property. It will run the function as soon as the webpage has been loaded. Syntax: window.onload = function exampleFunction() { // Function to be executed} Example: <!DOCTYPE html><html> <head> <title> How to run a function when the page is loaded in javascript ? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to run a function when the page is loaded in javascript? </b> <p> The script has been executed. Check the console for the output. </p> <script> window.onload = function exampleFunction() { console.log('The Script will load now.'); } </script></body> </html> Output:Console Output: 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. Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners 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": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 228, "s": 28, "text": "A function can be executed when the page loaded successfully. This can be used for various purposes like checking for cookies or setting the correct version of the page depending on the user browser." }, { "code": null, "e": 561, "s": 228, "text": "Method 1: Using onload method: The body of a webpage contains the actual content that is to be displayed. The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded. The function that is required to be executed is given here." }, { "code": null, "e": 569, "s": 561, "text": "Syntax:" }, { "code": null, "e": 606, "s": 569, "text": "<body onload=\"functionToBeExecuted\">" }, { "code": null, "e": 615, "s": 606, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to run a function when the page is loaded in javascript ? </title></head> <body onload=\"console.log('The Script will load now.')\"> <h1 style=\"color: green\">GeeksforGeeks</h1> <b> How to run a function when the page is loaded in javascript ? </b> <p> The script has been executed. Check the console for the output. </p></body> </html>", "e": 1074, "s": 615, "text": null }, { "code": null, "e": 1097, "s": 1074, "text": "Output:Console Output:" }, { "code": null, "e": 1500, "s": 1097, "text": "Method 2: The window object represents the browser window. The onload property processes load events after the element has finished loading. This is used with the window element to execute a script after the webpage has completely loaded. The function that is required to be executed is assigned as the handler function to this property. It will run the function as soon as the webpage has been loaded." }, { "code": null, "e": 1508, "s": 1500, "text": "Syntax:" }, { "code": "window.onload = function exampleFunction() { // Function to be executed}", "e": 1586, "s": 1508, "text": null }, { "code": null, "e": 1595, "s": 1586, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to run a function when the page is loaded in javascript ? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to run a function when the page is loaded in javascript? </b> <p> The script has been executed. Check the console for the output. </p> <script> window.onload = function exampleFunction() { console.log('The Script will load now.'); } </script></body> </html>", "e": 2155, "s": 1595, "text": null }, { "code": null, "e": 2178, "s": 2155, "text": "Output:Console Output:" }, { "code": null, "e": 2397, "s": 2178, "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": 2404, "s": 2397, "text": "Picked" }, { "code": null, "e": 2415, "s": 2404, "text": "JavaScript" }, { "code": null, "e": 2432, "s": 2415, "text": "Web Technologies" }, { "code": null, "e": 2459, "s": 2432, "text": "Web technologies Questions" }, { "code": null, "e": 2557, "s": 2459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2618, "s": 2557, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2690, "s": 2618, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2730, "s": 2690, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2772, "s": 2730, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2813, "s": 2772, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2846, "s": 2813, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2908, "s": 2846, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2969, "s": 2908, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3019, "s": 2969, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Convert java.util.Date to java.sql.Date in Java?
17 Jan, 2022 Date class is present in both java.util package and java.sql package. Though the name of the class is the same for both packages, their utilities are different. Date class of java.util package is required when data is required in a java application to do any computation or for other various things, while Date class of java.sql package is used whenever we need to store or read the data of DATE type in SQL, also Date class of java.sql package stores information only regarding the date, whereas Date class of java.util package stores both date and time information. It must be remembered that when we need to convert one data form to another, we must use getTime() method of the Date class of java.util package.Though java.sql.Date class is a subclass of java.util.Date class, we can’t use java.sql.Date class wherever java.util.Date class must be passed, else it will violate the Liskov Substitution principle and our program will throw run time errors on execution, therefore it is not advised to pass SQL Date to methods that expect util date. Let us do discuss getTime() method prior to landing upon the implementation part. The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by the Date object. Syntax: public long getTime() Parameters: The function does not accept any parameter. Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM. Exception: The function does not throw any exceptions. Example: Java // Java Program to Convert java.sql.Date to java.util.Date // Importing utility package// Importing SQL packageimport java.sql.*;import java.util.*; // Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Date class of Util package contains both date and // time information java.util.Date utilPackageDate = new java.util.Date(); // Print and display the utility package date in // java System.out.println("Util Package date in Java is : " + utilPackageDate); // Date class of sql package contains only date // information without time java.sql.Date sqlPackageDate = new java.sql.Date(utilPackageDate.getTime()); // Print and display the SQL java package System.out.println("SQL Package date in Java : " + sqlPackageDate); }} Util Package date in Java is : Wed Mar 17 11:56:06 UTC 2021 SQL Package date in Java : 2021-03-17 Note: The above date and time are fetched at the time program is being compiled and run. It will vary along the passage of time where the baseline for time calculations is epoch time sweetyty Java-Date-Time Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2022" }, { "code": null, "e": 596, "s": 28, "text": "Date class is present in both java.util package and java.sql package. Though the name of the class is the same for both packages, their utilities are different. Date class of java.util package is required when data is required in a java application to do any computation or for other various things, while Date class of java.sql package is used whenever we need to store or read the data of DATE type in SQL, also Date class of java.sql package stores information only regarding the date, whereas Date class of java.util package stores both date and time information." }, { "code": null, "e": 1159, "s": 596, "text": "It must be remembered that when we need to convert one data form to another, we must use getTime() method of the Date class of java.util package.Though java.sql.Date class is a subclass of java.util.Date class, we can’t use java.sql.Date class wherever java.util.Date class must be passed, else it will violate the Liskov Substitution principle and our program will throw run time errors on execution, therefore it is not advised to pass SQL Date to methods that expect util date. Let us do discuss getTime() method prior to landing upon the implementation part." }, { "code": null, "e": 1311, "s": 1159, "text": "The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by the Date object." }, { "code": null, "e": 1319, "s": 1311, "text": "Syntax:" }, { "code": null, "e": 1341, "s": 1319, "text": "public long getTime()" }, { "code": null, "e": 1397, "s": 1341, "text": "Parameters: The function does not accept any parameter." }, { "code": null, "e": 1486, "s": 1397, "text": "Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM." }, { "code": null, "e": 1541, "s": 1486, "text": "Exception: The function does not throw any exceptions." }, { "code": null, "e": 1550, "s": 1541, "text": "Example:" }, { "code": null, "e": 1555, "s": 1550, "text": "Java" }, { "code": "// Java Program to Convert java.sql.Date to java.util.Date // Importing utility package// Importing SQL packageimport java.sql.*;import java.util.*; // Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Date class of Util package contains both date and // time information java.util.Date utilPackageDate = new java.util.Date(); // Print and display the utility package date in // java System.out.println(\"Util Package date in Java is : \" + utilPackageDate); // Date class of sql package contains only date // information without time java.sql.Date sqlPackageDate = new java.sql.Date(utilPackageDate.getTime()); // Print and display the SQL java package System.out.println(\"SQL Package date in Java : \" + sqlPackageDate); }}", "e": 2492, "s": 1555, "text": null }, { "code": null, "e": 2594, "s": 2495, "text": "Util Package date in Java is : Wed Mar 17 11:56:06 UTC 2021\nSQL Package date in Java : 2021-03-17" }, { "code": null, "e": 2777, "s": 2594, "text": "Note: The above date and time are fetched at the time program is being compiled and run. It will vary along the passage of time where the baseline for time calculations is epoch time" }, { "code": null, "e": 2788, "s": 2779, "text": "sweetyty" }, { "code": null, "e": 2803, "s": 2788, "text": "Java-Date-Time" }, { "code": null, "e": 2810, "s": 2803, "text": "Picked" }, { "code": null, "e": 2815, "s": 2810, "text": "Java" }, { "code": null, "e": 2829, "s": 2815, "text": "Java Programs" }, { "code": null, "e": 2834, "s": 2829, "text": "Java" } ]
std::regex_match, std::regex_replace() | Regex (Regular Expression) In C++
04 Jul, 2022 Regex is the short form for “Regular expression”, which is often used in this way in programming languages and many different libraries. It is supported in C++11 onward compilers.Function Templates used in regex regex_match() -This function return true if the regular expression is a match against the given string otherwise it returns false. CPP // C++ program to demonstrate working of regex_match()#include <iostream>#include <regex> using namespace std;int main(){ string a = "GeeksForGeeks"; // Here b is an object of regex (regular expression) regex b("(Geek)(.*)"); // Geek followed by any character // regex_match function matches string a against regex b if ( regex_match(a, b) ) cout << "String 'a' matches regular expression 'b' \n"; // regex_match function for matching a range in string // against regex b if ( regex_match(a.begin(), a.end(), b) ) cout << "String 'a' matches with regular expression " "'b' in the range from 0 to string end\n"; return 0;} String 'a' matches regular expression 'b' String 'a' matches with regular expression 'b' in the range from 0 to string end regex_search() – This function is used to search for a pattern matching the regular expression CPP // C++ program to demonstrate working of regex_search()#include <iostream>#include <regex>#include<string.h>using namespace std; int main(){ // Target sequence string s = "I am looking for GeeksForGeeks " "articles"; // An object of regex for pattern to be searched regex r("Geek[a-zA-Z]+"); // flag type for determining the matching behavior // here it is for matches on 'string' objects smatch m; // regex_search() for searching the regex pattern // 'r' in the string 's'. 'm' is flag for determining // matching behavior. regex_search(s, m, r); // for each loop for (auto x : m) cout << x << " "; return 0;} GeeksForGeeks regex_replace() This function is used to replace the pattern matching to the regular expression with a string. CPP // C++ program to demonstrate working of regex_replace()#include <iostream>#include <string>#include <regex>#include <iterator>using namespace std; int main(){ string s = "I am looking for GeeksForGeek \n"; // matches words beginning by "Geek" regex r("Geek[a-zA-z]+"); // regex_replace() for replacing the match with 'geek' cout << std::regex_replace(s, r, "geek"); string result; // regex_replace( ) for replacing the match with 'geek' regex_replace(back_inserter(result), s.begin(), s.end(), r, "geek"); cout << result; return 0;} I am looking for geek I am looking for geek So Regex operations make use of following parameters : Target sequence (subject) – The string to be matched. Regular Expression (Pattern) – The regular expression for the target sequence. Matched Array – The information about matches is stored in a special match_result array. Replacement String – These string are used for allowing replacement of the matches. This article is contributed by Abhinav Tiwari . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. striver02 hardikkoriintern CPP-Library CPP-regex Microsoft STL C Language C++ Strings Microsoft Strings STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Priority Queue in C++ Standard Template Library (STL) Set in C++ Standard Template Library (STL)
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2022" }, { "code": null, "e": 266, "s": 54, "text": "Regex is the short form for “Regular expression”, which is often used in this way in programming languages and many different libraries. It is supported in C++11 onward compilers.Function Templates used in regex" }, { "code": null, "e": 397, "s": 266, "text": "regex_match() -This function return true if the regular expression is a match against the given string otherwise it returns false." }, { "code": null, "e": 401, "s": 397, "text": "CPP" }, { "code": "// C++ program to demonstrate working of regex_match()#include <iostream>#include <regex> using namespace std;int main(){ string a = \"GeeksForGeeks\"; // Here b is an object of regex (regular expression) regex b(\"(Geek)(.*)\"); // Geek followed by any character // regex_match function matches string a against regex b if ( regex_match(a, b) ) cout << \"String 'a' matches regular expression 'b' \\n\"; // regex_match function for matching a range in string // against regex b if ( regex_match(a.begin(), a.end(), b) ) cout << \"String 'a' matches with regular expression \" \"'b' in the range from 0 to string end\\n\"; return 0;}", "e": 1083, "s": 401, "text": null }, { "code": null, "e": 1208, "s": 1083, "text": "String 'a' matches regular expression 'b' \nString 'a' matches with regular expression 'b' in the range from 0 to string end\n" }, { "code": null, "e": 1304, "s": 1208, "text": "regex_search() – This function is used to search for a pattern matching the regular expression " }, { "code": null, "e": 1308, "s": 1304, "text": "CPP" }, { "code": "// C++ program to demonstrate working of regex_search()#include <iostream>#include <regex>#include<string.h>using namespace std; int main(){ // Target sequence string s = \"I am looking for GeeksForGeeks \" \"articles\"; // An object of regex for pattern to be searched regex r(\"Geek[a-zA-Z]+\"); // flag type for determining the matching behavior // here it is for matches on 'string' objects smatch m; // regex_search() for searching the regex pattern // 'r' in the string 's'. 'm' is flag for determining // matching behavior. regex_search(s, m, r); // for each loop for (auto x : m) cout << x << \" \"; return 0;}", "e": 1987, "s": 1308, "text": null }, { "code": null, "e": 2002, "s": 1987, "text": "GeeksForGeeks " }, { "code": null, "e": 2113, "s": 2002, "text": "regex_replace() This function is used to replace the pattern matching to the regular expression with a string." }, { "code": null, "e": 2117, "s": 2113, "text": "CPP" }, { "code": "// C++ program to demonstrate working of regex_replace()#include <iostream>#include <string>#include <regex>#include <iterator>using namespace std; int main(){ string s = \"I am looking for GeeksForGeek \\n\"; // matches words beginning by \"Geek\" regex r(\"Geek[a-zA-z]+\"); // regex_replace() for replacing the match with 'geek' cout << std::regex_replace(s, r, \"geek\"); string result; // regex_replace( ) for replacing the match with 'geek' regex_replace(back_inserter(result), s.begin(), s.end(), r, \"geek\"); cout << result; return 0;}", "e": 2721, "s": 2117, "text": null }, { "code": null, "e": 2768, "s": 2721, "text": "I am looking for geek \nI am looking for geek \n" }, { "code": null, "e": 2823, "s": 2768, "text": "So Regex operations make use of following parameters :" }, { "code": null, "e": 2877, "s": 2823, "text": "Target sequence (subject) – The string to be matched." }, { "code": null, "e": 2956, "s": 2877, "text": "Regular Expression (Pattern) – The regular expression for the target sequence." }, { "code": null, "e": 3045, "s": 2956, "text": "Matched Array – The information about matches is stored in a special match_result array." }, { "code": null, "e": 3129, "s": 3045, "text": "Replacement String – These string are used for allowing replacement of the matches." }, { "code": null, "e": 3428, "s": 3129, "text": "This article is contributed by Abhinav Tiwari . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3438, "s": 3428, "text": "striver02" }, { "code": null, "e": 3455, "s": 3438, "text": "hardikkoriintern" }, { "code": null, "e": 3467, "s": 3455, "text": "CPP-Library" }, { "code": null, "e": 3477, "s": 3467, "text": "CPP-regex" }, { "code": null, "e": 3487, "s": 3477, "text": "Microsoft" }, { "code": null, "e": 3491, "s": 3487, "text": "STL" }, { "code": null, "e": 3502, "s": 3491, "text": "C Language" }, { "code": null, "e": 3506, "s": 3502, "text": "C++" }, { "code": null, "e": 3514, "s": 3506, "text": "Strings" }, { "code": null, "e": 3524, "s": 3514, "text": "Microsoft" }, { "code": null, "e": 3532, "s": 3524, "text": "Strings" }, { "code": null, "e": 3536, "s": 3532, "text": "STL" }, { "code": null, "e": 3540, "s": 3536, "text": "CPP" }, { "code": null, "e": 3638, "s": 3540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3655, "s": 3638, "text": "Substring in C++" }, { "code": null, "e": 3690, "s": 3655, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 3712, "s": 3690, "text": "Function Pointer in C" }, { "code": null, "e": 3758, "s": 3712, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 3803, "s": 3758, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 3821, "s": 3803, "text": "Vector in C++ STL" }, { "code": null, "e": 3864, "s": 3821, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 3910, "s": 3864, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 3964, "s": 3910, "text": "Priority Queue in C++ Standard Template Library (STL)" } ]
Spring Boot – application.yml/application.yaml File
22 Dec, 2021 Spring is widely used for creating scalable applications. For web applications Spring provides. In Spring Boot, whenever we create a new Spring Boot Application in spring starter, or inside an IDE (Eclipse or STS) a file is located inside the src/main/resources folder named as application.properties file which is shown in the below media: So in a spring boot application, application.properties file is used to write the application-related property into that file. This file contains the different configuration which is required to run the application in a different environment, and each environment will have a different property defined by it. Inside the application properties file, we define every type of property like changing the port, database connectivity, connection to the eureka server, and many more. But sometimes there is another file is located inside the src/main/resources folder named as application.yml/application.yaml file and the code present inside this file is present in a hierarchical format which is shown in the below image: So what’s this application.yml file? YAML stands for Yet Another Markup Language or YAML ain’t markup language (a recursive acronym), which emphasizes that YAML is for data, not documents. YAML is a data serialization language that is often used for writing configuration files. So YAML configuration file in Spring Boot provides a very convenient syntax for storing logging configurations in a hierarchical format. The application.properties file is not that readable. So most of the time developers choose application.yml file over application.properties file. YAML is a superset of JSON, and as such is a very convenient format for specifying hierarchical configuration data. YAML is more readable and it is good for the developers to read/write configuration files. Now let’s see some examples for better understanding via proposing different examples as listed and described later as follows: To Change the Port NumberTo define the name of our applicationConnecting with the MySQL DatabaseConnecting with the H2 DatabaseConnecting with the MongoDB DatabaseConnecting with the Eureka Server To Change the Port Number To define the name of our application Connecting with the MySQL Database Connecting with the H2 Database Connecting with the MongoDB Database Connecting with the Eureka Server Example 1: To Change the Port Number Sometimes when you run your spring application you may encounter the following type of error The error is Port 8989 was already in use. So in this case you may kill that process that is running on this port number or you may change your port number and rerun your application. So where do you have to change your port number? e.g in the application.properties file or in application.yml file. So you can change your port number by the following line server: port: 8082 Example 2: To define the name of our application To define the name of our application you can write the properties like this spring: application: name: userservice So you can see this represents the property as key-value pair here, every key associated with a value also. Example 3: Connecting with the MySQL Database To connect with the MySQL Database you have to write a bunch of lines. You can write the properties like this spring: datasource: driver-class-name: com.mysql.jdbc.Driver username: springuser url: jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example password: ThePassword jpa: hibernate: ddl-auto: update Example 4: Connecting with the H2 Database H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It is generally used in unit testing. It stores data in memory, not persist the data on disk. To connect with the H2 Database you have to write a bunch of lines. You can write the properties like this spring: h2: console: enabled: 'true' datasource: username: sa url: jdbc:h2:mem:dcbapp driverClassName: org.h2.Driver password: password jpa: database-platform: org.hibernate.dialect.H2Dialect Example 5: Connecting with the MongoDB Database To connect with the MongoDB Database you have to write a bunch of lines. You can write the properties like this spring: data: mongodb: database: BookStore port: '27017' host: localhost Example 6: Connecting with the Eureka Server Eureka Server is an application that holds information about all client-service applications. Every Microservice will register into the Eureka server and the Eureka server knows all the client applications running on each port and IP address. Eureka Server is also known as Discovery Server. You can write the properties like this eureka: client: service-url: defaultZone: http://localhost:9096/eureka/ fetch-registry: 'true' register-with-eureka: 'true' instance: hostname: localhost Note: The value written here is sample data. Please write the values as per your requirements. But the keys remain the same. Tip: If you want to convert your application.properties file code to application.yml file then you can google and select some online tool for doing this. Java-Spring-Boot 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 Abstraction in Java HashSet in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Dec, 2021" }, { "code": null, "e": 394, "s": 53, "text": "Spring is widely used for creating scalable applications. For web applications Spring provides. In Spring Boot, whenever we create a new Spring Boot Application in spring starter, or inside an IDE (Eclipse or STS) a file is located inside the src/main/resources folder named as application.properties file which is shown in the below media:" }, { "code": null, "e": 1112, "s": 394, "text": "So in a spring boot application, application.properties file is used to write the application-related property into that file. This file contains the different configuration which is required to run the application in a different environment, and each environment will have a different property defined by it. Inside the application properties file, we define every type of property like changing the port, database connectivity, connection to the eureka server, and many more. But sometimes there is another file is located inside the src/main/resources folder named as application.yml/application.yaml file and the code present inside this file is present in a hierarchical format which is shown in the below image:" }, { "code": null, "e": 1883, "s": 1112, "text": "So what’s this application.yml file? YAML stands for Yet Another Markup Language or YAML ain’t markup language (a recursive acronym), which emphasizes that YAML is for data, not documents. YAML is a data serialization language that is often used for writing configuration files. So YAML configuration file in Spring Boot provides a very convenient syntax for storing logging configurations in a hierarchical format. The application.properties file is not that readable. So most of the time developers choose application.yml file over application.properties file. YAML is a superset of JSON, and as such is a very convenient format for specifying hierarchical configuration data. YAML is more readable and it is good for the developers to read/write configuration files. " }, { "code": null, "e": 2011, "s": 1883, "text": "Now let’s see some examples for better understanding via proposing different examples as listed and described later as follows:" }, { "code": null, "e": 2208, "s": 2011, "text": "To Change the Port NumberTo define the name of our applicationConnecting with the MySQL DatabaseConnecting with the H2 DatabaseConnecting with the MongoDB DatabaseConnecting with the Eureka Server" }, { "code": null, "e": 2234, "s": 2208, "text": "To Change the Port Number" }, { "code": null, "e": 2272, "s": 2234, "text": "To define the name of our application" }, { "code": null, "e": 2307, "s": 2272, "text": "Connecting with the MySQL Database" }, { "code": null, "e": 2339, "s": 2307, "text": "Connecting with the H2 Database" }, { "code": null, "e": 2376, "s": 2339, "text": "Connecting with the MongoDB Database" }, { "code": null, "e": 2410, "s": 2376, "text": "Connecting with the Eureka Server" }, { "code": null, "e": 2447, "s": 2410, "text": "Example 1: To Change the Port Number" }, { "code": null, "e": 2540, "s": 2447, "text": "Sometimes when you run your spring application you may encounter the following type of error" }, { "code": null, "e": 2897, "s": 2540, "text": "The error is Port 8989 was already in use. So in this case you may kill that process that is running on this port number or you may change your port number and rerun your application. So where do you have to change your port number? e.g in the application.properties file or in application.yml file. So you can change your port number by the following line" }, { "code": null, "e": 2922, "s": 2897, "text": "server:\n port:\n 8082" }, { "code": null, "e": 2971, "s": 2922, "text": "Example 2: To define the name of our application" }, { "code": null, "e": 3048, "s": 2971, "text": "To define the name of our application you can write the properties like this" }, { "code": null, "e": 3093, "s": 3048, "text": "spring:\n application:\n name: userservice" }, { "code": null, "e": 3201, "s": 3093, "text": "So you can see this represents the property as key-value pair here, every key associated with a value also." }, { "code": null, "e": 3247, "s": 3201, "text": "Example 3: Connecting with the MySQL Database" }, { "code": null, "e": 3357, "s": 3247, "text": "To connect with the MySQL Database you have to write a bunch of lines. You can write the properties like this" }, { "code": null, "e": 3582, "s": 3357, "text": "spring:\n datasource:\n driver-class-name: com.mysql.jdbc.Driver\n username: springuser\n url: jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example\n password: ThePassword\n jpa:\n hibernate:\n ddl-auto: update" }, { "code": null, "e": 3625, "s": 3582, "text": "Example 4: Connecting with the H2 Database" }, { "code": null, "e": 3980, "s": 3625, "text": "H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It is generally used in unit testing. It stores data in memory, not persist the data on disk. To connect with the H2 Database you have to write a bunch of lines. You can write the properties like this" }, { "code": null, "e": 4208, "s": 3980, "text": "spring:\n h2:\n console:\n enabled: 'true'\n datasource:\n username: sa\n url: jdbc:h2:mem:dcbapp\n driverClassName: org.h2.Driver\n password: password\n jpa:\n database-platform: org.hibernate.dialect.H2Dialect" }, { "code": null, "e": 4256, "s": 4208, "text": "Example 5: Connecting with the MongoDB Database" }, { "code": null, "e": 4368, "s": 4256, "text": "To connect with the MongoDB Database you have to write a bunch of lines. You can write the properties like this" }, { "code": null, "e": 4465, "s": 4368, "text": "spring:\n data:\n mongodb:\n database: BookStore\n port: '27017'\n host: localhost" }, { "code": null, "e": 4510, "s": 4465, "text": "Example 6: Connecting with the Eureka Server" }, { "code": null, "e": 4841, "s": 4510, "text": "Eureka Server is an application that holds information about all client-service applications. Every Microservice will register into the Eureka server and the Eureka server knows all the client applications running on each port and IP address. Eureka Server is also known as Discovery Server. You can write the properties like this" }, { "code": null, "e": 5021, "s": 4841, "text": "eureka:\n client:\n service-url:\n defaultZone: http://localhost:9096/eureka/\n fetch-registry: 'true'\n register-with-eureka: 'true'\n instance:\n hostname: localhost" }, { "code": null, "e": 5147, "s": 5021, "text": "Note: The value written here is sample data. Please write the values as per your requirements. But the keys remain the same. " }, { "code": null, "e": 5302, "s": 5147, "text": "Tip: If you want to convert your application.properties file code to application.yml file then you can google and select some online tool for doing this." }, { "code": null, "e": 5319, "s": 5302, "text": "Java-Spring-Boot" }, { "code": null, "e": 5324, "s": 5319, "text": "Java" }, { "code": null, "e": 5329, "s": 5324, "text": "Java" }, { "code": null, "e": 5427, "s": 5329, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5442, "s": 5427, "text": "Stream In Java" }, { "code": null, "e": 5463, "s": 5442, "text": "Introduction to Java" }, { "code": null, "e": 5484, "s": 5463, "text": "Constructors in Java" }, { "code": null, "e": 5503, "s": 5484, "text": "Exceptions in Java" }, { "code": null, "e": 5520, "s": 5503, "text": "Generics in Java" }, { "code": null, "e": 5550, "s": 5520, "text": "Functional Interfaces in Java" }, { "code": null, "e": 5576, "s": 5550, "text": "Java Programming Examples" }, { "code": null, "e": 5592, "s": 5576, "text": "Strings in Java" }, { "code": null, "e": 5612, "s": 5592, "text": "Abstraction in Java" } ]
Difference between MEAN Stack and MERN Stack
06 Nov, 2020 In the field of web development, full-stack development is playing a vital role. A full-stack development provides a solution for perfect solutions for front-end, back-end, testing, mobile application. In today’s world, the demand for a full-stack developer is rising tremendously. A full-stack developer can take care of the entire design structure of a project. There exist different full-stack development frameworks like MEAN stack and MERN stack. Now let us understand the variations in both of them. MEAN stack: MEAN is an abbreviation that stands for MongoDB, ExpressJS, AngularJS, Node.js. This framework provides quick and easy development of web and mobile applications. The main components of MEAN are as follows- MongoDB: It is used to store the data of back-end applications as JSON files. ExpressJS: It is a back-end application that runs on top of Node.js. AngularJS: It is the front-end framework that runs the code in the browser. NodeJS: It provides runtime system for JavaScript on the back-end web application. One of the prominent advantages of using MEAN stack is that the whole code is in JavaScript. So, it is easy for beginners to explore and learn. Also, its unified offerings can significantly reduce development time and cost. The MEAN stack contains various supporting libraries and reusable modules which deliver a scalable minimum viable product. Working of MEAN stack: The MEAN stack architecture is used to build web applications in JavaScript, and handling JSON, incredibly easy. Angular.js front end: Angular.js is at the top of the MEAN stack. It is a self-styled “JavaScript Framework”. Angular.js allows you to extend your HTML tags with metadata to create dynamic, interactive web experiences in much more powerful ways. Express.js and Node.js Server Tier: Express.js is the next step of MEAN stack, running on a Node.js server. Express.js is a fast, minimalist web framework for Node.js. Express.js has powerful models for URL routing and handling HTTP requests and responses. MongoDB Database Tier: If we need to store any data, then we need a database like MongoDB. JSON documents created in Angular.js front end are sent to the Express.js server, where they are processed and stored directly in MongoDB for later retrieval. MERN stack: MERN is an abbreviation which stands for MongoDB, ExpressJS, ReactJS, Node.js. This framework also provides quick and easy development of web and mobile applications using java as its main component. Main components of MERN are as follows. MongoDB: It is a document-oriented No-SQL data store used to store back-end applications. ExpressJS: It is a layered framework built on top of NodeJS that takes care of the website’s back-end functionality and structure. ReactJS: It is a library that facilitates creating the user interface components of single-page web applications. NodeJS: It is a runtime environment capable of running JavaScript on a machine Working of MERN stack: React.js front end: React.js is at the top of the development stack. It is declarative JavaScript framework for creating dynamic client-side applications. React.js let us build up complex interfaces through simple components, connect them to data on our backend server. Express.js and Node.js server tier: It plays same roles in MERN stack as in the MEAN stack as mentioned above. MongoDB Database tier: It plays the same roles in the MERN stack as in the MEAN stack as mentioned above. Difference between MEAN and MERN stacks: JavaScript-Misc Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Nov, 2020" }, { "code": null, "e": 559, "s": 53, "text": "In the field of web development, full-stack development is playing a vital role. A full-stack development provides a solution for perfect solutions for front-end, back-end, testing, mobile application. In today’s world, the demand for a full-stack developer is rising tremendously. A full-stack developer can take care of the entire design structure of a project. There exist different full-stack development frameworks like MEAN stack and MERN stack. Now let us understand the variations in both of them." }, { "code": null, "e": 778, "s": 559, "text": "MEAN stack: MEAN is an abbreviation that stands for MongoDB, ExpressJS, AngularJS, Node.js. This framework provides quick and easy development of web and mobile applications. The main components of MEAN are as follows-" }, { "code": null, "e": 856, "s": 778, "text": "MongoDB: It is used to store the data of back-end applications as JSON files." }, { "code": null, "e": 925, "s": 856, "text": "ExpressJS: It is a back-end application that runs on top of Node.js." }, { "code": null, "e": 1001, "s": 925, "text": "AngularJS: It is the front-end framework that runs the code in the browser." }, { "code": null, "e": 1084, "s": 1001, "text": "NodeJS: It provides runtime system for JavaScript on the back-end web application." }, { "code": null, "e": 1431, "s": 1084, "text": "One of the prominent advantages of using MEAN stack is that the whole code is in JavaScript. So, it is easy for beginners to explore and learn. Also, its unified offerings can significantly reduce development time and cost. The MEAN stack contains various supporting libraries and reusable modules which deliver a scalable minimum viable product." }, { "code": null, "e": 1567, "s": 1431, "text": "Working of MEAN stack: The MEAN stack architecture is used to build web applications in JavaScript, and handling JSON, incredibly easy." }, { "code": null, "e": 1813, "s": 1567, "text": "Angular.js front end: Angular.js is at the top of the MEAN stack. It is a self-styled “JavaScript Framework”. Angular.js allows you to extend your HTML tags with metadata to create dynamic, interactive web experiences in much more powerful ways." }, { "code": null, "e": 2070, "s": 1813, "text": "Express.js and Node.js Server Tier: Express.js is the next step of MEAN stack, running on a Node.js server. Express.js is a fast, minimalist web framework for Node.js. Express.js has powerful models for URL routing and handling HTTP requests and responses." }, { "code": null, "e": 2320, "s": 2070, "text": "MongoDB Database Tier: If we need to store any data, then we need a database like MongoDB. JSON documents created in Angular.js front end are sent to the Express.js server, where they are processed and stored directly in MongoDB for later retrieval." }, { "code": null, "e": 2572, "s": 2320, "text": "MERN stack: MERN is an abbreviation which stands for MongoDB, ExpressJS, ReactJS, Node.js. This framework also provides quick and easy development of web and mobile applications using java as its main component. Main components of MERN are as follows." }, { "code": null, "e": 2662, "s": 2572, "text": "MongoDB: It is a document-oriented No-SQL data store used to store back-end applications." }, { "code": null, "e": 2793, "s": 2662, "text": "ExpressJS: It is a layered framework built on top of NodeJS that takes care of the website’s back-end functionality and structure." }, { "code": null, "e": 2907, "s": 2793, "text": "ReactJS: It is a library that facilitates creating the user interface components of single-page web applications." }, { "code": null, "e": 2986, "s": 2907, "text": "NodeJS: It is a runtime environment capable of running JavaScript on a machine" }, { "code": null, "e": 3009, "s": 2986, "text": "Working of MERN stack:" }, { "code": null, "e": 3279, "s": 3009, "text": "React.js front end: React.js is at the top of the development stack. It is declarative JavaScript framework for creating dynamic client-side applications. React.js let us build up complex interfaces through simple components, connect them to data on our backend server." }, { "code": null, "e": 3390, "s": 3279, "text": "Express.js and Node.js server tier: It plays same roles in MERN stack as in the MEAN stack as mentioned above." }, { "code": null, "e": 3496, "s": 3390, "text": "MongoDB Database tier: It plays the same roles in the MERN stack as in the MEAN stack as mentioned above." }, { "code": null, "e": 3537, "s": 3496, "text": "Difference between MEAN and MERN stacks:" }, { "code": null, "e": 3553, "s": 3537, "text": "JavaScript-Misc" }, { "code": null, "e": 3570, "s": 3553, "text": "Web Technologies" }, { "code": null, "e": 3597, "s": 3570, "text": "Web technologies Questions" } ]
Stepping Numbers
04 Jul, 2022 Given two integers ‘n’ and ‘m’, find all the stepping numbers in range [n, m]. A number is called stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not. Examples : Input : n = 0, m = 21 Output : 0 1 2 3 4 5 6 7 8 9 10 12 21 Input : n = 10, m = 15 Output : 10, 12 Method 1: Brute force ApproachIn this method, a brute force approach is used to iterate through all the integers from n to m and check if it’s a stepping number. C++ Java Python3 C# Javascript // A C++ program to find all the Stepping Number in [n, m]#include<bits/stdc++.h>using namespace std; // This function checks if an integer n is a Stepping Numberbool isStepNum(int n){ // Initialize prevDigit with -1 int prevDigit = -1; // Iterate through all digits of n and compare difference // between value of previous and current digits while (n) { // Get Current digit int curDigit = n % 10; // Single digit is consider as a // Stepping Number if (prevDigit == -1) prevDigit = curDigit; else { // Check if absolute difference between // prev digit and current digit is 1 if (abs(prevDigit - curDigit) != 1) return false; } prevDigit = curDigit; n /= 10; } return true;} // A brute force approach based function to find all// stepping numbers.void displaySteppingNumbers(int n, int m){ // Iterate through all the numbers from [N,M] // and check if it’s a stepping number. for (int i=n; i<=m; i++) if (isStepNum(i)) cout << i << " ";} // Driver program to test above functionint main(){ int n = 0, m = 21; // Display Stepping Numbers in // the range [n, m] displaySteppingNumbers(n, m); return 0;} // A Java program to find all the Stepping Number in [n, m]class Main{ // This Method checks if an integer n // is a Stepping Number public static boolean isStepNum(int n) { // Initialize prevDigit with -1 int prevDigit = -1; // Iterate through all digits of n and compare // difference between value of previous and // current digits while (n > 0) { // Get Current digit int curDigit = n % 10; // Single digit is consider as a // Stepping Number if (prevDigit != -1) { // Check if absolute difference between // prev digit and current digit is 1 if (Math.abs(curDigit-prevDigit) != 1) return false; } n /= 10; prevDigit = curDigit; } return true; } // A brute force approach based function to find all // stepping numbers. public static void displaySteppingNumbers(int n,int m) { // Iterate through all the numbers from [N,M] // and check if it is a stepping number. for (int i = n; i <= m; i++) if (isStepNum(i)) System.out.print(i+ " "); } // Driver code public static void main(String args[]) { int n = 0, m = 21; // Display Stepping Numbers in the range [n,m] displaySteppingNumbers(n,m); }} # A Python3 program to find all the Stepping Number in [n, m] # This function checks if an integer n is a Stepping Numberdef isStepNum(n): # Initialize prevDigit with -1 prevDigit = -1 # Iterate through all digits of n and compare difference # between value of previous and current digits while (n): # Get Current digit curDigit = n % 10 # Single digit is consider as a # Stepping Number if (prevDigit == -1): prevDigit = curDigit else: # Check if absolute difference between # prev digit and current digit is 1 if (abs(prevDigit - curDigit) != 1): return False prevDigit = curDigit n //= 10 return True # A brute force approach based function to find all# stepping numbers.def displaySteppingNumbers(n, m): # Iterate through all the numbers from [N,M] # and check if it’s a stepping number. for i in range(n, m + 1): if (isStepNum(i)): print(i, end = " ") # Driver codeif __name__ == '__main__': n, m = 0, 21 # Display Stepping Numbers in # the range [n, m] displaySteppingNumbers(n, m) # This code is contributed by mohit kumar 29 // A C# program to find all// the Stepping Number in [n, m]using System; class GFG{ // This Method checks if an // integer n is a Stepping Number public static bool isStepNum(int n) { // Initialize prevDigit with -1 int prevDigit = -1; // Iterate through all digits // of n and compare difference // between value of previous // and current digits while (n > 0) { // Get Current digit int curDigit = n % 10; // Single digit is considered // as a Stepping Number if (prevDigit != -1) { // Check if absolute difference // between prev digit and current // digit is 1 if (Math.Abs(curDigit - prevDigit) != 1) return false; } n /= 10; prevDigit = curDigit; } return true; } // A brute force approach based // function to find all stepping numbers. public static void displaySteppingNumbers(int n, int m) { // Iterate through all the numbers // from [N,M] and check if it is // a stepping number. for (int i = n; i <= m; i++) if (isStepNum(i)) Console.Write(i+ " "); } // Driver code public static void Main() { int n = 0, m = 21; // Display Stepping Numbers // in the range [n,m] displaySteppingNumbers(n, m); }} // This code is contributed by nitin mittal. <script> // A Javascript program to find all the Stepping Number in [n, m] // This function checks if an integer n is a Stepping Number function isStepNum(n) { // Initialize prevDigit with -1 let prevDigit = -1; // Iterate through all digits of n and compare difference // between value of previous and current digits while (n > 0) { // Get Current digit let curDigit = n % 10; // Single digit is consider as a // Stepping Number if (prevDigit == -1) prevDigit = curDigit; else { // Check if absolute difference between // prev digit and current digit is 1 if (Math.abs(prevDigit - curDigit) != 1) return false; } prevDigit = curDigit; n = parseInt(n / 10, 10); } return true; } // A brute force approach based function to find all // stepping numbers. function displaySteppingNumbers(n, m) { // Iterate through all the numbers from [N,M] // and check if it’s a stepping number. for (let i = n; i <= m; i++) if (isStepNum(i)) document.write(i + " "); } let n = 0, m = 21; // Display Stepping Numbers in // the range [n, m] displaySteppingNumbers(n, m); // This code is contributed by mukesh07.</script> 0 1 2 3 4 5 6 7 8 9 10 12 21 Method 2: Using BFS/DFS The idea is to use a Breadth First Search/Depth First Search traversal. How to build the graph? Every node in the graph represents a stepping number; there will be a directed edge from a node U to V if V can be transformed from U. (U and V are Stepping Numbers) A Stepping Number V can be transformed from U in following manner.lastDigit refers to the last digit of U (i.e. U % 10) An adjacent number V can be: U*10 + lastDigit + 1 (Neighbor A) U*10 + lastDigit – 1 (Neighbor B) By applying above operations a new digit is appended to U, it is either lastDigit-1 or lastDigit+1, so that the new number V formed from U is also a Stepping Number. Therefore, every Node will have at most 2 neighboring Nodes.Edge Cases: When the last digit of U is 0 or 9 Case 1: lastDigit is 0 : In this case only digit ‘1’ can be appended. Case 2: lastDigit is 9 : In this case only digit ‘8’ can be appended. What will be the source/starting Node? Every single digit number is considered as a stepping Number, so bfs traversal for every digit will give all the stepping numbers starting from that digit. Do a bfs/dfs traversal for all the numbers from [0,9]. Note: For node 0, no need to explore neighbors during BFS traversal since it will lead to 01, 012, 010 and these will be covered by the BFS traversal starting from node 1. Example to find all the stepping numbers from 0 to 21 -> 0 is a stepping Number and it is in the range so display it. -> 1 is a Stepping Number, find neighbors of 1 i.e., 10 and 12 and push them into the queue How to get 10 and 12? Here U is 1 and last Digit is also 1 V = 10 + 0 = 10 ( Adding lastDigit - 1 ) V = 10 + 2 = 12 ( Adding lastDigit + 1 ) Then do the same for 10 and 12 this will result into 101, 123, 121 but these Numbers are out of range. Now any number transformed from 10 and 12 will result into a number greater than 21 so no need to explore their neighbors. -> 2 is a Stepping Number, find neighbors of 2 i.e. 21, 23. -> 23 is out of range so it is not considered as a Stepping Number (Or a neighbor of 2) The other stepping numbers will be 3, 4, 5, 6, 7, 8, 9. BFS based Solution: C++ Java Python3 C# Javascript // A C++ program to find all the Stepping Number from N=n// to m using BFS Approach#include<bits/stdc++.h>using namespace std; // Prints all stepping numbers reachable from num// and in range [n, m]void bfs(int n, int m, int num){ // Queue will contain all the stepping Numbers queue<int> q; q.push(num); while (!q.empty()) { // Get the front element and pop from the queue int stepNum = q.front(); q.pop(); // If the Stepping Number is in the range // [n, m] then display if (stepNum <= m && stepNum >= n) cout << stepNum << " "; // If Stepping Number is 0 or greater than m, // no need to explore the neighbors if (num == 0 || stepNum > m) continue; // Get the last digit of the currently visited // Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit to be // appended is lastDigit + 1 or lastDigit - 1 int stepNumA = stepNum * 10 + (lastDigit- 1); int stepNumB = stepNum * 10 + (lastDigit + 1); // If lastDigit is 0 then only possible digit // after 0 can be 1 for a Stepping Number if (lastDigit == 0) q.push(stepNumB); //If lastDigit is 9 then only possible //digit after 9 can be 8 for a Stepping //Number else if (lastDigit == 9) q.push(stepNumA); else { q.push(stepNumA); q.push(stepNumB); } }} // Prints all stepping numbers in range [n, m]// using BFS.void displaySteppingNumbers(int n, int m){ // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) bfs(n, m, i);} //Driver program to test above functionint main(){ int n = 0, m = 21; // Display Stepping Numbers in the // range [n,m] displaySteppingNumbers(n,m); return 0;} // A Java program to find all the Stepping Number in// range [n, m]import java.util.*; class Main{ // Prints all stepping numbers reachable from num // and in range [n, m] public static void bfs(int n,int m,int num) { // Queue will contain all the stepping Numbers Queue<Integer> q = new LinkedList<Integer> (); q.add(num); while (!q.isEmpty()) { // Get the front element and pop from // the queue int stepNum = q.poll(); // If the Stepping Number is in // the range [n,m] then display if (stepNum <= m && stepNum >= n) { System.out.print(stepNum + " "); } // If Stepping Number is 0 or greater // then m, no need to explore the neighbors if (stepNum == 0 || stepNum > m) continue; // Get the last digit of the currently // visited Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 int stepNumA = stepNum * 10 + (lastDigit- 1); int stepNumB = stepNum * 10 + (lastDigit + 1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) q.add(stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if (lastDigit == 9) q.add(stepNumA); else { q.add(stepNumA); q.add(stepNumB); } } } // Prints all stepping numbers in range [n, m] // using BFS. public static void displaySteppingNumbers(int n,int m) { // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) bfs(n, m, i); } //Driver code public static void main(String args[]) { int n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); }} # A Python3 program to find all the Stepping Number from N=n# to m using BFS Approach # Prints all stepping numbers reachable from num# and in range [n, m]def bfs(n, m, num) : # Queue will contain all the stepping Numbers q = [] q.append(num) while len(q) > 0 : # Get the front element and pop from the queue stepNum = q[0] q.pop(0); # If the Stepping Number is in the range # [n, m] then display if (stepNum <= m and stepNum >= n) : print(stepNum, end = " ") # If Stepping Number is 0 or greater than m, # no need to explore the neighbors if (num == 0 or stepNum > m) : continue # Get the last digit of the currently visited # Stepping Number lastDigit = stepNum % 10 # There can be 2 cases either digit to be # appended is lastDigit + 1 or lastDigit - 1 stepNumA = stepNum * 10 + (lastDigit- 1) stepNumB = stepNum * 10 + (lastDigit + 1) # If lastDigit is 0 then only possible digit # after 0 can be 1 for a Stepping Number if (lastDigit == 0) : q.append(stepNumB) #If lastDigit is 9 then only possible #digit after 9 can be 8 for a Stepping #Number elif (lastDigit == 9) : q.append(stepNumA) else : q.append(stepNumA) q.append(stepNumB) # Prints all stepping numbers in range [n, m]# using BFS.def displaySteppingNumbers(n, m) : # For every single digit Number 'i' # find all the Stepping Numbers # starting with i for i in range(10) : bfs(n, m, i) # Driver coden, m = 0, 21 # Display Stepping Numbers in the# range [n,m]displaySteppingNumbers(n, m) # This code is contributed by divyeshrabadiya07. // A C# program to find all the Stepping Number in// range [n, m]using System;using System.Collections.Generic;public class GFG{ // Prints all stepping numbers reachable from num // and in range [n, m] static void bfs(int n, int m, int num) { // Queue will contain all the stepping Numbers Queue<int> q = new Queue<int>(); q.Enqueue(num); while(q.Count != 0) { // Get the front element and pop from // the queue int stepNum = q.Dequeue(); // If the Stepping Number is in // the range [n,m] then display if (stepNum <= m && stepNum >= n) { Console.Write(stepNum + " "); } // If Stepping Number is 0 or greater // then m, no need to explore the neighbors if (stepNum == 0 || stepNum > m) continue; // Get the last digit of the currently // visited Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 int stepNumA = stepNum * 10 + (lastDigit- 1); int stepNumB = stepNum * 10 + (lastDigit + 1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) q.Enqueue(stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if (lastDigit == 9) q.Enqueue(stepNumA); else { q.Enqueue(stepNumA); q.Enqueue(stepNumB); } } } // Prints all stepping numbers in range [n, m] // using BFS. static void displaySteppingNumbers(int n,int m) { // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) bfs(n, m, i); } // Driver code static public void Main () { int n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); }} // This code is contributed by avanitrachhadiya2155 <script> // A Javascript program to find all// the Stepping Number in// range [n, m] // Prints all stepping numbers // reachable from num // and in range [n, m] function bfs(n,m,num) { // Queue will contain all the // stepping Numbers let q = []; q.push(num); while (q.length!=0) { // Get the front element and pop from // the queue let stepNum = q.shift(); // If the Stepping Number is in // the range [n,m] then display if (stepNum <= m && stepNum >= n) { document.write(stepNum + " "); } // If Stepping Number is 0 or greater // then m, no need to explore the neighbors if (stepNum == 0 || stepNum > m) continue; // Get the last digit of the currently // visited Stepping Number let lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 let stepNumA = stepNum * 10 + (lastDigit- 1); let stepNumB = stepNum * 10 + (lastDigit + 1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) q.push(stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if (lastDigit == 9) q.push(stepNumA); else { q.push(stepNumA); q.push(stepNumB); } } } // Prints all stepping numbers in range [n, m] // using BFS. function displaySteppingNumbers(n,m) { // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (let i = 0 ; i <= 9 ; i++) bfs(n, m, i); } // Driver code let n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); // This code is contributed by unknown2108 </script> 0 1 10 12 2 21 3 4 5 6 7 8 9 DFS based Solution: C++ Java Python3 C# Javascript // A C++ program to find all the Stepping Numbers// in range [n, m] using DFS Approach#include<bits/stdc++.h>using namespace std; // Prints all stepping numbers reachable from num// and in range [n, m]void dfs(int n, int m, int stepNum){ // If Stepping Number is in the // range [n,m] then display if (stepNum <= m && stepNum >= n) cout << stepNum << " "; // If Stepping Number is 0 or greater // than m, then return if (stepNum == 0 || stepNum > m) return ; // Get the last digit of the currently // visited Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 int stepNumA = stepNum*10 + (lastDigit-1); int stepNumB = stepNum*10 + (lastDigit+1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) dfs(n, m, stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if(lastDigit == 9) dfs(n, m, stepNumA); else { dfs(n, m, stepNumA); dfs(n, m, stepNumB); }} // Method displays all the stepping// numbers in range [n, m]void displaySteppingNumbers(int n, int m){ // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) dfs(n, m, i);} //Driver program to test above functionint main(){ int n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); return 0;} // A Java program to find all the Stepping Numbers// in range [n, m] using DFS Approachimport java.util.*; class Main{ // Method display's all the stepping numbers // in range [n, m] public static void dfs(int n,int m,int stepNum) { // If Stepping Number is in the // range [n,m] then display if (stepNum <= m && stepNum >= n) System.out.print(stepNum + " "); // If Stepping Number is 0 or greater // than m then return if (stepNum == 0 || stepNum > m) return ; // Get the last digit of the currently // visited Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 int stepNumA = stepNum*10 + (lastDigit-1); int stepNumB = stepNum*10 + (lastDigit+1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) dfs(n, m, stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if(lastDigit == 9) dfs(n, m, stepNumA); else { dfs(n, m, stepNumA); dfs(n, m, stepNumB); } } // Prints all stepping numbers in range [n, m] // using DFS. public static void displaySteppingNumbers(int n, int m) { // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) dfs(n, m, i); } // Driver code public static void main(String args[]) { int n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); }} # A Python3 program to find all the Stepping Numbers# in range [n, m] using DFS Approach # Prints all stepping numbers reachable from num# and in range [n, m]def dfs(n, m, stepNum) : # If Stepping Number is in the # range [n,m] then display if (stepNum <= m and stepNum >= n) : print(stepNum, end = " ") # If Stepping Number is 0 or greater # than m, then return if (stepNum == 0 or stepNum > m) : return # Get the last digit of the currently # visited Stepping Number lastDigit = stepNum % 10 # There can be 2 cases either digit # to be appended is lastDigit + 1 or # lastDigit - 1 stepNumA = stepNum * 10 + (lastDigit - 1) stepNumB = stepNum * 10 + (lastDigit + 1) # If lastDigit is 0 then only possible # digit after 0 can be 1 for a Stepping # Number if (lastDigit == 0) : dfs(n, m, stepNumB) # If lastDigit is 9 then only possible # digit after 9 can be 8 for a Stepping # Number elif(lastDigit == 9) : dfs(n, m, stepNumA) else : dfs(n, m, stepNumA) dfs(n, m, stepNumB) # Method displays all the stepping# numbers in range [n, m]def displaySteppingNumbers(n, m) : # For every single digit Number 'i' # find all the Stepping Numbers # starting with i for i in range(10) : dfs(n, m, i) n, m = 0, 21 # Display Stepping Numbers in# the range [n,m]displaySteppingNumbers(n, m) # This code is contributed by divyesh072019. // A C# program to find all the Stepping Numbers// in range [n, m] using DFS Approachusing System;public class GFG{ // Method display's all the stepping numbers // in range [n, m] static void dfs(int n, int m, int stepNum) { // If Stepping Number is in the // range [n,m] then display if (stepNum <= m && stepNum >= n) Console.Write(stepNum + " "); // If Stepping Number is 0 or greater // than m then return if (stepNum == 0 || stepNum > m) return ; // Get the last digit of the currently // visited Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 int stepNumA = stepNum*10 + (lastDigit - 1); int stepNumB = stepNum*10 + (lastDigit + 1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) dfs(n, m, stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if(lastDigit == 9) dfs(n, m, stepNumA); else { dfs(n, m, stepNumA); dfs(n, m, stepNumB); } } // Prints all stepping numbers in range [n, m] // using DFS. public static void displaySteppingNumbers(int n, int m) { // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) dfs(n, m, i); } // Driver code static public void Main () { int n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); }} // This code is contributed by rag2127. <script> // A Javascript program to find all the Stepping Numbers// in range [n, m] using DFS Approach // Method display's all the stepping numbers // in range [n, m]function dfs(n, m, stepNum){ // If Stepping Number is in the // range [n,m] then display if (stepNum <= m && stepNum >= n) document.write(stepNum + " "); // If Stepping Number is 0 or greater // than m then return if (stepNum == 0 || stepNum > m) return ; // Get the last digit of the currently // visited Stepping Number let lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 let stepNumA = stepNum*10 + (lastDigit-1); let stepNumB = stepNum*10 + (lastDigit+1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) dfs(n, m, stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if(lastDigit == 9) dfs(n, m, stepNumA); else { dfs(n, m, stepNumA); dfs(n, m, stepNumB); }} // Prints all stepping numbers in range [n, m] // using DFS.function displaySteppingNumbers(n, m){ // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (let i = 0 ; i <= 9 ; i++) dfs(n, m, i);} // Driver codelet n = 0, m = 21; // Display Stepping Numbers in// the range [n,m]displaySteppingNumbers(n,m); // This code is contributed by ab2127</script> 0 1 10 12 2 21 3 4 5 6 7 8 9 This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. nitin mittal mohit kumar 29 parasmadan15 avanitrachhadiya2155 rag2127 divyeshrabadiya07 divyesh072019 mukesh07 unknown2108 simmytarika5 ab2127 hardikkoriintern Amazon BFS DFS Graph Amazon DFS Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2022" }, { "code": null, "e": 266, "s": 52, "text": "Given two integers ‘n’ and ‘m’, find all the stepping numbers in range [n, m]. A number is called stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not." }, { "code": null, "e": 278, "s": 266, "text": "Examples : " }, { "code": null, "e": 378, "s": 278, "text": "Input : n = 0, m = 21\nOutput : 0 1 2 3 4 5 6 7 8 9 10 12 21\n\nInput : n = 10, m = 15\nOutput : 10, 12" }, { "code": null, "e": 541, "s": 378, "text": "Method 1: Brute force ApproachIn this method, a brute force approach is used to iterate through all the integers from n to m and check if it’s a stepping number. " }, { "code": null, "e": 545, "s": 541, "text": "C++" }, { "code": null, "e": 550, "s": 545, "text": "Java" }, { "code": null, "e": 558, "s": 550, "text": "Python3" }, { "code": null, "e": 561, "s": 558, "text": "C#" }, { "code": null, "e": 572, "s": 561, "text": "Javascript" }, { "code": "// A C++ program to find all the Stepping Number in [n, m]#include<bits/stdc++.h>using namespace std; // This function checks if an integer n is a Stepping Numberbool isStepNum(int n){ // Initialize prevDigit with -1 int prevDigit = -1; // Iterate through all digits of n and compare difference // between value of previous and current digits while (n) { // Get Current digit int curDigit = n % 10; // Single digit is consider as a // Stepping Number if (prevDigit == -1) prevDigit = curDigit; else { // Check if absolute difference between // prev digit and current digit is 1 if (abs(prevDigit - curDigit) != 1) return false; } prevDigit = curDigit; n /= 10; } return true;} // A brute force approach based function to find all// stepping numbers.void displaySteppingNumbers(int n, int m){ // Iterate through all the numbers from [N,M] // and check if it’s a stepping number. for (int i=n; i<=m; i++) if (isStepNum(i)) cout << i << \" \";} // Driver program to test above functionint main(){ int n = 0, m = 21; // Display Stepping Numbers in // the range [n, m] displaySteppingNumbers(n, m); return 0;}", "e": 1876, "s": 572, "text": null }, { "code": "// A Java program to find all the Stepping Number in [n, m]class Main{ // This Method checks if an integer n // is a Stepping Number public static boolean isStepNum(int n) { // Initialize prevDigit with -1 int prevDigit = -1; // Iterate through all digits of n and compare // difference between value of previous and // current digits while (n > 0) { // Get Current digit int curDigit = n % 10; // Single digit is consider as a // Stepping Number if (prevDigit != -1) { // Check if absolute difference between // prev digit and current digit is 1 if (Math.abs(curDigit-prevDigit) != 1) return false; } n /= 10; prevDigit = curDigit; } return true; } // A brute force approach based function to find all // stepping numbers. public static void displaySteppingNumbers(int n,int m) { // Iterate through all the numbers from [N,M] // and check if it is a stepping number. for (int i = n; i <= m; i++) if (isStepNum(i)) System.out.print(i+ \" \"); } // Driver code public static void main(String args[]) { int n = 0, m = 21; // Display Stepping Numbers in the range [n,m] displaySteppingNumbers(n,m); }}", "e": 3314, "s": 1876, "text": null }, { "code": "# A Python3 program to find all the Stepping Number in [n, m] # This function checks if an integer n is a Stepping Numberdef isStepNum(n): # Initialize prevDigit with -1 prevDigit = -1 # Iterate through all digits of n and compare difference # between value of previous and current digits while (n): # Get Current digit curDigit = n % 10 # Single digit is consider as a # Stepping Number if (prevDigit == -1): prevDigit = curDigit else: # Check if absolute difference between # prev digit and current digit is 1 if (abs(prevDigit - curDigit) != 1): return False prevDigit = curDigit n //= 10 return True # A brute force approach based function to find all# stepping numbers.def displaySteppingNumbers(n, m): # Iterate through all the numbers from [N,M] # and check if it’s a stepping number. for i in range(n, m + 1): if (isStepNum(i)): print(i, end = \" \") # Driver codeif __name__ == '__main__': n, m = 0, 21 # Display Stepping Numbers in # the range [n, m] displaySteppingNumbers(n, m) # This code is contributed by mohit kumar 29", "e": 4546, "s": 3314, "text": null }, { "code": "// A C# program to find all// the Stepping Number in [n, m]using System; class GFG{ // This Method checks if an // integer n is a Stepping Number public static bool isStepNum(int n) { // Initialize prevDigit with -1 int prevDigit = -1; // Iterate through all digits // of n and compare difference // between value of previous // and current digits while (n > 0) { // Get Current digit int curDigit = n % 10; // Single digit is considered // as a Stepping Number if (prevDigit != -1) { // Check if absolute difference // between prev digit and current // digit is 1 if (Math.Abs(curDigit - prevDigit) != 1) return false; } n /= 10; prevDigit = curDigit; } return true; } // A brute force approach based // function to find all stepping numbers. public static void displaySteppingNumbers(int n, int m) { // Iterate through all the numbers // from [N,M] and check if it is // a stepping number. for (int i = n; i <= m; i++) if (isStepNum(i)) Console.Write(i+ \" \"); } // Driver code public static void Main() { int n = 0, m = 21; // Display Stepping Numbers // in the range [n,m] displaySteppingNumbers(n, m); }} // This code is contributed by nitin mittal.", "e": 6150, "s": 4546, "text": null }, { "code": "<script> // A Javascript program to find all the Stepping Number in [n, m] // This function checks if an integer n is a Stepping Number function isStepNum(n) { // Initialize prevDigit with -1 let prevDigit = -1; // Iterate through all digits of n and compare difference // between value of previous and current digits while (n > 0) { // Get Current digit let curDigit = n % 10; // Single digit is consider as a // Stepping Number if (prevDigit == -1) prevDigit = curDigit; else { // Check if absolute difference between // prev digit and current digit is 1 if (Math.abs(prevDigit - curDigit) != 1) return false; } prevDigit = curDigit; n = parseInt(n / 10, 10); } return true; } // A brute force approach based function to find all // stepping numbers. function displaySteppingNumbers(n, m) { // Iterate through all the numbers from [N,M] // and check if it’s a stepping number. for (let i = n; i <= m; i++) if (isStepNum(i)) document.write(i + \" \"); } let n = 0, m = 21; // Display Stepping Numbers in // the range [n, m] displaySteppingNumbers(n, m); // This code is contributed by mukesh07.</script>", "e": 7608, "s": 6150, "text": null }, { "code": null, "e": 7638, "s": 7608, "text": "0 1 2 3 4 5 6 7 8 9 10 12 21 " }, { "code": null, "e": 7662, "s": 7638, "text": "Method 2: Using BFS/DFS" }, { "code": null, "e": 7734, "s": 7662, "text": "The idea is to use a Breadth First Search/Depth First Search traversal." }, { "code": null, "e": 8075, "s": 7734, "text": "How to build the graph? Every node in the graph represents a stepping number; there will be a directed edge from a node U to V if V can be transformed from U. (U and V are Stepping Numbers) A Stepping Number V can be transformed from U in following manner.lastDigit refers to the last digit of U (i.e. U % 10) An adjacent number V can be: " }, { "code": null, "e": 8109, "s": 8075, "text": "U*10 + lastDigit + 1 (Neighbor A)" }, { "code": null, "e": 8143, "s": 8109, "text": "U*10 + lastDigit – 1 (Neighbor B)" }, { "code": null, "e": 8416, "s": 8143, "text": "By applying above operations a new digit is appended to U, it is either lastDigit-1 or lastDigit+1, so that the new number V formed from U is also a Stepping Number. Therefore, every Node will have at most 2 neighboring Nodes.Edge Cases: When the last digit of U is 0 or 9" }, { "code": null, "e": 8486, "s": 8416, "text": "Case 1: lastDigit is 0 : In this case only digit ‘1’ can be appended." }, { "code": null, "e": 8556, "s": 8486, "text": "Case 2: lastDigit is 9 : In this case only digit ‘8’ can be appended." }, { "code": null, "e": 8597, "s": 8556, "text": "What will be the source/starting Node? " }, { "code": null, "e": 8753, "s": 8597, "text": "Every single digit number is considered as a stepping Number, so bfs traversal for every digit will give all the stepping numbers starting from that digit." }, { "code": null, "e": 8808, "s": 8753, "text": "Do a bfs/dfs traversal for all the numbers from [0,9]." }, { "code": null, "e": 9036, "s": 8808, "text": "Note: For node 0, no need to explore neighbors during BFS traversal since it will lead to 01, 012, 010 and these will be covered by the BFS traversal starting from node 1. Example to find all the stepping numbers from 0 to 21 " }, { "code": null, "e": 9784, "s": 9036, "text": "-> 0 is a stepping Number and it is in the range\n so display it.\n-> 1 is a Stepping Number, find neighbors of 1 i.e.,\n 10 and 12 and push them into the queue\n\nHow to get 10 and 12?\nHere U is 1 and last Digit is also 1 \nV = 10 + 0 = 10 ( Adding lastDigit - 1 )\nV = 10 + 2 = 12 ( Adding lastDigit + 1 )\n\nThen do the same for 10 and 12 this will result into\n101, 123, 121 but these Numbers are out of range. \nNow any number transformed from 10 and 12 will result\ninto a number greater than 21 so no need to explore \ntheir neighbors.\n\n-> 2 is a Stepping Number, find neighbors of 2 i.e. \n 21, 23.\n-> 23 is out of range so it is not considered as a \n Stepping Number (Or a neighbor of 2)\n\nThe other stepping numbers will be 3, 4, 5, 6, 7, 8, 9." }, { "code": null, "e": 9804, "s": 9784, "text": "BFS based Solution:" }, { "code": null, "e": 9808, "s": 9804, "text": "C++" }, { "code": null, "e": 9813, "s": 9808, "text": "Java" }, { "code": null, "e": 9821, "s": 9813, "text": "Python3" }, { "code": null, "e": 9824, "s": 9821, "text": "C#" }, { "code": null, "e": 9835, "s": 9824, "text": "Javascript" }, { "code": "// A C++ program to find all the Stepping Number from N=n// to m using BFS Approach#include<bits/stdc++.h>using namespace std; // Prints all stepping numbers reachable from num// and in range [n, m]void bfs(int n, int m, int num){ // Queue will contain all the stepping Numbers queue<int> q; q.push(num); while (!q.empty()) { // Get the front element and pop from the queue int stepNum = q.front(); q.pop(); // If the Stepping Number is in the range // [n, m] then display if (stepNum <= m && stepNum >= n) cout << stepNum << \" \"; // If Stepping Number is 0 or greater than m, // no need to explore the neighbors if (num == 0 || stepNum > m) continue; // Get the last digit of the currently visited // Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit to be // appended is lastDigit + 1 or lastDigit - 1 int stepNumA = stepNum * 10 + (lastDigit- 1); int stepNumB = stepNum * 10 + (lastDigit + 1); // If lastDigit is 0 then only possible digit // after 0 can be 1 for a Stepping Number if (lastDigit == 0) q.push(stepNumB); //If lastDigit is 9 then only possible //digit after 9 can be 8 for a Stepping //Number else if (lastDigit == 9) q.push(stepNumA); else { q.push(stepNumA); q.push(stepNumB); } }} // Prints all stepping numbers in range [n, m]// using BFS.void displaySteppingNumbers(int n, int m){ // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) bfs(n, m, i);} //Driver program to test above functionint main(){ int n = 0, m = 21; // Display Stepping Numbers in the // range [n,m] displaySteppingNumbers(n,m); return 0;}", "e": 11778, "s": 9835, "text": null }, { "code": "// A Java program to find all the Stepping Number in// range [n, m]import java.util.*; class Main{ // Prints all stepping numbers reachable from num // and in range [n, m] public static void bfs(int n,int m,int num) { // Queue will contain all the stepping Numbers Queue<Integer> q = new LinkedList<Integer> (); q.add(num); while (!q.isEmpty()) { // Get the front element and pop from // the queue int stepNum = q.poll(); // If the Stepping Number is in // the range [n,m] then display if (stepNum <= m && stepNum >= n) { System.out.print(stepNum + \" \"); } // If Stepping Number is 0 or greater // then m, no need to explore the neighbors if (stepNum == 0 || stepNum > m) continue; // Get the last digit of the currently // visited Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 int stepNumA = stepNum * 10 + (lastDigit- 1); int stepNumB = stepNum * 10 + (lastDigit + 1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) q.add(stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if (lastDigit == 9) q.add(stepNumA); else { q.add(stepNumA); q.add(stepNumB); } } } // Prints all stepping numbers in range [n, m] // using BFS. public static void displaySteppingNumbers(int n,int m) { // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) bfs(n, m, i); } //Driver code public static void main(String args[]) { int n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); }}", "e": 14042, "s": 11778, "text": null }, { "code": "# A Python3 program to find all the Stepping Number from N=n# to m using BFS Approach # Prints all stepping numbers reachable from num# and in range [n, m]def bfs(n, m, num) : # Queue will contain all the stepping Numbers q = [] q.append(num) while len(q) > 0 : # Get the front element and pop from the queue stepNum = q[0] q.pop(0); # If the Stepping Number is in the range # [n, m] then display if (stepNum <= m and stepNum >= n) : print(stepNum, end = \" \") # If Stepping Number is 0 or greater than m, # no need to explore the neighbors if (num == 0 or stepNum > m) : continue # Get the last digit of the currently visited # Stepping Number lastDigit = stepNum % 10 # There can be 2 cases either digit to be # appended is lastDigit + 1 or lastDigit - 1 stepNumA = stepNum * 10 + (lastDigit- 1) stepNumB = stepNum * 10 + (lastDigit + 1) # If lastDigit is 0 then only possible digit # after 0 can be 1 for a Stepping Number if (lastDigit == 0) : q.append(stepNumB) #If lastDigit is 9 then only possible #digit after 9 can be 8 for a Stepping #Number elif (lastDigit == 9) : q.append(stepNumA) else : q.append(stepNumA) q.append(stepNumB) # Prints all stepping numbers in range [n, m]# using BFS.def displaySteppingNumbers(n, m) : # For every single digit Number 'i' # find all the Stepping Numbers # starting with i for i in range(10) : bfs(n, m, i) # Driver coden, m = 0, 21 # Display Stepping Numbers in the# range [n,m]displaySteppingNumbers(n, m) # This code is contributed by divyeshrabadiya07.", "e": 15830, "s": 14042, "text": null }, { "code": "// A C# program to find all the Stepping Number in// range [n, m]using System;using System.Collections.Generic;public class GFG{ // Prints all stepping numbers reachable from num // and in range [n, m] static void bfs(int n, int m, int num) { // Queue will contain all the stepping Numbers Queue<int> q = new Queue<int>(); q.Enqueue(num); while(q.Count != 0) { // Get the front element and pop from // the queue int stepNum = q.Dequeue(); // If the Stepping Number is in // the range [n,m] then display if (stepNum <= m && stepNum >= n) { Console.Write(stepNum + \" \"); } // If Stepping Number is 0 or greater // then m, no need to explore the neighbors if (stepNum == 0 || stepNum > m) continue; // Get the last digit of the currently // visited Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 int stepNumA = stepNum * 10 + (lastDigit- 1); int stepNumB = stepNum * 10 + (lastDigit + 1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) q.Enqueue(stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if (lastDigit == 9) q.Enqueue(stepNumA); else { q.Enqueue(stepNumA); q.Enqueue(stepNumB); } } } // Prints all stepping numbers in range [n, m] // using BFS. static void displaySteppingNumbers(int n,int m) { // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) bfs(n, m, i); } // Driver code static public void Main () { int n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); }} // This code is contributed by avanitrachhadiya2155", "e": 18248, "s": 15830, "text": null }, { "code": "<script> // A Javascript program to find all// the Stepping Number in// range [n, m] // Prints all stepping numbers // reachable from num // and in range [n, m] function bfs(n,m,num) { // Queue will contain all the // stepping Numbers let q = []; q.push(num); while (q.length!=0) { // Get the front element and pop from // the queue let stepNum = q.shift(); // If the Stepping Number is in // the range [n,m] then display if (stepNum <= m && stepNum >= n) { document.write(stepNum + \" \"); } // If Stepping Number is 0 or greater // then m, no need to explore the neighbors if (stepNum == 0 || stepNum > m) continue; // Get the last digit of the currently // visited Stepping Number let lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 let stepNumA = stepNum * 10 + (lastDigit- 1); let stepNumB = stepNum * 10 + (lastDigit + 1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) q.push(stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if (lastDigit == 9) q.push(stepNumA); else { q.push(stepNumA); q.push(stepNumB); } } } // Prints all stepping numbers in range [n, m] // using BFS. function displaySteppingNumbers(n,m) { // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (let i = 0 ; i <= 9 ; i++) bfs(n, m, i); } // Driver code let n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); // This code is contributed by unknown2108 </script>", "e": 20475, "s": 18248, "text": null }, { "code": null, "e": 20505, "s": 20475, "text": "0 1 10 12 2 21 3 4 5 6 7 8 9 " }, { "code": null, "e": 20525, "s": 20505, "text": "DFS based Solution:" }, { "code": null, "e": 20529, "s": 20525, "text": "C++" }, { "code": null, "e": 20534, "s": 20529, "text": "Java" }, { "code": null, "e": 20542, "s": 20534, "text": "Python3" }, { "code": null, "e": 20545, "s": 20542, "text": "C#" }, { "code": null, "e": 20556, "s": 20545, "text": "Javascript" }, { "code": "// A C++ program to find all the Stepping Numbers// in range [n, m] using DFS Approach#include<bits/stdc++.h>using namespace std; // Prints all stepping numbers reachable from num// and in range [n, m]void dfs(int n, int m, int stepNum){ // If Stepping Number is in the // range [n,m] then display if (stepNum <= m && stepNum >= n) cout << stepNum << \" \"; // If Stepping Number is 0 or greater // than m, then return if (stepNum == 0 || stepNum > m) return ; // Get the last digit of the currently // visited Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 int stepNumA = stepNum*10 + (lastDigit-1); int stepNumB = stepNum*10 + (lastDigit+1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) dfs(n, m, stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if(lastDigit == 9) dfs(n, m, stepNumA); else { dfs(n, m, stepNumA); dfs(n, m, stepNumB); }} // Method displays all the stepping// numbers in range [n, m]void displaySteppingNumbers(int n, int m){ // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) dfs(n, m, i);} //Driver program to test above functionint main(){ int n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); return 0;}", "e": 22165, "s": 20556, "text": null }, { "code": "// A Java program to find all the Stepping Numbers// in range [n, m] using DFS Approachimport java.util.*; class Main{ // Method display's all the stepping numbers // in range [n, m] public static void dfs(int n,int m,int stepNum) { // If Stepping Number is in the // range [n,m] then display if (stepNum <= m && stepNum >= n) System.out.print(stepNum + \" \"); // If Stepping Number is 0 or greater // than m then return if (stepNum == 0 || stepNum > m) return ; // Get the last digit of the currently // visited Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 int stepNumA = stepNum*10 + (lastDigit-1); int stepNumB = stepNum*10 + (lastDigit+1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) dfs(n, m, stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if(lastDigit == 9) dfs(n, m, stepNumA); else { dfs(n, m, stepNumA); dfs(n, m, stepNumB); } } // Prints all stepping numbers in range [n, m] // using DFS. public static void displaySteppingNumbers(int n, int m) { // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) dfs(n, m, i); } // Driver code public static void main(String args[]) { int n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); }}", "e": 23992, "s": 22165, "text": null }, { "code": "# A Python3 program to find all the Stepping Numbers# in range [n, m] using DFS Approach # Prints all stepping numbers reachable from num# and in range [n, m]def dfs(n, m, stepNum) : # If Stepping Number is in the # range [n,m] then display if (stepNum <= m and stepNum >= n) : print(stepNum, end = \" \") # If Stepping Number is 0 or greater # than m, then return if (stepNum == 0 or stepNum > m) : return # Get the last digit of the currently # visited Stepping Number lastDigit = stepNum % 10 # There can be 2 cases either digit # to be appended is lastDigit + 1 or # lastDigit - 1 stepNumA = stepNum * 10 + (lastDigit - 1) stepNumB = stepNum * 10 + (lastDigit + 1) # If lastDigit is 0 then only possible # digit after 0 can be 1 for a Stepping # Number if (lastDigit == 0) : dfs(n, m, stepNumB) # If lastDigit is 9 then only possible # digit after 9 can be 8 for a Stepping # Number elif(lastDigit == 9) : dfs(n, m, stepNumA) else : dfs(n, m, stepNumA) dfs(n, m, stepNumB) # Method displays all the stepping# numbers in range [n, m]def displaySteppingNumbers(n, m) : # For every single digit Number 'i' # find all the Stepping Numbers # starting with i for i in range(10) : dfs(n, m, i) n, m = 0, 21 # Display Stepping Numbers in# the range [n,m]displaySteppingNumbers(n, m) # This code is contributed by divyesh072019.", "e": 25478, "s": 23992, "text": null }, { "code": "// A C# program to find all the Stepping Numbers// in range [n, m] using DFS Approachusing System;public class GFG{ // Method display's all the stepping numbers // in range [n, m] static void dfs(int n, int m, int stepNum) { // If Stepping Number is in the // range [n,m] then display if (stepNum <= m && stepNum >= n) Console.Write(stepNum + \" \"); // If Stepping Number is 0 or greater // than m then return if (stepNum == 0 || stepNum > m) return ; // Get the last digit of the currently // visited Stepping Number int lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 int stepNumA = stepNum*10 + (lastDigit - 1); int stepNumB = stepNum*10 + (lastDigit + 1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) dfs(n, m, stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if(lastDigit == 9) dfs(n, m, stepNumA); else { dfs(n, m, stepNumA); dfs(n, m, stepNumB); } } // Prints all stepping numbers in range [n, m] // using DFS. public static void displaySteppingNumbers(int n, int m) { // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (int i = 0 ; i <= 9 ; i++) dfs(n, m, i); } // Driver code static public void Main () { int n = 0, m = 21; // Display Stepping Numbers in // the range [n,m] displaySteppingNumbers(n,m); }} // This code is contributed by rag2127.", "e": 27127, "s": 25478, "text": null }, { "code": "<script> // A Javascript program to find all the Stepping Numbers// in range [n, m] using DFS Approach // Method display's all the stepping numbers // in range [n, m]function dfs(n, m, stepNum){ // If Stepping Number is in the // range [n,m] then display if (stepNum <= m && stepNum >= n) document.write(stepNum + \" \"); // If Stepping Number is 0 or greater // than m then return if (stepNum == 0 || stepNum > m) return ; // Get the last digit of the currently // visited Stepping Number let lastDigit = stepNum % 10; // There can be 2 cases either digit // to be appended is lastDigit + 1 or // lastDigit - 1 let stepNumA = stepNum*10 + (lastDigit-1); let stepNumB = stepNum*10 + (lastDigit+1); // If lastDigit is 0 then only possible // digit after 0 can be 1 for a Stepping // Number if (lastDigit == 0) dfs(n, m, stepNumB); // If lastDigit is 9 then only possible // digit after 9 can be 8 for a Stepping // Number else if(lastDigit == 9) dfs(n, m, stepNumA); else { dfs(n, m, stepNumA); dfs(n, m, stepNumB); }} // Prints all stepping numbers in range [n, m] // using DFS.function displaySteppingNumbers(n, m){ // For every single digit Number 'i' // find all the Stepping Numbers // starting with i for (let i = 0 ; i <= 9 ; i++) dfs(n, m, i);} // Driver codelet n = 0, m = 21; // Display Stepping Numbers in// the range [n,m]displaySteppingNumbers(n,m); // This code is contributed by ab2127</script>", "e": 28824, "s": 27127, "text": null }, { "code": null, "e": 28854, "s": 28824, "text": "0 1 10 12 2 21 3 4 5 6 7 8 9 " }, { "code": null, "e": 29153, "s": 28854, "text": "This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 29166, "s": 29153, "text": "nitin mittal" }, { "code": null, "e": 29181, "s": 29166, "text": "mohit kumar 29" }, { "code": null, "e": 29194, "s": 29181, "text": "parasmadan15" }, { "code": null, "e": 29215, "s": 29194, "text": "avanitrachhadiya2155" }, { "code": null, "e": 29223, "s": 29215, "text": "rag2127" }, { "code": null, "e": 29241, "s": 29223, "text": "divyeshrabadiya07" }, { "code": null, "e": 29255, "s": 29241, "text": "divyesh072019" }, { "code": null, "e": 29264, "s": 29255, "text": "mukesh07" }, { "code": null, "e": 29276, "s": 29264, "text": "unknown2108" }, { "code": null, "e": 29289, "s": 29276, "text": "simmytarika5" }, { "code": null, "e": 29296, "s": 29289, "text": "ab2127" }, { "code": null, "e": 29313, "s": 29296, "text": "hardikkoriintern" }, { "code": null, "e": 29320, "s": 29313, "text": "Amazon" }, { "code": null, "e": 29324, "s": 29320, "text": "BFS" }, { "code": null, "e": 29328, "s": 29324, "text": "DFS" }, { "code": null, "e": 29334, "s": 29328, "text": "Graph" }, { "code": null, "e": 29341, "s": 29334, "text": "Amazon" }, { "code": null, "e": 29345, "s": 29341, "text": "DFS" }, { "code": null, "e": 29351, "s": 29345, "text": "Graph" }, { "code": null, "e": 29355, "s": 29351, "text": "BFS" } ]
How to reverse a Vector using STL in C++?
30 May, 2021 Given a vector, reverse this vector using STL in C++.Example: Input: vec = {1, 45, 54, 71, 76, 12} Output: {12, 76, 71, 54, 45, 1} Input: vec = {1, 7, 5, 4, 6, 12} Output: {12, 6, 4, 5, 7, 1} Approach: Reversing can be done with the help of reverse() function provided in STL. The Time complexity of the reverse() is O(n) where n is the length of the string.Syntax: reverse(start_index, last_index); CPP // C++ program to reverse Vector// using reverse() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout << "Vector: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; // Reverse the vector reverse(a.begin(), a.end()); // Print the reversed vector cout << "Reversed Vector: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; return 0;} Vector: 1 45 54 71 76 12 Reversed Vector: 12 76 71 54 45 1 Time Complexity: O(n) where n is the length of the string. CoderSaty cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ Substring in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Inheritance in C++ Object Oriented Programming in C++ C++ Classes and Objects Sorting a vector in C++
[ { "code": null, "e": 53, "s": 25, "text": "\n30 May, 2021" }, { "code": null, "e": 117, "s": 53, "text": "Given a vector, reverse this vector using STL in C++.Example: " }, { "code": null, "e": 248, "s": 117, "text": "Input: vec = {1, 45, 54, 71, 76, 12}\nOutput: {12, 76, 71, 54, 45, 1}\n\nInput: vec = {1, 7, 5, 4, 6, 12}\nOutput: {12, 6, 4, 5, 7, 1}" }, { "code": null, "e": 423, "s": 248, "text": "Approach: Reversing can be done with the help of reverse() function provided in STL. The Time complexity of the reverse() is O(n) where n is the length of the string.Syntax: " }, { "code": null, "e": 457, "s": 423, "text": "reverse(start_index, last_index);" }, { "code": null, "e": 461, "s": 457, "text": "CPP" }, { "code": "// C++ program to reverse Vector// using reverse() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout << \"Vector: \"; for (int i = 0; i < a.size(); i++) cout << a[i] << \" \"; cout << endl; // Reverse the vector reverse(a.begin(), a.end()); // Print the reversed vector cout << \"Reversed Vector: \"; for (int i = 0; i < a.size(); i++) cout << a[i] << \" \"; cout << endl; return 0;}", "e": 995, "s": 461, "text": null }, { "code": null, "e": 1055, "s": 995, "text": "Vector: 1 45 54 71 76 12 \nReversed Vector: 12 76 71 54 45 1" }, { "code": null, "e": 1116, "s": 1057, "text": "Time Complexity: O(n) where n is the length of the string." }, { "code": null, "e": 1126, "s": 1116, "text": "CoderSaty" }, { "code": null, "e": 1137, "s": 1126, "text": "cpp-vector" }, { "code": null, "e": 1141, "s": 1137, "text": "STL" }, { "code": null, "e": 1145, "s": 1141, "text": "C++" }, { "code": null, "e": 1149, "s": 1145, "text": "STL" }, { "code": null, "e": 1153, "s": 1149, "text": "CPP" }, { "code": null, "e": 1251, "s": 1153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1278, "s": 1251, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 1321, "s": 1278, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 1355, "s": 1321, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1372, "s": 1355, "text": "Substring in C++" }, { "code": null, "e": 1397, "s": 1372, "text": "unordered_map in C++ STL" }, { "code": null, "e": 1451, "s": 1397, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1470, "s": 1451, "text": "Inheritance in C++" }, { "code": null, "e": 1505, "s": 1470, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 1529, "s": 1505, "text": "C++ Classes and Objects" } ]
How to append data to <div> element using JavaScript ?
11 Oct, 2019 To append the data to <div> element we have to use DOM(Document Object Model) manipulation techniques. The approach is to create a empty <div> with an id inside the HTML skeleton. Then that id will be used to fetch that <div> and then we will manipulate the inner text of that div. Syntax: document.getElementById("div_name").innerText += "Your Data Here"; Example: <!DOCTYPE html> <html> <head> <title> How to append data to div using JavaScript ? </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <hr> <form> <div class="form-group"> <label for="">Enter Your Name:</label> <input id="name" class="form-control" type="text" placeholder="Input Your Name Here"> </div> <div class="form-group text-center"> <button id="my_button" class="btn btn-outline-success btn-lg" type="button"> Add Name </button> </div> </form> <h3>List of Names:</h3> <div id="my_div"></div> </div> <script> function append_to_div(div_name, data){ document.getElementById(div_name).innerText += data; } document.getElementById("my_button") .addEventListener('click', function() { var user_name = document.getElementById("name"); var value = user_name.value.trim(); if(!value) alert("Name Cannot be empty!"); else append_to_div("my_div", value+"\n"); user_name.value = ""; }); </script> </body> </html> Output: Before Adding the Data: After Adding the Data: Picked JavaScript Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Oct, 2019" }, { "code": null, "e": 336, "s": 54, "text": "To append the data to <div> element we have to use DOM(Document Object Model) manipulation techniques. The approach is to create a empty <div> with an id inside the HTML skeleton. Then that id will be used to fetch that <div> and then we will manipulate the inner text of that div." }, { "code": null, "e": 344, "s": 336, "text": "Syntax:" }, { "code": null, "e": 411, "s": 344, "text": "document.getElementById(\"div_name\").innerText += \"Your Data Here\";" }, { "code": null, "e": 420, "s": 411, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> How to append data to div using JavaScript ? </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> </head> <body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <hr> <form> <div class=\"form-group\"> <label for=\"\">Enter Your Name:</label> <input id=\"name\" class=\"form-control\" type=\"text\" placeholder=\"Input Your Name Here\"> </div> <div class=\"form-group text-center\"> <button id=\"my_button\" class=\"btn btn-outline-success btn-lg\" type=\"button\"> Add Name </button> </div> </form> <h3>List of Names:</h3> <div id=\"my_div\"></div> </div> <script> function append_to_div(div_name, data){ document.getElementById(div_name).innerText += data; } document.getElementById(\"my_button\") .addEventListener('click', function() { var user_name = document.getElementById(\"name\"); var value = user_name.value.trim(); if(!value) alert(\"Name Cannot be empty!\"); else append_to_div(\"my_div\", value+\"\\n\"); user_name.value = \"\"; }); </script> </body> </html>", "e": 2186, "s": 420, "text": null }, { "code": null, "e": 2194, "s": 2186, "text": "Output:" }, { "code": null, "e": 2218, "s": 2194, "text": "Before Adding the Data:" }, { "code": null, "e": 2241, "s": 2218, "text": "After Adding the Data:" }, { "code": null, "e": 2248, "s": 2241, "text": "Picked" }, { "code": null, "e": 2259, "s": 2248, "text": "JavaScript" }, { "code": null, "e": 2278, "s": 2259, "text": "Technical Scripter" }, { "code": null, "e": 2295, "s": 2278, "text": "Web Technologies" }, { "code": null, "e": 2322, "s": 2295, "text": "Web technologies Questions" } ]
Minimize absolute difference between the smallest and largest array elements by minimum increment decrement operations
19 Jul, 2021 Given an array arr[] consisting of N positive integers, the task is to minimize the number of operations required to minimize the absolute difference between the smallest and largest elements present in the array. In each operation, subtract 1 from an array element and increment 1 to another array element. Examples: Input: arr[] = {1, 6}Output: 2Explanation:Below are the operations performed:Operation 1: Subtracting 1 from 2nd element and adding 1 to 1st element modifies the array to {2, 5}.Operation2: Subtracting 1 from 2nd element and adding 1 to 1st element modifies the array to {3, 4}.After the above operations, the absolute difference between the minimum and the maximum element is (4 – 3) = 1, which is minimum and number of operation required is 2. Input: arr[] = {1, 2, 2, 1, 1}Output: 0 Approach: The given problem can be solved by observing the fact that increment and decrement of an array element by 1 are performed in pairs so if the sum of the array element is divisible by N then all array elements can be made sum/N. Otherwise, some elements will have the value sum/N, and some elements will have value (sum/N + 1) after performing the given operations. Follow the steps below to solve the given problem: Initialize an auxiliary array, say final[] that stores the resultant array having the required minimum difference. Sort the given array in increasing order. Traverse the given array and if the current index i is less than sum%N, then update the current element of the final array to the value (sum/N + 1). Otherwise, update final[i] to (sum/N). Reverse the array final[]. Initialize a variable, say ans = 0 that stores the minimum number of operations to convert arr[] to final[]. Traverse both the arrays arr[] and final[] simultaneously and add the absolute value of the difference of arr[i] and final[i] to the variable ans. After completing the above steps, print the value of ans/2 as the resultant minimum operation. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to minimize the operations// for the difference between minimum// and maximum element by incrementing// decrementing array elements in pairsvoid countMinimumSteps(int arr[], int N){ // Stores the sum of the array int sum = 0; // Find the sum of array element for (int i = 0; i < N; i++) { sum += arr[i]; } // Stores the resultant final array int finalArray[N]; // Iterate over the range [0, N] for (int i = 0; i < N; ++i) { // Assign values to finalArray if (i < sum % N) { finalArray[i] = sum / N + 1; } else { finalArray[i] = sum / N; } } // Reverse the final array reverse(finalArray, finalArray + N); // Stores the minimum number of // operations required int ans = 0; // Update the value of ans for (int i = 0; i < N; ++i) { ans += abs(arr[i] - finalArray[i]); } // Print the result cout << ans / 2;} // Driver Codeint main(){ int arr[] = { 1, 6 }; int N = sizeof(arr) / sizeof(arr[0]); countMinimumSteps(arr, N); return 0;} // Java program for the above approachclass GFG{ static void reverse(int a[], int n){ int i, k, t; for(i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; }} // Function to minimize the operations// for the difference between minimum// and maximum element by incrementing// decrementing array elements in pairsstatic void countMinimumSteps(int arr[], int N){ // Stores the sum of the array int sum = 0; // Find the sum of array element for(int i = 0; i < N; i++) { sum += arr[i]; } // Stores the resultant final array int finalArray[] = new int[N]; // Iterate over the range [0, N] for(int i = 0; i < N; ++i) { // Assign values to finalArray if (i < sum % N) { finalArray[i] = sum / N + 1; } else { finalArray[i] = sum / N; } } // Reverse the final array reverse(finalArray, finalArray.length); // Stores the minimum number of // operations required int ans = 0; // Update the value of ans for(int i = 0; i < N; ++i) { ans += Math.abs(arr[i] - finalArray[i]); } // Print the result System.out.println(ans / 2);} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 6 }; int N = arr.length; countMinimumSteps(arr, N);}} // This code is contributed by abhinavjain194 # Python program for the above approach # Function to minimize the operations# for the difference between minimum# and maximum element by incrementing# decrementing array elements in pairsdef countMinimumSteps(arr, N): # Stores the sum of the array sum = 0; # Find the sum of array element for i in range(N): sum += arr[i]; # Stores the resultant final array finalArray = [0] * N; # Iterate over the range [0, N] for i in range(0, N): #print(i) # Assign values to finalArray if (i < sum % N): finalArray[i] = (sum // N)+ 1; else: finalArray[i] = sum // N; # Reverse the final array finalArray = finalArray[::-1]; # Stores the minimum number of # operations required ans = 0; # Update the value of ans for i in range(N): ans += abs(arr[i] - finalArray[i]); # Print the result print(ans // 2); # Driver Codearr = [1, 6];N = len(arr);countMinimumSteps(arr, N); # This code is contributed by _saurabh_jaiswal. // C# program for the above approachusing System; class GFG{ static void reverse(int[] a, int n){ int i, t; for(i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; }} // Function to minimize the operations// for the difference between minimum// and maximum element by incrementing// decrementing array elements in pairsstatic void countMinimumSteps(int[] arr, int N){ // Stores the sum of the array int sum = 0; // Find the sum of array element for(int i = 0; i < N; i++) { sum += arr[i]; } // Stores the resultant final array int[] finalArray = new int[N]; // Iterate over the range [0, N] for(int i = 0; i < N; ++i) { // Assign values to finalArray if (i < sum % N) { finalArray[i] = sum / N + 1; } else { finalArray[i] = sum / N; } } // Reverse the final array reverse(finalArray, finalArray.Length); // Stores the minimum number of // operations required int ans = 0; // Update the value of ans for(int i = 0; i < N; ++i) { ans += Math.Abs(arr[i] - finalArray[i]); } // Print the result Console.WriteLine(ans / 2);} // Driver Codepublic static void Main(String[] args){ int[] arr = { 1, 6 }; int N = arr.Length; countMinimumSteps(arr, N);}} // This code is contributed by target_2 <script> // Javascript program for the above approach // Function to minimize the operations// for the difference between minimum// and maximum element by incrementing// decrementing array elements in pairsfunction countMinimumSteps(arr, N){ // Stores the sum of the array let sum = 0; // Find the sum of array element for (let i = 0; i < N; i++) { sum += arr[i]; } // Stores the resultant final array let finalArray = new Array(N); // Iterate over the range [0, N] for (let i = 0; i < N; ++i) { // Assign values to finalArray if (i < sum % N) { finalArray[i] = Math.floor(sum / N + 1); } else { finalArray[i] = Math.floor(sum / N); } } // Reverse the final array finalArray.reverse(); // Stores the minimum number of // operations required let ans = 0; // Update the value of ans for (let i = 0; i < N; ++i) { ans += Math.abs(arr[i] - finalArray[i]); } // Print the result document.write(Math.floor(ans / 2));} // Driver Codelet arr = [1, 6];let N = arr.lengthcountMinimumSteps(arr, N); // This code is contributed by _saurabh_jaiswal.</script> 2 Time Complexity: O(N*log N)Auxiliary Space: O(N) abhinavjain194 _saurabh_jaiswal target_2 array-rearrange Arrays Mathematical Sorting Arrays Mathematical Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Search, insert and delete in an unsorted array Window Sliding Technique Longest Consecutive Subsequence Chocolate Distribution Problem Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jul, 2021" }, { "code": null, "e": 336, "s": 28, "text": "Given an array arr[] consisting of N positive integers, the task is to minimize the number of operations required to minimize the absolute difference between the smallest and largest elements present in the array. In each operation, subtract 1 from an array element and increment 1 to another array element." }, { "code": null, "e": 346, "s": 336, "text": "Examples:" }, { "code": null, "e": 792, "s": 346, "text": "Input: arr[] = {1, 6}Output: 2Explanation:Below are the operations performed:Operation 1: Subtracting 1 from 2nd element and adding 1 to 1st element modifies the array to {2, 5}.Operation2: Subtracting 1 from 2nd element and adding 1 to 1st element modifies the array to {3, 4}.After the above operations, the absolute difference between the minimum and the maximum element is (4 – 3) = 1, which is minimum and number of operation required is 2." }, { "code": null, "e": 832, "s": 792, "text": "Input: arr[] = {1, 2, 2, 1, 1}Output: 0" }, { "code": null, "e": 1257, "s": 832, "text": "Approach: The given problem can be solved by observing the fact that increment and decrement of an array element by 1 are performed in pairs so if the sum of the array element is divisible by N then all array elements can be made sum/N. Otherwise, some elements will have the value sum/N, and some elements will have value (sum/N + 1) after performing the given operations. Follow the steps below to solve the given problem:" }, { "code": null, "e": 1372, "s": 1257, "text": "Initialize an auxiliary array, say final[] that stores the resultant array having the required minimum difference." }, { "code": null, "e": 1414, "s": 1372, "text": "Sort the given array in increasing order." }, { "code": null, "e": 1602, "s": 1414, "text": "Traverse the given array and if the current index i is less than sum%N, then update the current element of the final array to the value (sum/N + 1). Otherwise, update final[i] to (sum/N)." }, { "code": null, "e": 1629, "s": 1602, "text": "Reverse the array final[]." }, { "code": null, "e": 1738, "s": 1629, "text": "Initialize a variable, say ans = 0 that stores the minimum number of operations to convert arr[] to final[]." }, { "code": null, "e": 1885, "s": 1738, "text": "Traverse both the arrays arr[] and final[] simultaneously and add the absolute value of the difference of arr[i] and final[i] to the variable ans." }, { "code": null, "e": 1980, "s": 1885, "text": "After completing the above steps, print the value of ans/2 as the resultant minimum operation." }, { "code": null, "e": 2031, "s": 1980, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2035, "s": 2031, "text": "C++" }, { "code": null, "e": 2040, "s": 2035, "text": "Java" }, { "code": null, "e": 2048, "s": 2040, "text": "Python3" }, { "code": null, "e": 2051, "s": 2048, "text": "C#" }, { "code": null, "e": 2062, "s": 2051, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to minimize the operations// for the difference between minimum// and maximum element by incrementing// decrementing array elements in pairsvoid countMinimumSteps(int arr[], int N){ // Stores the sum of the array int sum = 0; // Find the sum of array element for (int i = 0; i < N; i++) { sum += arr[i]; } // Stores the resultant final array int finalArray[N]; // Iterate over the range [0, N] for (int i = 0; i < N; ++i) { // Assign values to finalArray if (i < sum % N) { finalArray[i] = sum / N + 1; } else { finalArray[i] = sum / N; } } // Reverse the final array reverse(finalArray, finalArray + N); // Stores the minimum number of // operations required int ans = 0; // Update the value of ans for (int i = 0; i < N; ++i) { ans += abs(arr[i] - finalArray[i]); } // Print the result cout << ans / 2;} // Driver Codeint main(){ int arr[] = { 1, 6 }; int N = sizeof(arr) / sizeof(arr[0]); countMinimumSteps(arr, N); return 0;}", "e": 3239, "s": 2062, "text": null }, { "code": "// Java program for the above approachclass GFG{ static void reverse(int a[], int n){ int i, k, t; for(i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; }} // Function to minimize the operations// for the difference between minimum// and maximum element by incrementing// decrementing array elements in pairsstatic void countMinimumSteps(int arr[], int N){ // Stores the sum of the array int sum = 0; // Find the sum of array element for(int i = 0; i < N; i++) { sum += arr[i]; } // Stores the resultant final array int finalArray[] = new int[N]; // Iterate over the range [0, N] for(int i = 0; i < N; ++i) { // Assign values to finalArray if (i < sum % N) { finalArray[i] = sum / N + 1; } else { finalArray[i] = sum / N; } } // Reverse the final array reverse(finalArray, finalArray.length); // Stores the minimum number of // operations required int ans = 0; // Update the value of ans for(int i = 0; i < N; ++i) { ans += Math.abs(arr[i] - finalArray[i]); } // Print the result System.out.println(ans / 2);} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 6 }; int N = arr.length; countMinimumSteps(arr, N);}} // This code is contributed by abhinavjain194", "e": 4666, "s": 3239, "text": null }, { "code": "# Python program for the above approach # Function to minimize the operations# for the difference between minimum# and maximum element by incrementing# decrementing array elements in pairsdef countMinimumSteps(arr, N): # Stores the sum of the array sum = 0; # Find the sum of array element for i in range(N): sum += arr[i]; # Stores the resultant final array finalArray = [0] * N; # Iterate over the range [0, N] for i in range(0, N): #print(i) # Assign values to finalArray if (i < sum % N): finalArray[i] = (sum // N)+ 1; else: finalArray[i] = sum // N; # Reverse the final array finalArray = finalArray[::-1]; # Stores the minimum number of # operations required ans = 0; # Update the value of ans for i in range(N): ans += abs(arr[i] - finalArray[i]); # Print the result print(ans // 2); # Driver Codearr = [1, 6];N = len(arr);countMinimumSteps(arr, N); # This code is contributed by _saurabh_jaiswal.", "e": 5697, "s": 4666, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ static void reverse(int[] a, int n){ int i, t; for(i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; }} // Function to minimize the operations// for the difference between minimum// and maximum element by incrementing// decrementing array elements in pairsstatic void countMinimumSteps(int[] arr, int N){ // Stores the sum of the array int sum = 0; // Find the sum of array element for(int i = 0; i < N; i++) { sum += arr[i]; } // Stores the resultant final array int[] finalArray = new int[N]; // Iterate over the range [0, N] for(int i = 0; i < N; ++i) { // Assign values to finalArray if (i < sum % N) { finalArray[i] = sum / N + 1; } else { finalArray[i] = sum / N; } } // Reverse the final array reverse(finalArray, finalArray.Length); // Stores the minimum number of // operations required int ans = 0; // Update the value of ans for(int i = 0; i < N; ++i) { ans += Math.Abs(arr[i] - finalArray[i]); } // Print the result Console.WriteLine(ans / 2);} // Driver Codepublic static void Main(String[] args){ int[] arr = { 1, 6 }; int N = arr.Length; countMinimumSteps(arr, N);}} // This code is contributed by target_2", "e": 7126, "s": 5697, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to minimize the operations// for the difference between minimum// and maximum element by incrementing// decrementing array elements in pairsfunction countMinimumSteps(arr, N){ // Stores the sum of the array let sum = 0; // Find the sum of array element for (let i = 0; i < N; i++) { sum += arr[i]; } // Stores the resultant final array let finalArray = new Array(N); // Iterate over the range [0, N] for (let i = 0; i < N; ++i) { // Assign values to finalArray if (i < sum % N) { finalArray[i] = Math.floor(sum / N + 1); } else { finalArray[i] = Math.floor(sum / N); } } // Reverse the final array finalArray.reverse(); // Stores the minimum number of // operations required let ans = 0; // Update the value of ans for (let i = 0; i < N; ++i) { ans += Math.abs(arr[i] - finalArray[i]); } // Print the result document.write(Math.floor(ans / 2));} // Driver Codelet arr = [1, 6];let N = arr.lengthcountMinimumSteps(arr, N); // This code is contributed by _saurabh_jaiswal.</script>", "e": 8312, "s": 7126, "text": null }, { "code": null, "e": 8314, "s": 8312, "text": "2" }, { "code": null, "e": 8365, "s": 8316, "text": "Time Complexity: O(N*log N)Auxiliary Space: O(N)" }, { "code": null, "e": 8380, "s": 8365, "text": "abhinavjain194" }, { "code": null, "e": 8397, "s": 8380, "text": "_saurabh_jaiswal" }, { "code": null, "e": 8406, "s": 8397, "text": "target_2" }, { "code": null, "e": 8422, "s": 8406, "text": "array-rearrange" }, { "code": null, "e": 8429, "s": 8422, "text": "Arrays" }, { "code": null, "e": 8442, "s": 8429, "text": "Mathematical" }, { "code": null, "e": 8450, "s": 8442, "text": "Sorting" }, { "code": null, "e": 8457, "s": 8450, "text": "Arrays" }, { "code": null, "e": 8470, "s": 8457, "text": "Mathematical" }, { "code": null, "e": 8478, "s": 8470, "text": "Sorting" }, { "code": null, "e": 8576, "s": 8478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8608, "s": 8576, "text": "Introduction to Data Structures" }, { "code": null, "e": 8655, "s": 8608, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 8680, "s": 8655, "text": "Window Sliding Technique" }, { "code": null, "e": 8712, "s": 8680, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 8743, "s": 8712, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 8773, "s": 8743, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 8816, "s": 8773, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 8876, "s": 8816, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 8891, "s": 8876, "text": "C++ Data Types" } ]
Pythagorean Triplet in an array
21 Jun, 2022 Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2. Example: Input: arr[] = {3, 1, 4, 6, 5} Output: True There is a Pythagorean triplet (3, 4, 5). Input: arr[] = {10, 4, 6, 12, 5} Output: False There is no Pythagorean triplet. Method 1 (Naive) A simple solution is to run three loops, three loops pick three array elements, and check if the current three elements form a Pythagorean Triplet. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Below is the implementation of the above idea : C++ Java Python3 C# PHP Javascript // A C++ program that returns true if there is a Pythagorean// Triplet in a given array.#include <iostream> using namespace std; // Returns true if there is Pythagorean triplet in ar[0..n-1]bool isTriplet(int ar[], int n){ for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Calculate square of array elements int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k]; if (x == y + z || y == x + z || z == x + y) return true; } } } // If we reach here, no triplet found return false;} /* Driver program to test above function */int main(){ int ar[] = { 3, 1, 4, 6, 5 }; int ar_size = sizeof(ar) / sizeof(ar[0]); isTriplet(ar, ar_size) ? cout << "Yes" : cout << "No"; return 0;} // A Java program that returns true if there is a Pythagorean// Triplet in a given array.import java.io.*; class PythagoreanTriplet { // Returns true if there is Pythagorean triplet in ar[0..n-1] static boolean isTriplet(int ar[], int n) { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Calculate square of array elements int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k]; if (x == y + z || y == x + z || z == x + y) return true; } } } // If we reach here, no triplet found return false; } // Driver program to test above function public static void main(String[] args) { int ar[] = { 3, 1, 4, 6, 5 }; int ar_size = ar.length; if (isTriplet(ar, ar_size) == true) System.out.println("Yes"); else System.out.println("No"); }}/* This code is contributed by Devesh Agrawal */ # Python program to check if there is Pythagorean# triplet in given array # Returns true if there is Pythagorean# triplet in ar[0..n-1] def isTriplet(ar, n): j = 0 for i in range(n - 2): for k in range(j + 1, n): for j in range(i + 1, n - 1): # Calculate square of array elements x = ar[i]*ar[i] y = ar[j]*ar[j] z = ar[k]*ar[k] if (x == y + z or y == x + z or z == x + y): return 1 # If we reach here, no triplet found return 0 # Driver program to test above functionar = [3, 1, 4, 6, 5]ar_size = len(ar) if(isTriplet(ar, ar_size)): print("Yes")else: print("No") # This code is contributed by Aditi Sharma // A C# program that returns true// if there is a Pythagorean// Triplet in a given array.using System; class GFG { // Returns true if there is Pythagorean // triplet in ar[0..n-1] static bool isTriplet(int[] ar, int n) { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Calculate square of array elements int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k]; if (x == y + z || y == x + z || z == x + y) return true; } } } // If we reach here, // no triplet found return false; } // Driver code public static void Main() { int[] ar = { 3, 1, 4, 6, 5 }; int ar_size = ar.Length; if (isTriplet(ar, ar_size) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by shiv_bhakt. <?php// A PHP program that returns// true if there is a Pythagorean// Triplet in a given array. // Returns true if there is// Pythagorean triplet in// ar[0..n-1]function isTriplet($ar, $n){ for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { for ($k = $j + 1; $k < $n; $k++) { // Calculate square of // array elements $x = $ar[$i] * $ar[$i]; $y = $ar[$j] * $ar[$j]; $z = $ar[$k] * $ar[$k]; if ($x == $y + $z or $y == $x + $z or $z == $x + $y) return true; } } } // If we reach here, // no triplet found return false;} // Driver Code $ar = array(3, 1, 4, 6, 5); $ar_size = count($ar); if(isTriplet($ar, $ar_size)) echo "Yes"; else echo "No"; // This code is contributed by anuj_67.?> <script> // A Javascript program that returns// true if there is a Pythagorean// Triplet in a given array. // Returns true if there is// Pythagorean triplet in ar[0..n-1]function isTriplet( ar, n){ for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { for (let k = j + 1; k < n; k++) { // Calculate square of array elements let x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k]; if (x == y + z || y == x + z || z == x + y) return true; } } } // If we reach here, no triplet found return false;} // driver code let ar = [ 3, 1, 4, 6, 5 ]; let ar_size = ar.length; if (isTriplet(ar, ar_size) == true) document.write("Yes"); else document.write("No"); </script> Output: Yes The Time Complexity of the above solution is O(n3). Auxiliary Space: O(1) Method 2 (Use Sorting) We can solve this in O(n2) time by sorting the array first. 1) Do the square of every element in the input array. This step takes O(n) time.2) Sort the squared array in increasing order. This step takes O(nLogn) time.3) To find a triplet (a, b, c) such that a2 = b2 + c2, do following. Fix ‘a’ as the last element of the sorted array.Now search for pair (b, c) in subarray between the first element and ‘a’. A pair (b, c) with a given sum can be found in O(n) time using the meet in middle algorithm discussed in method 1 of this post.If no pair is found for current ‘a’, then move ‘a’ one position back and repeat step 3.2. Fix ‘a’ as the last element of the sorted array. Now search for pair (b, c) in subarray between the first element and ‘a’. A pair (b, c) with a given sum can be found in O(n) time using the meet in middle algorithm discussed in method 1 of this post. If no pair is found for current ‘a’, then move ‘a’ one position back and repeat step 3.2. Below image is a dry run of the above approach: Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // A C++ program that returns true if there is a Pythagorean// Triplet in a given array.#include <algorithm>#include <iostream> using namespace std; // Returns true if there is a triplet with following property// A[i]*A[i] = A[j]*A[j] + A[k]*[k]// Note that this function modifies given arraybool isTriplet(int arr[], int n){ // Square array elements for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements sort(arr, arr + n); // Now fix one element one by one and find the other two // elements for (int i = n - 1; i >= 2; i--) { // To find the other two elements, start two index // variables from two corners of the array and move // them toward each other int l = 0; // index of the first element in arr[0..i-1] int r = i - 1; // index of the last element in arr[0..i-1] while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true; // Else either move 'l' or 'r' (arr[l] + arr[r] < arr[i]) ? l++ : r--; } } // If we reach here, then no triplet found return false;} /* Driver program to test above function */int main(){ int arr[] = { 3, 1, 4, 6, 5 }; int arr_size = sizeof(arr) / sizeof(arr[0]); isTriplet(arr, arr_size) ? cout << "Yes" : cout << "No"; return 0;} // A Java program that returns true if there is a Pythagorean// Triplet in a given array.import java.io.*;import java.util.*; class PythagoreanTriplet { // Returns true if there is a triplet with following property // A[i]*A[i] = A[j]*A[j] + A[k]*[k] // Note that this function modifies given array static boolean isTriplet(int arr[], int n) { // Square array elements for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements Arrays.sort(arr); // Now fix one element one by one and find the other two // elements for (int i = n - 1; i >= 2; i--) { // To find the other two elements, start two index // variables from two corners of the array and move // them toward each other int l = 0; // index of the first element in arr[0..i-1] int r = i - 1; // index of the last element in arr[0..i-1] while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true; // Else either move 'l' or 'r' if (arr[l] + arr[r] < arr[i]) l++; else r--; } } // If we reach here, then no triplet found return false; } // Driver program to test above function public static void main(String[] args) { int arr[] = { 3, 1, 4, 6, 5 }; int arr_size = arr.length; if (isTriplet(arr, arr_size) == true) System.out.println("Yes"); else System.out.println("No"); }}/*This code is contributed by Devesh Agrawal*/ # Python program that returns true if there is# a Pythagorean Triplet in a given array. # Returns true if there is Pythagorean# triplet in ar[0..n-1]def isTriplet(ar, n): # Square all the elements for i in range(n): ar[i] = ar[i] * ar[i] # sort array elements ar.sort() # fix one element # and find other two # i goes from n - 1 to 2 for i in range(n-1, 1, -1): # start two index variables from # two corners of the array and # move them toward each other j = 0 k = i - 1 while (j < k): # A triplet found if (ar[j] + ar[k] == ar[i]): return True else: if (ar[j] + ar[k] < ar[i]): j = j + 1 else: k = k - 1 # If we reach here, then no triplet found return False # Driver program to test above function */ar = [3, 1, 4, 6, 5]ar_size = len(ar)if(isTriplet(ar, ar_size)): print("Yes")else: print("No") # This code is contributed by Aditi Sharma // C# program that returns true// if there is a Pythagorean// Triplet in a given array.using System; class GFG { // Returns true if there is a triplet // with following property A[i]*A[i] // = A[j]*A[j]+ A[k]*[k] Note that // this function modifies given array static bool isTriplet(int[] arr, int n) { // Square array elements for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements Array.Sort(arr); // Now fix one element one by one // and find the other two elements for (int i = n - 1; i >= 2; i--) { // To find the other two elements, // start two index variables from // two corners of the array and // move them toward each other // index of the first element // in arr[0..i-1] int l = 0; // index of the last element // in arr[0..i - 1] int r = i - 1; while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true; // Else either move 'l' or 'r' if (arr[l] + arr[r] < arr[i]) l++; else r--; } } // If we reach here, then // no triplet found return false; } // Driver Code public static void Main() { int[] arr = { 3, 1, 4, 6, 5 }; int arr_size = arr.Length; if (isTriplet(arr, arr_size) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by shiv_bhakt. <?php// A PHP program that returns// true if there is a Pythagorean// Triplet in a given array. // Returns true if there is a// triplet with following property// A[i]*A[i] = A[j]*A[j] + A[k]*[k]// Note that this function modifies// given arrayfunction isTriplet( $arr, $n){ // Square array elements for ($i = 0; $i < $n; $i++) $arr[$i] = $arr[$i] * $arr[$i]; // Sort array elements sort($arr); // Now fix one element one by // one and find the other two // elements for($i = $n - 1; $i >= 2; $i--) { // To find the other two // elements, start two index // variables from two corners // of the array and move // them toward each other // index of the first element // in arr[0..i-1] $l = 0; // index of the last element // in arr[0..i-1] $r = $i - 1; while ($l < $r) { // A triplet found if ($arr[$l] + $arr[$r] == $arr[$i]) return true; // Else either move 'l' or 'r' ($arr[$l] + $arr[$r] < $arr[$i])? $l++: $r--; } } // If we reach here, // then no triplet found return false;} // Driver Code $arr = array(3, 1, 4, 6, 5); $arr_size = count($arr); if(isTriplet($arr, $arr_size)) echo "Yes"; else echo "No"; // This code is contributed by anuj_67.?> <script>// A javascript program that returns true if there is a Pythagorean// Triplet in a given array. // Returns true if there is a triplet with following property // A[i]*A[i] = A[j]*A[j] + A[k]*[k] // Note that this function modifies given array function isTriplet(arr , n) { // Square array elements for (i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements arr.sort((a,b)=>a-b); // Now fix one element one by one and find the other two // elements for (i = n - 1; i >= 2; i--) { // To find the other two elements, start two index // variables from two corners of the array and move // them toward each other var l = 0; // index of the first element in arr[0..i-1] var r = i - 1; // index of the last element in arr[0..i-1] while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true; // Else either move 'l' or 'r' if (arr[l] + arr[r] < arr[i]) l++; else r--; } } // If we reach here, then no triplet found return false; } // Driver program to test above function var arr = [ 3, 1, 4, 6, 5 ]; var arr_size = arr.length; if (isTriplet(arr, arr_size) == true) document.write("Yes"); else document.write("No"); // This code is contributed by umadevi9616</script> Output: Yes The time complexity of this method is O(n2). Auxiliary Space: O(1) Method 3: (Using Hashing) The problem can also be solved using hashing. We can use a hash map to mark all the values of the given array. Using two loops, we can iterate for all the possible combinations of a and b, and then check if there exists the third value c. If there exists any such value, then there is a Pythagorean triplet. Below is the implementation of the above approach: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // Function to check if the// Pythagorean triplet exists or notbool checkTriplet(int arr[], int n){ int maximum = 0; // Find the maximum element for (int i = 0; i < n; i++) { maximum = max(maximum, arr[i]); } // Hashing array int hash[maximum + 1] = { 0 }; // Increase the count of array elements // in hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for (int i = 1; i < maximum + 1; i++) { // If a is not there if (hash[i] == 0) continue; // Iterate for all possible b for (int j = 1; j < maximum + 1; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1) || hash[j] == 0) continue; // Find c int val = sqrt(i * i + j * j); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue; // If c exceeds the maximum value if (val > maximum) continue; // If there exists c in the original array, // we have the triplet if (hash[val]) { return true; } } } return false;}// Driver Codeint main(){ int arr[] = { 3, 2, 4, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); if (checkTriplet(arr, n)) cout << "Yes"; else cout << "No";} import java.util.*; class GFG{ // Function to check if the// Pythagorean triplet exists or notstatic boolean checkTriplet(int arr[], int n){ int maximum = 0; // Find the maximum element for (int i = 0; i < n; i++) { maximum = Math.max(maximum, arr[i]); } // Hashing array int []hash = new int[maximum + 1]; // Increase the count of array elements // in hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for (int i = 1; i < maximum + 1; i++) { // If a is not there if (hash[i] == 0) continue; // Iterate for all possible b for (int j = 1; j < maximum + 1; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1) || hash[j] == 0) continue; // Find c int val = (int) Math.sqrt(i * i + j * j); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue; // If c exceeds the maximum value if (val > maximum) continue; // If there exists c in the original array, // we have the triplet if (hash[val] == 1) { return true; } } } return false;} // Driver Codepublic static void main(String[] args){ int arr[] = { 3, 2, 4, 6, 5 }; int n = arr.length; if (checkTriplet(arr, n)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by Rajput-Ji # Function to check if the# Pythagorean triplet exists or notimport math def checkTriplet(arr, n): maximum = 0 # Find the maximum element maximum = max(arr) # Hashing array hash = [0]*(maximum+1) # Increase the count of array elements # in hash table for i in range(n): hash[arr[i]] += 1 # Iterate for all possible a for i in range(1, maximum+1): # If a is not there if (hash[i] == 0): continue # Iterate for all possible b for j in range(1, maximum+1): # If a and b are same and there is only one a # or if there is no b in original array if ((i == j and hash[i] == 1) or hash[j] == 0): continue # Find c val = int(math.sqrt(i * i + j * j)) # If c^2 is not a perfect square if ((val * val) != (i * i + j * j)): continue # If c exceeds the maximum value if (val > maximum): continue # If there exists c in the original array, # we have the triplet if (hash[val]): return True return False # Driver Codearr = [3, 2, 4, 6, 5]n = len(arr)if (checkTriplet(arr, n)): print("Yes")else: print("No") # This code is contributed by ankush_953 using System; class GFG{ // Function to check if the// Pythagorean triplet exists or notstatic bool checkTriplet(int []arr, int n){ int maximum = 0; // Find the maximum element for (int i = 0; i < n; i++) { maximum = Math.Max(maximum, arr[i]); } // Hashing array int []hash = new int[maximum + 1]; // Increase the count of array elements // in hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for (int i = 1; i < maximum + 1; i++) { // If a is not there if (hash[i] == 0) continue; // Iterate for all possible b for (int j = 1; j < maximum + 1; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1) || hash[j] == 0) continue; // Find c int val = (int) Math.Sqrt(i * i + j * j); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue; // If c exceeds the maximum value if (val > maximum) continue; // If there exists c in the original array, // we have the triplet if (hash[val] == 1) { return true; } } } return false;} // Driver Codepublic static void Main(String[] args){ int []arr = { 3, 2, 4, 6, 5 }; int n = arr.Length; if (checkTriplet(arr, n)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Rajput-Ji <script> // Function to check if the // Pythagorean triplet exists or not function checkTriplet(arr , n) { var maximum = 0; // Find the maximum element for (i = 0; i < n; i++) { maximum = Math.max(maximum, arr[i]); } // Hashing array var hash = Array(maximum + 1).fill(0); // Increase the count of array elements // in hash table for (i = 0; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for (i = 1; i < maximum + 1; i++) { // If a is not there if (hash[i] == 0) continue; // Iterate for all possible b for (j = 1; j < maximum + 1; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1) || hash[j] == 0) continue; // Find c var val = parseInt( Math.sqrt(i * i + j * j)); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue; // If c exceeds the maximum value if (val > maximum) continue; // If there exists c in the original array, // we have the triplet if (hash[val] == 1) { return true; } } } return false; } // Driver Code var arr = [ 3, 2, 4, 6, 5 ]; var n = arr.length; if (checkTriplet(arr, n)) document.write("Yes"); else document.write("No"); // This code is contributed by gauravrajput1 </script> Yes Thanks to Striver for suggesting the above approach. Time Complexity: O( max * max ), where max is the maximum most element in the array. Auxiliary Space: O(max) Method -4:Using STL Approach: The problem can be solved using ordered maps and unordered maps. There is no need to store the elements in an ordered manner so implementation by an unordered map is faster. We can use the unordered map to mark all the values of the given array. Using two loops, we can iterate for all the possible combinations of a and b, and then check if there exists the third value c. If there exists any such value, then there is a Pythagorean triplet. Below is the implementation of the above approach: C++ Java C# Javascript #include <bits/stdc++.h>using namespace std; // Returns true if there is Pythagorean triplet in// ar[0..n-1]bool checkTriplet(int arr[], int n){ // initializing unordered map with key and value as // integers unordered_map<int, int> umap; // Increase the count of array elements in unordered map for (int i = 0; i < n; i++) umap[arr[i]] = umap[arr[i]] + 1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // calculating the squares of two elements as // integer and float int p = sqrt(arr[i] * arr[i] + arr[j] * arr[j]); float q = sqrt(arr[i] * arr[i] + arr[j] * arr[j]); // Condition is true if the value is same in // integer and float and also the value is // present in unordered map if (p == q && umap[p] != 0) return true; } } // If we reach here, no triplet found return false;} // Driver Codeint main(){ int arr[] = { 3, 2, 4, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); if (checkTriplet(arr, n)) cout << "Yes"; else cout << "No";}// This code is contributed by Vikkycirus import java.util.*;class GFG{ // Returns true if there is Pythagorean triplet in // ar[0..n-1] static boolean checkTriplet(int arr[], int n) { // initializing unordered map with key and value as // integers HashMap<Integer,Integer> umap = new HashMap<>(); // Increase the count of array elements in unordered map for (int i = 0; i < n; i++) if(umap.containsKey(arr[i])) umap.put(arr[i] , umap.get(arr[i]) + 1); else umap.put(arr[i], 1); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // calculating the squares of two elements as // integer and float int p =(int) Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j]); float q =(float) Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j]); // Condition is true if the value is same in // integer and float and also the value is // present in unordered map if (p == q && umap.get(p) != 0) return true; } } // If we reach here, no triplet found return false; } // Driver Code public static void main(String[] args) { int arr[] = { 3, 2, 4, 6, 5 }; int n = arr.length; if (checkTriplet(arr, n)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by umadevi9616 using System;using System.Collections.Generic; public class GFG { // Returns true if there is Pythagorean triplet in // ar[0..n-1] static bool checkTriplet(int []arr, int n) { // initializing unordered map with key and value as // integers Dictionary<int, int> umap = new Dictionary<int,int>(); // Increase the count of array elements in unordered map for (int i = 0; i < n; i++) if (umap.ContainsKey(arr[i])) umap.Add(arr[i], umap[arr[i]] + 1); else umap.Add(arr[i], 1); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // calculating the squares of two elements as // integer and float int p = (int) Math.Sqrt(arr[i] * arr[i] + arr[j] * arr[j]); float q = (float) Math.Sqrt(arr[i] * arr[i] + arr[j] * arr[j]); // Condition is true if the value is same in // integer and float and also the value is // present in unordered map if (p == q && umap[p] != 0) return true; } } // If we reach here, no triplet found return false; } // Driver Code public static void Main(String[] args) { int []arr = { 3, 2, 4, 6, 5 }; int n = arr.Length; if (checkTriplet(arr, n)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by umadevi9616 <script> // Returns true if there is Pythagorean triplet in // ar[0..n-1] function checkTriplet(arr , n) { // initializing unordered map with key and value as // integers var umap = new Map(); // Increase the count of array elements in unordered map for (i = 0; i < n; i++) if (umap.has(arr[i])) umap.set(arr[i], umap.get(arr[i]) + 1); else umap.set(arr[i], 1); for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { // calculating the squares of two elements as // integer and float var p = parseInt( Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j])); var q = Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j]); // Condition is true if the value is same in // integer and var and also the value is // present in unordered map if (p == q && umap.get(p) != 0) return true; } } // If we reach here, no triplet found return false; } // Driver Code var arr = [ 3, 2, 4, 6, 5 ]; var n = arr.length; if (checkTriplet(arr, n)) document.write("Yes"); else document.write("No"); // This code contributed by gauravrajput1</script> Yes Time Complexity:O(n2) This article is contributed by Harshit Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Method 5 – A better hashing based approach This approach uses Set. Firstly, we’ll square the elements of the array and then sort the array in increasing order. Run two loops where the outer loop starts from the last index of the array to the second index (0 based indexing is assumed) and the inner loop starts from outerLoopIndex – 1 to the start. Create a set to store the elements in between outerLoopIndex and innerLoopIndex. Check if there is a number in the set which is equal to arr[outerLoopIndex] – arr[innerLoopIndex]. If yes, then return “True”. Python3 # Python program to check if there exists a pythagorean tripletdef checkTriplet(arr, n): for i in range(n): arr[i] = arr[i] * arr[i] arr.sort() for i in range(n - 1, 1, -1): s = set() for j in range(i - 1, -1, -1): if (arr[i] - arr[j]) in s: return True s.add(arr[j]) return False # Driver Programarr = [3, 2, 4, 6, 5]n = len(arr)if (checkTriplet(arr, n)): print("Yes")else: print("No") # This is contributed by Manvi Pandey Yes Time Complexity: O(n2) Auxiliary Space: O(n) Vishal_Khoda vt_m vasu_arora nidhi_biet ankush_953 Rajput-Ji vikkycirus jana_sayantan umadevi9616 GauravRajput1 manvimuskan surindertarika1234 chandramauliguptach Amazon Arrays Amazon Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 176, "s": 52, "text": "Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2." }, { "code": null, "e": 186, "s": 176, "text": "Example: " }, { "code": null, "e": 272, "s": 186, "text": "Input: arr[] = {3, 1, 4, 6, 5} Output: True There is a Pythagorean triplet (3, 4, 5)." }, { "code": null, "e": 353, "s": 272, "text": "Input: arr[] = {10, 4, 6, 12, 5} Output: False There is no Pythagorean triplet. " }, { "code": null, "e": 519, "s": 353, "text": "Method 1 (Naive) A simple solution is to run three loops, three loops pick three array elements, and check if the current three elements form a Pythagorean Triplet. " }, { "code": null, "e": 528, "s": 519, "text": "Chapters" }, { "code": null, "e": 555, "s": 528, "text": "descriptions off, selected" }, { "code": null, "e": 605, "s": 555, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 628, "s": 605, "text": "captions off, selected" }, { "code": null, "e": 636, "s": 628, "text": "English" }, { "code": null, "e": 660, "s": 636, "text": "This is a modal window." }, { "code": null, "e": 729, "s": 660, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 751, "s": 729, "text": "End of dialog window." }, { "code": null, "e": 799, "s": 751, "text": "Below is the implementation of the above idea :" }, { "code": null, "e": 803, "s": 799, "text": "C++" }, { "code": null, "e": 808, "s": 803, "text": "Java" }, { "code": null, "e": 816, "s": 808, "text": "Python3" }, { "code": null, "e": 819, "s": 816, "text": "C#" }, { "code": null, "e": 823, "s": 819, "text": "PHP" }, { "code": null, "e": 834, "s": 823, "text": "Javascript" }, { "code": "// A C++ program that returns true if there is a Pythagorean// Triplet in a given array.#include <iostream> using namespace std; // Returns true if there is Pythagorean triplet in ar[0..n-1]bool isTriplet(int ar[], int n){ for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Calculate square of array elements int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k]; if (x == y + z || y == x + z || z == x + y) return true; } } } // If we reach here, no triplet found return false;} /* Driver program to test above function */int main(){ int ar[] = { 3, 1, 4, 6, 5 }; int ar_size = sizeof(ar) / sizeof(ar[0]); isTriplet(ar, ar_size) ? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 1689, "s": 834, "text": null }, { "code": "// A Java program that returns true if there is a Pythagorean// Triplet in a given array.import java.io.*; class PythagoreanTriplet { // Returns true if there is Pythagorean triplet in ar[0..n-1] static boolean isTriplet(int ar[], int n) { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Calculate square of array elements int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k]; if (x == y + z || y == x + z || z == x + y) return true; } } } // If we reach here, no triplet found return false; } // Driver program to test above function public static void main(String[] args) { int ar[] = { 3, 1, 4, 6, 5 }; int ar_size = ar.length; if (isTriplet(ar, ar_size) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}/* This code is contributed by Devesh Agrawal */", "e": 2763, "s": 1689, "text": null }, { "code": "# Python program to check if there is Pythagorean# triplet in given array # Returns true if there is Pythagorean# triplet in ar[0..n-1] def isTriplet(ar, n): j = 0 for i in range(n - 2): for k in range(j + 1, n): for j in range(i + 1, n - 1): # Calculate square of array elements x = ar[i]*ar[i] y = ar[j]*ar[j] z = ar[k]*ar[k] if (x == y + z or y == x + z or z == x + y): return 1 # If we reach here, no triplet found return 0 # Driver program to test above functionar = [3, 1, 4, 6, 5]ar_size = len(ar) if(isTriplet(ar, ar_size)): print(\"Yes\")else: print(\"No\") # This code is contributed by Aditi Sharma", "e": 3510, "s": 2763, "text": null }, { "code": "// A C# program that returns true// if there is a Pythagorean// Triplet in a given array.using System; class GFG { // Returns true if there is Pythagorean // triplet in ar[0..n-1] static bool isTriplet(int[] ar, int n) { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { // Calculate square of array elements int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k]; if (x == y + z || y == x + z || z == x + y) return true; } } } // If we reach here, // no triplet found return false; } // Driver code public static void Main() { int[] ar = { 3, 1, 4, 6, 5 }; int ar_size = ar.Length; if (isTriplet(ar, ar_size) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by shiv_bhakt.", "e": 4533, "s": 3510, "text": null }, { "code": "<?php// A PHP program that returns// true if there is a Pythagorean// Triplet in a given array. // Returns true if there is// Pythagorean triplet in// ar[0..n-1]function isTriplet($ar, $n){ for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { for ($k = $j + 1; $k < $n; $k++) { // Calculate square of // array elements $x = $ar[$i] * $ar[$i]; $y = $ar[$j] * $ar[$j]; $z = $ar[$k] * $ar[$k]; if ($x == $y + $z or $y == $x + $z or $z == $x + $y) return true; } } } // If we reach here, // no triplet found return false;} // Driver Code $ar = array(3, 1, 4, 6, 5); $ar_size = count($ar); if(isTriplet($ar, $ar_size)) echo \"Yes\"; else echo \"No\"; // This code is contributed by anuj_67.?>", "e": 5433, "s": 4533, "text": null }, { "code": "<script> // A Javascript program that returns// true if there is a Pythagorean// Triplet in a given array. // Returns true if there is// Pythagorean triplet in ar[0..n-1]function isTriplet( ar, n){ for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { for (let k = j + 1; k < n; k++) { // Calculate square of array elements let x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k]; if (x == y + z || y == x + z || z == x + y) return true; } } } // If we reach here, no triplet found return false;} // driver code let ar = [ 3, 1, 4, 6, 5 ]; let ar_size = ar.length; if (isTriplet(ar, ar_size) == true) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 6290, "s": 5433, "text": null }, { "code": null, "e": 6299, "s": 6290, "text": "Output: " }, { "code": null, "e": 6303, "s": 6299, "text": "Yes" }, { "code": null, "e": 6356, "s": 6303, "text": "The Time Complexity of the above solution is O(n3). " }, { "code": null, "e": 6378, "s": 6356, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6688, "s": 6378, "text": "Method 2 (Use Sorting) We can solve this in O(n2) time by sorting the array first. 1) Do the square of every element in the input array. This step takes O(n) time.2) Sort the squared array in increasing order. This step takes O(nLogn) time.3) To find a triplet (a, b, c) such that a2 = b2 + c2, do following. " }, { "code": null, "e": 7027, "s": 6688, "text": "Fix ‘a’ as the last element of the sorted array.Now search for pair (b, c) in subarray between the first element and ‘a’. A pair (b, c) with a given sum can be found in O(n) time using the meet in middle algorithm discussed in method 1 of this post.If no pair is found for current ‘a’, then move ‘a’ one position back and repeat step 3.2." }, { "code": null, "e": 7076, "s": 7027, "text": "Fix ‘a’ as the last element of the sorted array." }, { "code": null, "e": 7278, "s": 7076, "text": "Now search for pair (b, c) in subarray between the first element and ‘a’. A pair (b, c) with a given sum can be found in O(n) time using the meet in middle algorithm discussed in method 1 of this post." }, { "code": null, "e": 7368, "s": 7278, "text": "If no pair is found for current ‘a’, then move ‘a’ one position back and repeat step 3.2." }, { "code": null, "e": 7417, "s": 7368, "text": "Below image is a dry run of the above approach: " }, { "code": null, "e": 7469, "s": 7417, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 7473, "s": 7469, "text": "C++" }, { "code": null, "e": 7478, "s": 7473, "text": "Java" }, { "code": null, "e": 7486, "s": 7478, "text": "Python3" }, { "code": null, "e": 7489, "s": 7486, "text": "C#" }, { "code": null, "e": 7493, "s": 7489, "text": "PHP" }, { "code": null, "e": 7504, "s": 7493, "text": "Javascript" }, { "code": "// A C++ program that returns true if there is a Pythagorean// Triplet in a given array.#include <algorithm>#include <iostream> using namespace std; // Returns true if there is a triplet with following property// A[i]*A[i] = A[j]*A[j] + A[k]*[k]// Note that this function modifies given arraybool isTriplet(int arr[], int n){ // Square array elements for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements sort(arr, arr + n); // Now fix one element one by one and find the other two // elements for (int i = n - 1; i >= 2; i--) { // To find the other two elements, start two index // variables from two corners of the array and move // them toward each other int l = 0; // index of the first element in arr[0..i-1] int r = i - 1; // index of the last element in arr[0..i-1] while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true; // Else either move 'l' or 'r' (arr[l] + arr[r] < arr[i]) ? l++ : r--; } } // If we reach here, then no triplet found return false;} /* Driver program to test above function */int main(){ int arr[] = { 3, 1, 4, 6, 5 }; int arr_size = sizeof(arr) / sizeof(arr[0]); isTriplet(arr, arr_size) ? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 8872, "s": 7504, "text": null }, { "code": "// A Java program that returns true if there is a Pythagorean// Triplet in a given array.import java.io.*;import java.util.*; class PythagoreanTriplet { // Returns true if there is a triplet with following property // A[i]*A[i] = A[j]*A[j] + A[k]*[k] // Note that this function modifies given array static boolean isTriplet(int arr[], int n) { // Square array elements for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements Arrays.sort(arr); // Now fix one element one by one and find the other two // elements for (int i = n - 1; i >= 2; i--) { // To find the other two elements, start two index // variables from two corners of the array and move // them toward each other int l = 0; // index of the first element in arr[0..i-1] int r = i - 1; // index of the last element in arr[0..i-1] while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true; // Else either move 'l' or 'r' if (arr[l] + arr[r] < arr[i]) l++; else r--; } } // If we reach here, then no triplet found return false; } // Driver program to test above function public static void main(String[] args) { int arr[] = { 3, 1, 4, 6, 5 }; int arr_size = arr.length; if (isTriplet(arr, arr_size) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}/*This code is contributed by Devesh Agrawal*/", "e": 10562, "s": 8872, "text": null }, { "code": "# Python program that returns true if there is# a Pythagorean Triplet in a given array. # Returns true if there is Pythagorean# triplet in ar[0..n-1]def isTriplet(ar, n): # Square all the elements for i in range(n): ar[i] = ar[i] * ar[i] # sort array elements ar.sort() # fix one element # and find other two # i goes from n - 1 to 2 for i in range(n-1, 1, -1): # start two index variables from # two corners of the array and # move them toward each other j = 0 k = i - 1 while (j < k): # A triplet found if (ar[j] + ar[k] == ar[i]): return True else: if (ar[j] + ar[k] < ar[i]): j = j + 1 else: k = k - 1 # If we reach here, then no triplet found return False # Driver program to test above function */ar = [3, 1, 4, 6, 5]ar_size = len(ar)if(isTriplet(ar, ar_size)): print(\"Yes\")else: print(\"No\") # This code is contributed by Aditi Sharma", "e": 11606, "s": 10562, "text": null }, { "code": "// C# program that returns true// if there is a Pythagorean// Triplet in a given array.using System; class GFG { // Returns true if there is a triplet // with following property A[i]*A[i] // = A[j]*A[j]+ A[k]*[k] Note that // this function modifies given array static bool isTriplet(int[] arr, int n) { // Square array elements for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements Array.Sort(arr); // Now fix one element one by one // and find the other two elements for (int i = n - 1; i >= 2; i--) { // To find the other two elements, // start two index variables from // two corners of the array and // move them toward each other // index of the first element // in arr[0..i-1] int l = 0; // index of the last element // in arr[0..i - 1] int r = i - 1; while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true; // Else either move 'l' or 'r' if (arr[l] + arr[r] < arr[i]) l++; else r--; } } // If we reach here, then // no triplet found return false; } // Driver Code public static void Main() { int[] arr = { 3, 1, 4, 6, 5 }; int arr_size = arr.Length; if (isTriplet(arr, arr_size) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by shiv_bhakt.", "e": 13293, "s": 11606, "text": null }, { "code": "<?php// A PHP program that returns// true if there is a Pythagorean// Triplet in a given array. // Returns true if there is a// triplet with following property// A[i]*A[i] = A[j]*A[j] + A[k]*[k]// Note that this function modifies// given arrayfunction isTriplet( $arr, $n){ // Square array elements for ($i = 0; $i < $n; $i++) $arr[$i] = $arr[$i] * $arr[$i]; // Sort array elements sort($arr); // Now fix one element one by // one and find the other two // elements for($i = $n - 1; $i >= 2; $i--) { // To find the other two // elements, start two index // variables from two corners // of the array and move // them toward each other // index of the first element // in arr[0..i-1] $l = 0; // index of the last element // in arr[0..i-1] $r = $i - 1; while ($l < $r) { // A triplet found if ($arr[$l] + $arr[$r] == $arr[$i]) return true; // Else either move 'l' or 'r' ($arr[$l] + $arr[$r] < $arr[$i])? $l++: $r--; } } // If we reach here, // then no triplet found return false;} // Driver Code $arr = array(3, 1, 4, 6, 5); $arr_size = count($arr); if(isTriplet($arr, $arr_size)) echo \"Yes\"; else echo \"No\"; // This code is contributed by anuj_67.?>", "e": 14721, "s": 13293, "text": null }, { "code": "<script>// A javascript program that returns true if there is a Pythagorean// Triplet in a given array. // Returns true if there is a triplet with following property // A[i]*A[i] = A[j]*A[j] + A[k]*[k] // Note that this function modifies given array function isTriplet(arr , n) { // Square array elements for (i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements arr.sort((a,b)=>a-b); // Now fix one element one by one and find the other two // elements for (i = n - 1; i >= 2; i--) { // To find the other two elements, start two index // variables from two corners of the array and move // them toward each other var l = 0; // index of the first element in arr[0..i-1] var r = i - 1; // index of the last element in arr[0..i-1] while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true; // Else either move 'l' or 'r' if (arr[l] + arr[r] < arr[i]) l++; else r--; } } // If we reach here, then no triplet found return false; } // Driver program to test above function var arr = [ 3, 1, 4, 6, 5 ]; var arr_size = arr.length; if (isTriplet(arr, arr_size) == true) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by umadevi9616</script>", "e": 16335, "s": 14721, "text": null }, { "code": null, "e": 16343, "s": 16335, "text": "Output:" }, { "code": null, "e": 16349, "s": 16343, "text": " Yes " }, { "code": null, "e": 16394, "s": 16349, "text": "The time complexity of this method is O(n2)." }, { "code": null, "e": 16416, "s": 16394, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 16751, "s": 16416, "text": "Method 3: (Using Hashing) The problem can also be solved using hashing. We can use a hash map to mark all the values of the given array. Using two loops, we can iterate for all the possible combinations of a and b, and then check if there exists the third value c. If there exists any such value, then there is a Pythagorean triplet. " }, { "code": null, "e": 16804, "s": 16751, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 16808, "s": 16804, "text": "C++" }, { "code": null, "e": 16813, "s": 16808, "text": "Java" }, { "code": null, "e": 16821, "s": 16813, "text": "Python3" }, { "code": null, "e": 16824, "s": 16821, "text": "C#" }, { "code": null, "e": 16835, "s": 16824, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to check if the// Pythagorean triplet exists or notbool checkTriplet(int arr[], int n){ int maximum = 0; // Find the maximum element for (int i = 0; i < n; i++) { maximum = max(maximum, arr[i]); } // Hashing array int hash[maximum + 1] = { 0 }; // Increase the count of array elements // in hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for (int i = 1; i < maximum + 1; i++) { // If a is not there if (hash[i] == 0) continue; // Iterate for all possible b for (int j = 1; j < maximum + 1; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1) || hash[j] == 0) continue; // Find c int val = sqrt(i * i + j * j); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue; // If c exceeds the maximum value if (val > maximum) continue; // If there exists c in the original array, // we have the triplet if (hash[val]) { return true; } } } return false;}// Driver Codeint main(){ int arr[] = { 3, 2, 4, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); if (checkTriplet(arr, n)) cout << \"Yes\"; else cout << \"No\";}", "e": 18367, "s": 16835, "text": null }, { "code": "import java.util.*; class GFG{ // Function to check if the// Pythagorean triplet exists or notstatic boolean checkTriplet(int arr[], int n){ int maximum = 0; // Find the maximum element for (int i = 0; i < n; i++) { maximum = Math.max(maximum, arr[i]); } // Hashing array int []hash = new int[maximum + 1]; // Increase the count of array elements // in hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for (int i = 1; i < maximum + 1; i++) { // If a is not there if (hash[i] == 0) continue; // Iterate for all possible b for (int j = 1; j < maximum + 1; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1) || hash[j] == 0) continue; // Find c int val = (int) Math.sqrt(i * i + j * j); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue; // If c exceeds the maximum value if (val > maximum) continue; // If there exists c in the original array, // we have the triplet if (hash[val] == 1) { return true; } } } return false;} // Driver Codepublic static void main(String[] args){ int arr[] = { 3, 2, 4, 6, 5 }; int n = arr.length; if (checkTriplet(arr, n)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by Rajput-Ji", "e": 20017, "s": 18367, "text": null }, { "code": "# Function to check if the# Pythagorean triplet exists or notimport math def checkTriplet(arr, n): maximum = 0 # Find the maximum element maximum = max(arr) # Hashing array hash = [0]*(maximum+1) # Increase the count of array elements # in hash table for i in range(n): hash[arr[i]] += 1 # Iterate for all possible a for i in range(1, maximum+1): # If a is not there if (hash[i] == 0): continue # Iterate for all possible b for j in range(1, maximum+1): # If a and b are same and there is only one a # or if there is no b in original array if ((i == j and hash[i] == 1) or hash[j] == 0): continue # Find c val = int(math.sqrt(i * i + j * j)) # If c^2 is not a perfect square if ((val * val) != (i * i + j * j)): continue # If c exceeds the maximum value if (val > maximum): continue # If there exists c in the original array, # we have the triplet if (hash[val]): return True return False # Driver Codearr = [3, 2, 4, 6, 5]n = len(arr)if (checkTriplet(arr, n)): print(\"Yes\")else: print(\"No\") # This code is contributed by ankush_953", "e": 21346, "s": 20017, "text": null }, { "code": "using System; class GFG{ // Function to check if the// Pythagorean triplet exists or notstatic bool checkTriplet(int []arr, int n){ int maximum = 0; // Find the maximum element for (int i = 0; i < n; i++) { maximum = Math.Max(maximum, arr[i]); } // Hashing array int []hash = new int[maximum + 1]; // Increase the count of array elements // in hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for (int i = 1; i < maximum + 1; i++) { // If a is not there if (hash[i] == 0) continue; // Iterate for all possible b for (int j = 1; j < maximum + 1; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1) || hash[j] == 0) continue; // Find c int val = (int) Math.Sqrt(i * i + j * j); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue; // If c exceeds the maximum value if (val > maximum) continue; // If there exists c in the original array, // we have the triplet if (hash[val] == 1) { return true; } } } return false;} // Driver Codepublic static void Main(String[] args){ int []arr = { 3, 2, 4, 6, 5 }; int n = arr.Length; if (checkTriplet(arr, n)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by Rajput-Ji", "e": 22981, "s": 21346, "text": null }, { "code": "<script> // Function to check if the // Pythagorean triplet exists or not function checkTriplet(arr , n) { var maximum = 0; // Find the maximum element for (i = 0; i < n; i++) { maximum = Math.max(maximum, arr[i]); } // Hashing array var hash = Array(maximum + 1).fill(0); // Increase the count of array elements // in hash table for (i = 0; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for (i = 1; i < maximum + 1; i++) { // If a is not there if (hash[i] == 0) continue; // Iterate for all possible b for (j = 1; j < maximum + 1; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1) || hash[j] == 0) continue; // Find c var val = parseInt( Math.sqrt(i * i + j * j)); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue; // If c exceeds the maximum value if (val > maximum) continue; // If there exists c in the original array, // we have the triplet if (hash[val] == 1) { return true; } } } return false; } // Driver Code var arr = [ 3, 2, 4, 6, 5 ]; var n = arr.length; if (checkTriplet(arr, n)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by gauravrajput1 </script>", "e": 24727, "s": 22981, "text": null }, { "code": null, "e": 24731, "s": 24727, "text": "Yes" }, { "code": null, "e": 24870, "s": 24731, "text": "Thanks to Striver for suggesting the above approach. Time Complexity: O( max * max ), where max is the maximum most element in the array. " }, { "code": null, "e": 24894, "s": 24870, "text": "Auxiliary Space: O(max)" }, { "code": null, "e": 24914, "s": 24894, "text": "Method -4:Using STL" }, { "code": null, "e": 24924, "s": 24914, "text": "Approach:" }, { "code": null, "e": 25367, "s": 24924, "text": "The problem can be solved using ordered maps and unordered maps. There is no need to store the elements in an ordered manner so implementation by an unordered map is faster. We can use the unordered map to mark all the values of the given array. Using two loops, we can iterate for all the possible combinations of a and b, and then check if there exists the third value c. If there exists any such value, then there is a Pythagorean triplet." }, { "code": null, "e": 25418, "s": 25367, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25422, "s": 25418, "text": "C++" }, { "code": null, "e": 25427, "s": 25422, "text": "Java" }, { "code": null, "e": 25430, "s": 25427, "text": "C#" }, { "code": null, "e": 25441, "s": 25430, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Returns true if there is Pythagorean triplet in// ar[0..n-1]bool checkTriplet(int arr[], int n){ // initializing unordered map with key and value as // integers unordered_map<int, int> umap; // Increase the count of array elements in unordered map for (int i = 0; i < n; i++) umap[arr[i]] = umap[arr[i]] + 1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // calculating the squares of two elements as // integer and float int p = sqrt(arr[i] * arr[i] + arr[j] * arr[j]); float q = sqrt(arr[i] * arr[i] + arr[j] * arr[j]); // Condition is true if the value is same in // integer and float and also the value is // present in unordered map if (p == q && umap[p] != 0) return true; } } // If we reach here, no triplet found return false;} // Driver Codeint main(){ int arr[] = { 3, 2, 4, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); if (checkTriplet(arr, n)) cout << \"Yes\"; else cout << \"No\";}// This code is contributed by Vikkycirus", "e": 26674, "s": 25441, "text": null }, { "code": "import java.util.*;class GFG{ // Returns true if there is Pythagorean triplet in // ar[0..n-1] static boolean checkTriplet(int arr[], int n) { // initializing unordered map with key and value as // integers HashMap<Integer,Integer> umap = new HashMap<>(); // Increase the count of array elements in unordered map for (int i = 0; i < n; i++) if(umap.containsKey(arr[i])) umap.put(arr[i] , umap.get(arr[i]) + 1); else umap.put(arr[i], 1); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // calculating the squares of two elements as // integer and float int p =(int) Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j]); float q =(float) Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j]); // Condition is true if the value is same in // integer and float and also the value is // present in unordered map if (p == q && umap.get(p) != 0) return true; } } // If we reach here, no triplet found return false; } // Driver Code public static void main(String[] args) { int arr[] = { 3, 2, 4, 6, 5 }; int n = arr.length; if (checkTriplet(arr, n)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by umadevi9616", "e": 28003, "s": 26674, "text": null }, { "code": "using System;using System.Collections.Generic; public class GFG { // Returns true if there is Pythagorean triplet in // ar[0..n-1] static bool checkTriplet(int []arr, int n) { // initializing unordered map with key and value as // integers Dictionary<int, int> umap = new Dictionary<int,int>(); // Increase the count of array elements in unordered map for (int i = 0; i < n; i++) if (umap.ContainsKey(arr[i])) umap.Add(arr[i], umap[arr[i]] + 1); else umap.Add(arr[i], 1); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // calculating the squares of two elements as // integer and float int p = (int) Math.Sqrt(arr[i] * arr[i] + arr[j] * arr[j]); float q = (float) Math.Sqrt(arr[i] * arr[i] + arr[j] * arr[j]); // Condition is true if the value is same in // integer and float and also the value is // present in unordered map if (p == q && umap[p] != 0) return true; } } // If we reach here, no triplet found return false; } // Driver Code public static void Main(String[] args) { int []arr = { 3, 2, 4, 6, 5 }; int n = arr.Length; if (checkTriplet(arr, n)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by umadevi9616", "e": 29335, "s": 28003, "text": null }, { "code": "<script> // Returns true if there is Pythagorean triplet in // ar[0..n-1] function checkTriplet(arr , n) { // initializing unordered map with key and value as // integers var umap = new Map(); // Increase the count of array elements in unordered map for (i = 0; i < n; i++) if (umap.has(arr[i])) umap.set(arr[i], umap.get(arr[i]) + 1); else umap.set(arr[i], 1); for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { // calculating the squares of two elements as // integer and float var p = parseInt( Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j])); var q = Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j]); // Condition is true if the value is same in // integer and var and also the value is // present in unordered map if (p == q && umap.get(p) != 0) return true; } } // If we reach here, no triplet found return false; } // Driver Code var arr = [ 3, 2, 4, 6, 5 ]; var n = arr.length; if (checkTriplet(arr, n)) document.write(\"Yes\"); else document.write(\"No\"); // This code contributed by gauravrajput1</script>", "e": 30706, "s": 29335, "text": null }, { "code": null, "e": 30710, "s": 30706, "text": "Yes" }, { "code": null, "e": 30732, "s": 30710, "text": "Time Complexity:O(n2)" }, { "code": null, "e": 30903, "s": 30732, "text": "This article is contributed by Harshit Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30946, "s": 30903, "text": "Method 5 – A better hashing based approach" }, { "code": null, "e": 31460, "s": 30946, "text": "This approach uses Set. Firstly, we’ll square the elements of the array and then sort the array in increasing order. Run two loops where the outer loop starts from the last index of the array to the second index (0 based indexing is assumed) and the inner loop starts from outerLoopIndex – 1 to the start. Create a set to store the elements in between outerLoopIndex and innerLoopIndex. Check if there is a number in the set which is equal to arr[outerLoopIndex] – arr[innerLoopIndex]. If yes, then return “True”." }, { "code": null, "e": 31468, "s": 31460, "text": "Python3" }, { "code": "# Python program to check if there exists a pythagorean tripletdef checkTriplet(arr, n): for i in range(n): arr[i] = arr[i] * arr[i] arr.sort() for i in range(n - 1, 1, -1): s = set() for j in range(i - 1, -1, -1): if (arr[i] - arr[j]) in s: return True s.add(arr[j]) return False # Driver Programarr = [3, 2, 4, 6, 5]n = len(arr)if (checkTriplet(arr, n)): print(\"Yes\")else: print(\"No\") # This is contributed by Manvi Pandey", "e": 31971, "s": 31468, "text": null }, { "code": null, "e": 31975, "s": 31971, "text": "Yes" }, { "code": null, "e": 32020, "s": 31975, "text": "Time Complexity: O(n2) Auxiliary Space: O(n)" }, { "code": null, "e": 32033, "s": 32020, "text": "Vishal_Khoda" }, { "code": null, "e": 32038, "s": 32033, "text": "vt_m" }, { "code": null, "e": 32049, "s": 32038, "text": "vasu_arora" }, { "code": null, "e": 32060, "s": 32049, "text": "nidhi_biet" }, { "code": null, "e": 32071, "s": 32060, "text": "ankush_953" }, { "code": null, "e": 32081, "s": 32071, "text": "Rajput-Ji" }, { "code": null, "e": 32092, "s": 32081, "text": "vikkycirus" }, { "code": null, "e": 32106, "s": 32092, "text": "jana_sayantan" }, { "code": null, "e": 32118, "s": 32106, "text": "umadevi9616" }, { "code": null, "e": 32132, "s": 32118, "text": "GauravRajput1" }, { "code": null, "e": 32144, "s": 32132, "text": "manvimuskan" }, { "code": null, "e": 32163, "s": 32144, "text": "surindertarika1234" }, { "code": null, "e": 32183, "s": 32163, "text": "chandramauliguptach" }, { "code": null, "e": 32190, "s": 32183, "text": "Amazon" }, { "code": null, "e": 32197, "s": 32190, "text": "Arrays" }, { "code": null, "e": 32204, "s": 32197, "text": "Amazon" }, { "code": null, "e": 32211, "s": 32204, "text": "Arrays" }, { "code": null, "e": 32309, "s": 32211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32377, "s": 32309, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32421, "s": 32377, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32453, "s": 32421, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32501, "s": 32453, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32515, "s": 32501, "text": "Linear Search" }, { "code": null, "e": 32600, "s": 32515, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 32623, "s": 32600, "text": "Introduction to Arrays" }, { "code": null, "e": 32679, "s": 32623, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 32706, "s": 32679, "text": "Subset Sum Problem | DP-25" } ]
Using Instance Blocks in Java
31 Aug, 2021 The instance block can be defined as the name-less method in java inside which we can define logic and they possess certain characteristics as follows. They can be declared inside classes but not inside any method. Instance block logic is common for all the objects. Instance block will be executed only once for each object during its creation. Illustration: class GFG { { // Code inside instance block } } The advantage of the Instance block is as follows: Instance blocks are executed whenever an object of any kind is created. If we want to write a logic that we want to execute on the creation of all kinds of objects, then using instance blocks is a good idea to avoid writing the same logic inside every constructor. The drawback of the Instance block is as follows: We generally don’t use them for the initialization of objects because they can not accept the parameters. If we still use instance blocks for the purpose of initialization, then all the objects will have to be initialized with the same values which are practically useless. Example 1: Java // Java Program to Illustrate Usage of Instance Blocks // Class 1// Helper classclass GFG { // Constructors of this class // Constructor 1 // This constructor will get executed for 1st // kind of object GFG() { System.out.println("1st argument constructor"); } // Constructor 2 // This constructor will get executed for // 2nd kind of object GFG(String a) { // Print statement when this constructor is called System.out.println("2nd argument constructor"); } // Constructor 3 // This constructor will get executed // for 3rd kind of object GFG(int a, int b) { // Print statement when this constructor is called System.out.println("3rd arguments constructor"); } { // Creation of an instance block System.out.println("Instance block"); }} // Class 2// Main classclass GFGJava { // main driver method public static void main(String[] args) { // Object of 1st kind new GFG(); // Object of 2nd kind new GFG("I like Java"); // Object of 3rd kind new GFG(10, 20); }} Instance block 1st argument constructor Instance block 2nd argument constructor Instance block 3rd arguments constructor Note: The sequence of execution of instance blocks follows the order- Static block, Instance block, and Constructor.\\ It can be justified from the example been proposed below as follows: Example 2: Java // Java Program to Illustrate Execution of Instance Blocks // Main classclass GFG { // Main driver method public static void main(String[] args) { // Making object of class in main() GFG geek = new GFG(); } // Constructor of this class GFG() { // Print statement when constructor is called System.out.println("I am Constructor!"); } { // Print statement when instance block is called System.out.println("I am Instance block!"); } static { // Print statement when static block is called System.out.println("I am Static block!"); }} I am Static block! I am Instance block! I am Constructor! 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 Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n31 Aug, 2021" }, { "code": null, "e": 400, "s": 53, "text": "The instance block can be defined as the name-less method in java inside which we can define logic and they possess certain characteristics as follows. They can be declared inside classes but not inside any method. Instance block logic is common for all the objects. Instance block will be executed only once for each object during its creation. " }, { "code": null, "e": 414, "s": 400, "text": "Illustration:" }, { "code": null, "e": 478, "s": 414, "text": "class GFG {\n {\n // Code inside instance block\n }\n}" }, { "code": null, "e": 530, "s": 478, "text": "The advantage of the Instance block is as follows: " }, { "code": null, "e": 795, "s": 530, "text": "Instance blocks are executed whenever an object of any kind is created. If we want to write a logic that we want to execute on the creation of all kinds of objects, then using instance blocks is a good idea to avoid writing the same logic inside every constructor." }, { "code": null, "e": 846, "s": 795, "text": "The drawback of the Instance block is as follows: " }, { "code": null, "e": 1120, "s": 846, "text": "We generally don’t use them for the initialization of objects because they can not accept the parameters. If we still use instance blocks for the purpose of initialization, then all the objects will have to be initialized with the same values which are practically useless." }, { "code": null, "e": 1131, "s": 1120, "text": "Example 1:" }, { "code": null, "e": 1136, "s": 1131, "text": "Java" }, { "code": "// Java Program to Illustrate Usage of Instance Blocks // Class 1// Helper classclass GFG { // Constructors of this class // Constructor 1 // This constructor will get executed for 1st // kind of object GFG() { System.out.println(\"1st argument constructor\"); } // Constructor 2 // This constructor will get executed for // 2nd kind of object GFG(String a) { // Print statement when this constructor is called System.out.println(\"2nd argument constructor\"); } // Constructor 3 // This constructor will get executed // for 3rd kind of object GFG(int a, int b) { // Print statement when this constructor is called System.out.println(\"3rd arguments constructor\"); } { // Creation of an instance block System.out.println(\"Instance block\"); }} // Class 2// Main classclass GFGJava { // main driver method public static void main(String[] args) { // Object of 1st kind new GFG(); // Object of 2nd kind new GFG(\"I like Java\"); // Object of 3rd kind new GFG(10, 20); }}", "e": 2287, "s": 1136, "text": null }, { "code": null, "e": 2408, "s": 2287, "text": "Instance block\n1st argument constructor\nInstance block\n2nd argument constructor\nInstance block\n3rd arguments constructor" }, { "code": null, "e": 2527, "s": 2408, "text": "Note: The sequence of execution of instance blocks follows the order- Static block, Instance block, and Constructor.\\\\" }, { "code": null, "e": 2596, "s": 2527, "text": "It can be justified from the example been proposed below as follows:" }, { "code": null, "e": 2607, "s": 2596, "text": "Example 2:" }, { "code": null, "e": 2612, "s": 2607, "text": "Java" }, { "code": "// Java Program to Illustrate Execution of Instance Blocks // Main classclass GFG { // Main driver method public static void main(String[] args) { // Making object of class in main() GFG geek = new GFG(); } // Constructor of this class GFG() { // Print statement when constructor is called System.out.println(\"I am Constructor!\"); } { // Print statement when instance block is called System.out.println(\"I am Instance block!\"); } static { // Print statement when static block is called System.out.println(\"I am Static block!\"); }}", "e": 3251, "s": 2612, "text": null }, { "code": null, "e": 3309, "s": 3251, "text": "I am Static block!\nI am Instance block!\nI am Constructor!" }, { "code": null, "e": 3316, "s": 3309, "text": "Picked" }, { "code": null, "e": 3321, "s": 3316, "text": "Java" }, { "code": null, "e": 3326, "s": 3321, "text": "Java" }, { "code": null, "e": 3424, "s": 3326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3475, "s": 3424, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3506, "s": 3475, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3536, "s": 3506, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3551, "s": 3536, "text": "Stream In Java" }, { "code": null, "e": 3569, "s": 3551, "text": "ArrayList in Java" }, { "code": null, "e": 3589, "s": 3569, "text": "Collections in Java" }, { "code": null, "e": 3613, "s": 3589, "text": "Singleton Class in Java" }, { "code": null, "e": 3645, "s": 3613, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3657, "s": 3645, "text": "Set in Java" } ]
Understanding HDBSCAN and Density-Based Clustering | by Pepe Berba | Towards Data Science
HDBSCAN is a clustering algorithm developed by Campello, Moulavi, and Sander [8]. It stands for “Hierarchical Density-Based Spatial Clustering of Applications with Noise.” In this blog post, I will try to present in a top-down approach the key concepts to help understand how and why HDBSCAN works. This is meant to complement existing documentation such as sklearn’s “How HDBSCAN works” [1], and other works and presentations by McInnes and Healy [2], [3]. Let’s start at the very top. Before we even describe our clustering algorithm, we should ask, “what type of data are we trying to cluster?” We want to have as few assumptions about our data as possible. Perhaps the only assumptions that we can safely make are: There is noise in our data There are clusters in our data which we hope to discover To motivate our discussion, we start with the data set used in [1] and [3]. With only 2 dimensions, we can plot the data and identify 6 “natural” clusters in our dataset. We hope to automatically identify these through some clustering algorithm. Knowing the expected number of clusters, we run the classical K-means algorithm and compare the resulting labels with those obtained using HDBSCAN. Even when provided with the correct number of clusters, K-means clearly fails to group the data into useful clusters. HDBSCAN, on the other hand, gives us the expected clustering. Briefly, K-means performs poorly because the underlying assumptions on the shape of the clusters are not met; it is a parametric algorithm parameterized by the K cluster centroids, the centers of gaussian spheres. K-means performs best when clusters are: “round” or spherical equally sized equally dense most dense in the center of the sphere not contaminated by noise/outliers Let us borrow a simpler example from ESLR [4] to illustrate how K-means can be sensitive to the shape of the clusters. Below are two clusterings from the same data. On the left, data was standardized before clustering. Without standardization, we get a “wrong” clustering. We go back to our original data set and by simply describing it, it becomes obvious why K-means has a hard time. The data set has: Clusters with arbitrary shapes Clusters of different sizes Clusters with different densities Some noise and maybe some outliers While each bullet point can be reasonably expected from a real-world dataset, each one can be problematic for parametric algorithms such as K-means. We might want to check if the assumptions of our algorithms are met before trusting their output. But, checking for these assumptions can be difficult when little is known about the data. This is unfortunate because one of the primary uses of clustering algorithms is data exploration where we are still in the process of understanding the data Therefore, a clustering algorithm that will be used for data exploration needs to have as few assumptions as possible so that the initial insights we get are “useful”; having fewer assumptions make it more robust and applicable to a wider range of real-world data. Now, we have an idea what type of data we are dealing with, let’s explore the core ideas of HDBSCAN and how it excels even when the data has: Arbitrarily shaped clusters Clusters with different sizes and densities Noise HDBSCAN uses a density-based approach which makes few implicit assumptions about the clusters. It is a non-parametric method that looks for a cluster hierarchy shaped by the multivariate modes of the underlying distribution. Rather than looking for clusters with a particular shape, it looks for regions of the data that are denser than the surrounding space. The mental image you can use is trying to separate the islands from the sea or mountains from its valleys. How do we define a “cluster”? The characteristics of what we intuitively think as a cluster can be poorly defined and are often context-specific. (See Christian Hennig’s talk [5] for an overview) If we go back to the original data set, the reason we identify clusters is that we see 6 dense regions surrounded by sparse and noisy space. One way of defining a cluster which is usually consistent with our intuitive notion of clusters is: highly dense regions separated by sparse regions. Look at the plot of 1-d simulated data. We can see 3 clusters. X is simulated data from a mixture of normal distributions, and we can plot the exact probability distribution of X. The peaks correspond to the densest regions and the troughs correspond to the sparse regions. This gives us another way of framing the problem assuming we know the underlying distribution, clusters are highly probable regions separated by improbable regions. Imagine the higher-dimensional probability distributions forming a landscape of mountains and valleys, where the mountains are your clusters. For those not as familiar, the two statements are practically the same: highly dense regions separated by sparse regions highly probable regions separated by improbable regions One describes the data through its probability distribution and the other through a random sample from that distribution. The PDF plot and the strip plot above are equivalent. PDF, probability density function, is interpreted as the probability of being within a small region around a point, and when looking at a sample from X, it can also be interpreted as the expected density around that point. Given the underlying distribution, we expect that regions that are more probable would tend to have more points (denser) in a random sample. Similarly, given a random sample, you can make inferences on the probability of a region based on the empirical density. Denser regions in the random sample correspond to more probable regions in the underlying distributions. In fact, if we look at the histogram of a random sample of X, we see that it looks exactly like the true distribution of X. The histogram is sometimes called the empirical probability distribution, and with enough data, we expect the histogram to converge to the true underlying distribution. Again, density = probability. Denser = more probable. Sadly, even with our “mountains and valleys” definition of clusters, it can be difficult to know whether or not something is a single cluster. Look at the example below where we shifted one of the modes of X to the right. Although we still have 3 peaks, do we have 3 clusters? In some contexts, we might consider 3 clusters. “Intuitively” we say there are just 2 clusters. How do we decide? By looking at the strip plot of X’, we can be a bit more certain that there are just 2 clusters. X has 3 clusters, and X’ has 2 clusters. At what point does the number of clusters change? One way to define this is to set some global threshold for the PDF of the underlying distribution. The connected components from the resulting level-sets are your clusters [3]. This is what the algorithm DBSCAN does, and doing at multiple levels would result to DeBaCl [7]. This might be appealing because of its simplicity but don’t be fooled! We end up with an extra hyperparameter, the threshold λ, which we might have to fine-tune. Moreover, this doesn’t work well for clusters with different densities. To help us choose, we color our cluster choices as shown in the illustration below. Should we consider blue and yellow, or green only? To choose, we look at which one “persists” more. Do we see them more together or apart? We can quantify this using the area of the colored regions. On the left, we see that the sum of the areas of the blue and yellow regions is greater than the area of the green region. This means that the 2 peaks are more prominent, so we decide that they are two separate clusters. On the right, we see that the area of green is much larger. This means that they are just “bumps” rather than peaks. So we say that they are just one cluster. In the literature [2], the area of the regions is the measure of persistence, and the method is called eom or excess of mass. A bit more formally, we maximize the total sum of persistence of the clusters under the constraint that the chosen clusters are non-overlapping. By getting multiple level-sets at different values of λ, we get a hierarchy. For a multidimensional setting, imagine the clusters are islands in the middle of the ocean. As you lower the sea level, the islands will start to “grow” and eventually islands will start to connect with one another. To be able to capture and represent these relationships between clusters (islands), we represent it as a hierarchy tree. This representation generalizes to higher dimensions and is a natural abstraction that is easier to represent as a data structure that we can traverse and manipulate. By convention, trees are drawn top-down, where the root (the node where everything is just one cluster) is at the top and the tree grows downward. If you are using the HDBSCAN library, you might use the clusterer.condensed_tree_.plot() API. The result of this, shown below, is equivalent to the one shown above. The encircled nodes correspond to the chosen clusters, which are the yellow, blue and red regions respectively. When using HDBSCAN, this particular plot may be useful for assessing the quality of your clusters and can help with fine-tuning the hyper-parameters, as we will discuss in the “Parameter Selection” section. In the previous section, we had access to the true PDF of the underlying distribution. However, the underlying distribution is almost always unknown for real-world data. Therefore, we have to estimate the PDF using the empirical density. We already discussed one way of doing this, using a histogram. However, this is only useful for one-dimensional data and becomes computationally intractable as we increase the number of dimensions. We need other ways to get the empirical PDF. Here are two ways: Counting the number of neighbors of a particular point within its ε-radius Finding the distance to the K-th nearest neighbor (which is what HDBSCAN uses) For each point, we draw a ε-radius hypersphere around the point and count the number of points within it. This is our local approximation of the density at that point in space. We do this for every point and we compare the estimated PDF with the true value of the PDF (which we only do now because we simulated the data and its distribution is something we defined). For our 1-dimensional simulated data, the neighbor count is highly correlated with the true value of the PDF. The higher the number of neighbors results in a higher estimated PDF. We see that this method results in good estimates of the PDF for our simulated data X. Note that this can be sensitive to the scale of the data and the sample size. You might need to iterate over several values of ε to get good results. In this one, we get the complement of the previous approach. Instead of setting ε then counting the neighbors, we determine the number of neighbors we want and find the smallest value of ε that would contain these K neighbors. The results are what we call core distances in HDBSCAN. Points with smaller core distances are in denser regions and would have a high estimate for the PDF. Points with larger core distances are in sparser regions because we have to travel larger distances to include enough neighbors. We try to estimate the PDF on our simulated data X. In the plots above, we use 1/core_distance as the estimate of the PDF. As expected, the estimates are highly correlated with the true PDF. While the previous method was sensitive to both the scale of the data and the size of the data set, this method is mainly sensitive to the size of the data set. If you scale each dimension equally, then all core distances will proportionally increase. The key takeaway here is: core distance = estimate of density (recall that) density = probability core distance = some estimate of the PDF So when we refer to a point’s core distance, you can think of implicitly referring to the PDF. Filtering points based on the core distance is similar to obtaining a level-set from the underlying distribution. Whenever we have core_distance ≤ ε, there is an implicit pdf(x) ≥ λ happening. There is always a mapping between ε and λ, and we will just use symbol λ for both core distances and the PDF for simplicity. Recall that in the previous examples, we get a level-set from the PDF and the resulting regions are our clusters. This was easy because a region was represented as some shape. But when we are dealing with points, how do we know what the different regions are? We have a small data set on the left and its corresponding PDF on the right. The first step is to find the level-set at someλ. We filter for regions pdf(x) ≥ λ or filter for points with core_distance ≤ λ . Now we need to find the different regions. This is done by connecting “nearby” points to each other. “Nearby” is determined by the current density level defined by λ and we say that two points are near enough if their Euclidean distance is less than λ. We draw a sphere with radius λ around each point. We connect the point to all points within its λ-sphere. If two points are connected they belong to the same region and should have the same color. Do this for every point and what we are left with are several connected components. These are our clusters. This is the clustering you get at some level-set. We continue to “lower the sea” and keep track as new clusters appear, some clusters grow and eventually some merge together. Here are four visualizations where we show 4 clusters at 4 different level-sets. We keep track of the different clusters so that we can build the hierarchy tree which we have previously discussed. I’d like to highlight that points can be inside the λ-sphere but they still won’t be connected. They have to be included in the level-set first so λ should be greater than its core distance for the point to be considered. The value of λ at which two points finally connected can be interpreted as some new distance. For two points to be connected they must be: In a dense enough region Close enough to each other For a and b, we get the following inequalities in terms of λ : core_distance(a) ≤ λcore_distance(b) ≤λdistance(a, b) ≤λ core_distance(a) ≤ λ core_distance(b) ≤λ distance(a, b) ≤λ (1) and (2) are for the “In a dense enough region”. (3) is for the “Close enough to each other” Combining these inequalities, the smallest value of λ needed to be able to directly connect a and b is mutual_reachability_distance(a, b) = max( core_distance(a), core_distance(b), distance(a, b)) This is called the mutual reachability distance in HDBSCAN literature. Note: This “lambda space” is a term not found in the literature. This is just for this blog. Instead of using Euclidean distance as our metric, we can now use the mutual reachability distance as our new metric. Using it as a metric is equivalent to embedding the points in some new metric space, which we would simply call λ-space*. This has an effect of spreading apart close points in sparse regions. Due to the randomness of a random sample, two points can be close to each other in a very sparse region. However, we expect points in sparse regions to be far apart from each other. By using the mutual reachability distance, points in sparse regions “repel other points” if they are too close to it, while points in very dense regions are unaffected. Below is a plot of the points in λ-space projected using Multidimensional Scaling to show its effect more concretely. We can see this repelling effect on the left and on top. The four points on the left are spread out the most because they are in a very sparse space. Recall that to build the hierarchy tree, we have the following steps: Set λ to the smallest value of the core distanceFilter for the points in the level-setConnect points that are at most λ units apartCreate new clusters, expand new clusters and merge clustersSet λ to the next smallest value of the core distance and go to step (2) Set λ to the smallest value of the core distance Filter for the points in the level-set Connect points that are at most λ units apart Create new clusters, expand new clusters and merge clusters Set λ to the next smallest value of the core distance and go to step (2) Notice that when doing step (3), connecting two points that already belong the same connected component is useless. What really matters are the connections across clusters. The connection that would connect two clusters correspond to the pair of points from two different clusters with the smallest mutual reachability distance. If we ignore these “useless” connections and only note the relevant ones, what we are left with is an ordered list of edges that always merge two clusters (connected components). This might sound complicated but this can be simplified if we consider the mutual reachability distance as our new metric: Embed the points in λ-space and consider each point as a separate clusterFind the shortest distance between two points from two different clustersMerge the two clustersGo back to step (2) until there is only one cluster Embed the points in λ-space and consider each point as a separate cluster Find the shortest distance between two points from two different clusters Merge the two clusters Go back to step (2) until there is only one cluster If this sounds familiar, it’s the classical agglomerative clustering. This is just the single linkage clustering in λ-space! Doing single linkage clustering in Euclidean space can be sensitive to noise since noisy points can form spurious bridges across islands. By embedding the points in λ-space, the “repelling effect” makes the clustering much more robust to noise. Single linkage clustering is conveniently equivalent to building a minimum spanning tree! So we can use all the efficient ways of constructing the MST from graph theory. Now we go through notes regarding the main parameters of HDBSCAN, min_samples and min_cluster_size , and HDBSCAN in general. Recall our simulated data X, where we are trying to estimate the true PDF. We try to estimate this using the core distances, which is the distance to the K-th nearest neighbor. The hyperparameter K is referred to as min_samples in the HDBSCAN API. These are just empirical observations from the simulated data. We compare the plot we have above with the estimated PDF based on different values of min_samples . As you can see, setting min_samples too low will result in very noisy estimates for the PDF since the core distances become sensitive to local variations in density. This can lead to spurious clusters or some big cluster can end up fragmenting into many small clusters. Setting min_samples too high can smoothen the PDF too much. The finer details of the PDF are lost, but at least you are able to capture the bigger more global structures of the underlying distribution. In the example above, the two small clusters were “blurred” into just one cluster. Determining the optimal value for min_samples might be difficult, and is ultimately data-dependent. Don’t be mislead by the high value of min_samples that we are using here. We used 1-d simulated data that has smooth variations in density across the domain and only 3 clusters. Typical real-world data are wholly different characteristics and smaller values for min_samples are enough. The insight on the smoothing effect definitely applicable in other datasets. Increasing the value of min_samples smoothens the estimated distribution so that small peaks flattened and we get to focus only on the denser regions. The simplest intuition for what min_samples does is provide a measure of how conservative you want you clustering to be. The larger the value of min_samples you provide, the more conservative the clustering – more points will be declared as noise, and clusters will be restricted to progressively more dense areas. [7] Be cautious, one possible side-effect of this is that it might require longer running times because you have to find more “nearest neighbors” per point, and might require more memory. Notice that the underlying PDF that we are trying to estimate is very smooth, but because we are trying to estimate with a sample, we expect some variance in our estimates. This results in a “bumpy” estimated PDF. Let’s focus on a small area of the PDF to illustrate this. What is the effect of this bumpiness in the hierarchy tree? Well, this affects the persistence measures of the clusters. Because the little bumps are interpreted as mini-clusters, the persistence measures of the true clusters are divided into small segments. Without removing the bumps, the main cluster may not be seen by the excess of mass method. Instead of seeing a large smooth mountain, it sees it as a collection of numerous mini-peaks. To solve this, we flatten these small bumps. This is implemented by “trimming” the clusters that are not big enough in the hierarchy tree. The effect of this is that the excess of mass method is no longer distracted by the small bumps and can now see the main cluster. min_cluster_size dictates the maximum size of a “bump” before it is considered a peak. By increasing the value of min_cluster_size you are, in a way, smoothening the estimated PDF so that the true peaks of the distributions become prominent. Since we have access to the true PDF of X, we know a good value of min_samples which will result in a smooth estimated PDF. If the estimates are good, then the min_cluster_size is not as important. Let’s say we used a smaller value for min_samples and set it to 100. If you look at the PDF plot it has the general shape of the PDF but there is noticeable variance. Even though we know there should only be 3 peaks, we see a lot of small peaks. If you see a more extreme version of this, perhaps you can’t even see the colors of the bars anymore, then that would mean that the hierarchy tree is complex. Maybe it’s because of the variance of the estimates or maybe that’s really how the data is structured. One way can address this is by increasing min_cluster_size, which helps HDBSCAN simplify the tree and concentrate on bigger more global structures. Although we’ve established that HDBSCAN can find clusters even with some arbitrary shape, it doesn’t mean there is no need for any data transformations. It really depends on your use cases. Scaling certain features can increase or decrease the influence of that feature. Also, some transformations such as log and square root transform can change the shape of the underlying distribution altogether. Another insight that should be noted is that classical ways of assessing and summarizing clusters may not be as meaningful when using HDSCAN. Some metrics such as the silhouette score work best when the clusters are round. For the “moons” dataset in sklearn, K-means has a better silhouette score than the result of HDBSCAN even though we see that the clusters in HDBSCAN are better. This also applies in summarizing the clusters by getting the mean of all the points of the cluster. This is very useful for K-means and is a good prototype of the cluster. But for HDBSCAN, it can be problematic because the clusters aren’t round. The mean point can be far from the actual cluster! This can be very misleading and can lead to wrong insight. You might want to use something like a medoid which is a point that is part of the cluster that is closest to all other points. But be careful, you can lose too much information to try to summarize a complex shape with just one point in space. This all really depends on what kind of clusters you prefer and the underlying data you are processing. See Henning’s talk [5] for an overview on cluster assessment. We’re done! We have discussed the core ideas of HDBSCAN! We will breeze through some specific implementation details as a recap. A rough sketch of the HDBSCAN’s implementation goes as follows: Compute the core distances per pointsUse the mutual_reachability(a, b) as a distance metric for each a, bConstruct a minimum spanning treePrune the treeChoose the clusters using “excess of mass” Compute the core distances per points Use the mutual_reachability(a, b) as a distance metric for each a, b Construct a minimum spanning tree Prune the tree Choose the clusters using “excess of mass” This basically is the way we “estimate the underlying pdf” The mutual reachability distance is a summary at what level of λ two points together will connect. This is what we use as a new metric. Building the minimum spanning tree is equivalent to single linkage clustering in λ-space, which is equivalent to iterating through every possible level-set and keeping track of the clusters. Briefly, since what we have is just an estimate PDF, we expect to have some variance. So even if the underlying distribution is very smooth, the estimated PDF can be very bumpy, and therefore result to a very complicated hierarchy tree. We use the parameter min_cluster_size to smoothen the curves of the estimated distribution and as a result, simplifying the tree into the condensed_tree_ Using the condensed tree, we can estimate the persistence of each cluster and then calculate for the optimal clustering as discussed in the previous section. [1] https://hdbscan.readthedocs.io/en/latest/how_hdbscan_works.html [2] McInnes, Leland, and John Healy. “Accelerated hierarchical density clustering.” arXiv preprint arXiv:1705.07321 (2017). [3] John Healy. HDBSCAN, Fast Density Based Clustering, the How and the Why. PyData NYC. 2018 [4] Hastie, Trevor, Robert Tibshirani, and Jerome Friedman. The elements of statistical learning: data mining, inference, and prediction. Springer Science & Business Media, 2009. [5] Christian Hennig. Assessing the quality of a clustering. PyData NYC. 2018. [6] Alessandro Rinaldo. DeBaCl: a Density-based Clustering Algorithm and its Properties. [7] https://hdbscan.readthedocs.io/en/latest/parameter_selection.html [8] Campello, Ricardo JGB, Davoud Moulavi, and Jörg Sander. “Density-based clustering based on hierarchical density estimates.” Pacific-Asia conference on knowledge discovery and data mining. Springer, Berlin, Heidelberg, 2013. Photos by Dan Otis on Unsplash, Creative Vix from Pexels, Egor Kamelev from Pexels, Jesse Gardner on Unsplash, Casey Horner on Unsplash, Keisuke Higashio on Unsplash, Kim Daniel on Unsplash
[ { "code": null, "e": 344, "s": 172, "text": "HDBSCAN is a clustering algorithm developed by Campello, Moulavi, and Sander [8]. It stands for “Hierarchical Density-Based Spatial Clustering of Applications with Noise.”" }, { "code": null, "e": 630, "s": 344, "text": "In this blog post, I will try to present in a top-down approach the key concepts to help understand how and why HDBSCAN works. This is meant to complement existing documentation such as sklearn’s “How HDBSCAN works” [1], and other works and presentations by McInnes and Healy [2], [3]." }, { "code": null, "e": 770, "s": 630, "text": "Let’s start at the very top. Before we even describe our clustering algorithm, we should ask, “what type of data are we trying to cluster?”" }, { "code": null, "e": 891, "s": 770, "text": "We want to have as few assumptions about our data as possible. Perhaps the only assumptions that we can safely make are:" }, { "code": null, "e": 918, "s": 891, "text": "There is noise in our data" }, { "code": null, "e": 975, "s": 918, "text": "There are clusters in our data which we hope to discover" }, { "code": null, "e": 1051, "s": 975, "text": "To motivate our discussion, we start with the data set used in [1] and [3]." }, { "code": null, "e": 1221, "s": 1051, "text": "With only 2 dimensions, we can plot the data and identify 6 “natural” clusters in our dataset. We hope to automatically identify these through some clustering algorithm." }, { "code": null, "e": 1369, "s": 1221, "text": "Knowing the expected number of clusters, we run the classical K-means algorithm and compare the resulting labels with those obtained using HDBSCAN." }, { "code": null, "e": 1549, "s": 1369, "text": "Even when provided with the correct number of clusters, K-means clearly fails to group the data into useful clusters. HDBSCAN, on the other hand, gives us the expected clustering." }, { "code": null, "e": 1804, "s": 1549, "text": "Briefly, K-means performs poorly because the underlying assumptions on the shape of the clusters are not met; it is a parametric algorithm parameterized by the K cluster centroids, the centers of gaussian spheres. K-means performs best when clusters are:" }, { "code": null, "e": 1825, "s": 1804, "text": "“round” or spherical" }, { "code": null, "e": 1839, "s": 1825, "text": "equally sized" }, { "code": null, "e": 1853, "s": 1839, "text": "equally dense" }, { "code": null, "e": 1892, "s": 1853, "text": "most dense in the center of the sphere" }, { "code": null, "e": 1927, "s": 1892, "text": "not contaminated by noise/outliers" }, { "code": null, "e": 2200, "s": 1927, "text": "Let us borrow a simpler example from ESLR [4] to illustrate how K-means can be sensitive to the shape of the clusters. Below are two clusterings from the same data. On the left, data was standardized before clustering. Without standardization, we get a “wrong” clustering." }, { "code": null, "e": 2331, "s": 2200, "text": "We go back to our original data set and by simply describing it, it becomes obvious why K-means has a hard time. The data set has:" }, { "code": null, "e": 2362, "s": 2331, "text": "Clusters with arbitrary shapes" }, { "code": null, "e": 2390, "s": 2362, "text": "Clusters of different sizes" }, { "code": null, "e": 2424, "s": 2390, "text": "Clusters with different densities" }, { "code": null, "e": 2459, "s": 2424, "text": "Some noise and maybe some outliers" }, { "code": null, "e": 2953, "s": 2459, "text": "While each bullet point can be reasonably expected from a real-world dataset, each one can be problematic for parametric algorithms such as K-means. We might want to check if the assumptions of our algorithms are met before trusting their output. But, checking for these assumptions can be difficult when little is known about the data. This is unfortunate because one of the primary uses of clustering algorithms is data exploration where we are still in the process of understanding the data" }, { "code": null, "e": 3218, "s": 2953, "text": "Therefore, a clustering algorithm that will be used for data exploration needs to have as few assumptions as possible so that the initial insights we get are “useful”; having fewer assumptions make it more robust and applicable to a wider range of real-world data." }, { "code": null, "e": 3360, "s": 3218, "text": "Now, we have an idea what type of data we are dealing with, let’s explore the core ideas of HDBSCAN and how it excels even when the data has:" }, { "code": null, "e": 3388, "s": 3360, "text": "Arbitrarily shaped clusters" }, { "code": null, "e": 3432, "s": 3388, "text": "Clusters with different sizes and densities" }, { "code": null, "e": 3438, "s": 3432, "text": "Noise" }, { "code": null, "e": 3905, "s": 3438, "text": "HDBSCAN uses a density-based approach which makes few implicit assumptions about the clusters. It is a non-parametric method that looks for a cluster hierarchy shaped by the multivariate modes of the underlying distribution. Rather than looking for clusters with a particular shape, it looks for regions of the data that are denser than the surrounding space. The mental image you can use is trying to separate the islands from the sea or mountains from its valleys." }, { "code": null, "e": 4101, "s": 3905, "text": "How do we define a “cluster”? The characteristics of what we intuitively think as a cluster can be poorly defined and are often context-specific. (See Christian Hennig’s talk [5] for an overview)" }, { "code": null, "e": 4242, "s": 4101, "text": "If we go back to the original data set, the reason we identify clusters is that we see 6 dense regions surrounded by sparse and noisy space." }, { "code": null, "e": 4392, "s": 4242, "text": "One way of defining a cluster which is usually consistent with our intuitive notion of clusters is: highly dense regions separated by sparse regions." }, { "code": null, "e": 4455, "s": 4392, "text": "Look at the plot of 1-d simulated data. We can see 3 clusters." }, { "code": null, "e": 4572, "s": 4455, "text": "X is simulated data from a mixture of normal distributions, and we can plot the exact probability distribution of X." }, { "code": null, "e": 4973, "s": 4572, "text": "The peaks correspond to the densest regions and the troughs correspond to the sparse regions. This gives us another way of framing the problem assuming we know the underlying distribution, clusters are highly probable regions separated by improbable regions. Imagine the higher-dimensional probability distributions forming a landscape of mountains and valleys, where the mountains are your clusters." }, { "code": null, "e": 5045, "s": 4973, "text": "For those not as familiar, the two statements are practically the same:" }, { "code": null, "e": 5094, "s": 5045, "text": "highly dense regions separated by sparse regions" }, { "code": null, "e": 5150, "s": 5094, "text": "highly probable regions separated by improbable regions" }, { "code": null, "e": 5272, "s": 5150, "text": "One describes the data through its probability distribution and the other through a random sample from that distribution." }, { "code": null, "e": 5549, "s": 5272, "text": "The PDF plot and the strip plot above are equivalent. PDF, probability density function, is interpreted as the probability of being within a small region around a point, and when looking at a sample from X, it can also be interpreted as the expected density around that point." }, { "code": null, "e": 5811, "s": 5549, "text": "Given the underlying distribution, we expect that regions that are more probable would tend to have more points (denser) in a random sample. Similarly, given a random sample, you can make inferences on the probability of a region based on the empirical density." }, { "code": null, "e": 5916, "s": 5811, "text": "Denser regions in the random sample correspond to more probable regions in the underlying distributions." }, { "code": null, "e": 6209, "s": 5916, "text": "In fact, if we look at the histogram of a random sample of X, we see that it looks exactly like the true distribution of X. The histogram is sometimes called the empirical probability distribution, and with enough data, we expect the histogram to converge to the true underlying distribution." }, { "code": null, "e": 6263, "s": 6209, "text": "Again, density = probability. Denser = more probable." }, { "code": null, "e": 6654, "s": 6263, "text": "Sadly, even with our “mountains and valleys” definition of clusters, it can be difficult to know whether or not something is a single cluster. Look at the example below where we shifted one of the modes of X to the right. Although we still have 3 peaks, do we have 3 clusters? In some contexts, we might consider 3 clusters. “Intuitively” we say there are just 2 clusters. How do we decide?" }, { "code": null, "e": 6751, "s": 6654, "text": "By looking at the strip plot of X’, we can be a bit more certain that there are just 2 clusters." }, { "code": null, "e": 6842, "s": 6751, "text": "X has 3 clusters, and X’ has 2 clusters. At what point does the number of clusters change?" }, { "code": null, "e": 7116, "s": 6842, "text": "One way to define this is to set some global threshold for the PDF of the underlying distribution. The connected components from the resulting level-sets are your clusters [3]. This is what the algorithm DBSCAN does, and doing at multiple levels would result to DeBaCl [7]." }, { "code": null, "e": 7350, "s": 7116, "text": "This might be appealing because of its simplicity but don’t be fooled! We end up with an extra hyperparameter, the threshold λ, which we might have to fine-tune. Moreover, this doesn’t work well for clusters with different densities." }, { "code": null, "e": 7485, "s": 7350, "text": "To help us choose, we color our cluster choices as shown in the illustration below. Should we consider blue and yellow, or green only?" }, { "code": null, "e": 7633, "s": 7485, "text": "To choose, we look at which one “persists” more. Do we see them more together or apart? We can quantify this using the area of the colored regions." }, { "code": null, "e": 7854, "s": 7633, "text": "On the left, we see that the sum of the areas of the blue and yellow regions is greater than the area of the green region. This means that the 2 peaks are more prominent, so we decide that they are two separate clusters." }, { "code": null, "e": 8013, "s": 7854, "text": "On the right, we see that the area of green is much larger. This means that they are just “bumps” rather than peaks. So we say that they are just one cluster." }, { "code": null, "e": 8284, "s": 8013, "text": "In the literature [2], the area of the regions is the measure of persistence, and the method is called eom or excess of mass. A bit more formally, we maximize the total sum of persistence of the clusters under the constraint that the chosen clusters are non-overlapping." }, { "code": null, "e": 8578, "s": 8284, "text": "By getting multiple level-sets at different values of λ, we get a hierarchy. For a multidimensional setting, imagine the clusters are islands in the middle of the ocean. As you lower the sea level, the islands will start to “grow” and eventually islands will start to connect with one another." }, { "code": null, "e": 8866, "s": 8578, "text": "To be able to capture and represent these relationships between clusters (islands), we represent it as a hierarchy tree. This representation generalizes to higher dimensions and is a natural abstraction that is easier to represent as a data structure that we can traverse and manipulate." }, { "code": null, "e": 9013, "s": 8866, "text": "By convention, trees are drawn top-down, where the root (the node where everything is just one cluster) is at the top and the tree grows downward." }, { "code": null, "e": 9290, "s": 9013, "text": "If you are using the HDBSCAN library, you might use the clusterer.condensed_tree_.plot() API. The result of this, shown below, is equivalent to the one shown above. The encircled nodes correspond to the chosen clusters, which are the yellow, blue and red regions respectively." }, { "code": null, "e": 9497, "s": 9290, "text": "When using HDBSCAN, this particular plot may be useful for assessing the quality of your clusters and can help with fine-tuning the hyper-parameters, as we will discuss in the “Parameter Selection” section." }, { "code": null, "e": 9667, "s": 9497, "text": "In the previous section, we had access to the true PDF of the underlying distribution. However, the underlying distribution is almost always unknown for real-world data." }, { "code": null, "e": 9933, "s": 9667, "text": "Therefore, we have to estimate the PDF using the empirical density. We already discussed one way of doing this, using a histogram. However, this is only useful for one-dimensional data and becomes computationally intractable as we increase the number of dimensions." }, { "code": null, "e": 9997, "s": 9933, "text": "We need other ways to get the empirical PDF. Here are two ways:" }, { "code": null, "e": 10072, "s": 9997, "text": "Counting the number of neighbors of a particular point within its ε-radius" }, { "code": null, "e": 10151, "s": 10072, "text": "Finding the distance to the K-th nearest neighbor (which is what HDBSCAN uses)" }, { "code": null, "e": 10328, "s": 10151, "text": "For each point, we draw a ε-radius hypersphere around the point and count the number of points within it. This is our local approximation of the density at that point in space." }, { "code": null, "e": 10518, "s": 10328, "text": "We do this for every point and we compare the estimated PDF with the true value of the PDF (which we only do now because we simulated the data and its distribution is something we defined)." }, { "code": null, "e": 10698, "s": 10518, "text": "For our 1-dimensional simulated data, the neighbor count is highly correlated with the true value of the PDF. The higher the number of neighbors results in a higher estimated PDF." }, { "code": null, "e": 10935, "s": 10698, "text": "We see that this method results in good estimates of the PDF for our simulated data X. Note that this can be sensitive to the scale of the data and the sample size. You might need to iterate over several values of ε to get good results." }, { "code": null, "e": 11162, "s": 10935, "text": "In this one, we get the complement of the previous approach. Instead of setting ε then counting the neighbors, we determine the number of neighbors we want and find the smallest value of ε that would contain these K neighbors." }, { "code": null, "e": 11448, "s": 11162, "text": "The results are what we call core distances in HDBSCAN. Points with smaller core distances are in denser regions and would have a high estimate for the PDF. Points with larger core distances are in sparser regions because we have to travel larger distances to include enough neighbors." }, { "code": null, "e": 11639, "s": 11448, "text": "We try to estimate the PDF on our simulated data X. In the plots above, we use 1/core_distance as the estimate of the PDF. As expected, the estimates are highly correlated with the true PDF." }, { "code": null, "e": 11891, "s": 11639, "text": "While the previous method was sensitive to both the scale of the data and the size of the data set, this method is mainly sensitive to the size of the data set. If you scale each dimension equally, then all core distances will proportionally increase." }, { "code": null, "e": 11917, "s": 11891, "text": "The key takeaway here is:" }, { "code": null, "e": 11953, "s": 11917, "text": "core distance = estimate of density" }, { "code": null, "e": 11989, "s": 11953, "text": "(recall that) density = probability" }, { "code": null, "e": 12030, "s": 11989, "text": "core distance = some estimate of the PDF" }, { "code": null, "e": 12239, "s": 12030, "text": "So when we refer to a point’s core distance, you can think of implicitly referring to the PDF. Filtering points based on the core distance is similar to obtaining a level-set from the underlying distribution." }, { "code": null, "e": 12443, "s": 12239, "text": "Whenever we have core_distance ≤ ε, there is an implicit pdf(x) ≥ λ happening. There is always a mapping between ε and λ, and we will just use symbol λ for both core distances and the PDF for simplicity." }, { "code": null, "e": 12703, "s": 12443, "text": "Recall that in the previous examples, we get a level-set from the PDF and the resulting regions are our clusters. This was easy because a region was represented as some shape. But when we are dealing with points, how do we know what the different regions are?" }, { "code": null, "e": 12780, "s": 12703, "text": "We have a small data set on the left and its corresponding PDF on the right." }, { "code": null, "e": 12909, "s": 12780, "text": "The first step is to find the level-set at someλ. We filter for regions pdf(x) ≥ λ or filter for points with core_distance ≤ λ ." }, { "code": null, "e": 13162, "s": 12909, "text": "Now we need to find the different regions. This is done by connecting “nearby” points to each other. “Nearby” is determined by the current density level defined by λ and we say that two points are near enough if their Euclidean distance is less than λ." }, { "code": null, "e": 13212, "s": 13162, "text": "We draw a sphere with radius λ around each point." }, { "code": null, "e": 13359, "s": 13212, "text": "We connect the point to all points within its λ-sphere. If two points are connected they belong to the same region and should have the same color." }, { "code": null, "e": 13467, "s": 13359, "text": "Do this for every point and what we are left with are several connected components. These are our clusters." }, { "code": null, "e": 13642, "s": 13467, "text": "This is the clustering you get at some level-set. We continue to “lower the sea” and keep track as new clusters appear, some clusters grow and eventually some merge together." }, { "code": null, "e": 13839, "s": 13642, "text": "Here are four visualizations where we show 4 clusters at 4 different level-sets. We keep track of the different clusters so that we can build the hierarchy tree which we have previously discussed." }, { "code": null, "e": 14061, "s": 13839, "text": "I’d like to highlight that points can be inside the λ-sphere but they still won’t be connected. They have to be included in the level-set first so λ should be greater than its core distance for the point to be considered." }, { "code": null, "e": 14200, "s": 14061, "text": "The value of λ at which two points finally connected can be interpreted as some new distance. For two points to be connected they must be:" }, { "code": null, "e": 14225, "s": 14200, "text": "In a dense enough region" }, { "code": null, "e": 14252, "s": 14225, "text": "Close enough to each other" }, { "code": null, "e": 14315, "s": 14252, "text": "For a and b, we get the following inequalities in terms of λ :" }, { "code": null, "e": 14372, "s": 14315, "text": "core_distance(a) ≤ λcore_distance(b) ≤λdistance(a, b) ≤λ" }, { "code": null, "e": 14393, "s": 14372, "text": "core_distance(a) ≤ λ" }, { "code": null, "e": 14413, "s": 14393, "text": "core_distance(b) ≤λ" }, { "code": null, "e": 14431, "s": 14413, "text": "distance(a, b) ≤λ" }, { "code": null, "e": 14527, "s": 14431, "text": "(1) and (2) are for the “In a dense enough region”. (3) is for the “Close enough to each other”" }, { "code": null, "e": 14630, "s": 14527, "text": "Combining these inequalities, the smallest value of λ needed to be able to directly connect a and b is" }, { "code": null, "e": 14735, "s": 14630, "text": "mutual_reachability_distance(a, b) = max( core_distance(a), core_distance(b), distance(a, b))" }, { "code": null, "e": 14806, "s": 14735, "text": "This is called the mutual reachability distance in HDBSCAN literature." }, { "code": null, "e": 14899, "s": 14806, "text": "Note: This “lambda space” is a term not found in the literature. This is just for this blog." }, { "code": null, "e": 15139, "s": 14899, "text": "Instead of using Euclidean distance as our metric, we can now use the mutual reachability distance as our new metric. Using it as a metric is equivalent to embedding the points in some new metric space, which we would simply call λ-space*." }, { "code": null, "e": 15209, "s": 15139, "text": "This has an effect of spreading apart close points in sparse regions." }, { "code": null, "e": 15560, "s": 15209, "text": "Due to the randomness of a random sample, two points can be close to each other in a very sparse region. However, we expect points in sparse regions to be far apart from each other. By using the mutual reachability distance, points in sparse regions “repel other points” if they are too close to it, while points in very dense regions are unaffected." }, { "code": null, "e": 15678, "s": 15560, "text": "Below is a plot of the points in λ-space projected using Multidimensional Scaling to show its effect more concretely." }, { "code": null, "e": 15828, "s": 15678, "text": "We can see this repelling effect on the left and on top. The four points on the left are spread out the most because they are in a very sparse space." }, { "code": null, "e": 15898, "s": 15828, "text": "Recall that to build the hierarchy tree, we have the following steps:" }, { "code": null, "e": 16161, "s": 15898, "text": "Set λ to the smallest value of the core distanceFilter for the points in the level-setConnect points that are at most λ units apartCreate new clusters, expand new clusters and merge clustersSet λ to the next smallest value of the core distance and go to step (2)" }, { "code": null, "e": 16210, "s": 16161, "text": "Set λ to the smallest value of the core distance" }, { "code": null, "e": 16249, "s": 16210, "text": "Filter for the points in the level-set" }, { "code": null, "e": 16295, "s": 16249, "text": "Connect points that are at most λ units apart" }, { "code": null, "e": 16355, "s": 16295, "text": "Create new clusters, expand new clusters and merge clusters" }, { "code": null, "e": 16428, "s": 16355, "text": "Set λ to the next smallest value of the core distance and go to step (2)" }, { "code": null, "e": 16936, "s": 16428, "text": "Notice that when doing step (3), connecting two points that already belong the same connected component is useless. What really matters are the connections across clusters. The connection that would connect two clusters correspond to the pair of points from two different clusters with the smallest mutual reachability distance. If we ignore these “useless” connections and only note the relevant ones, what we are left with is an ordered list of edges that always merge two clusters (connected components)." }, { "code": null, "e": 17059, "s": 16936, "text": "This might sound complicated but this can be simplified if we consider the mutual reachability distance as our new metric:" }, { "code": null, "e": 17279, "s": 17059, "text": "Embed the points in λ-space and consider each point as a separate clusterFind the shortest distance between two points from two different clustersMerge the two clustersGo back to step (2) until there is only one cluster" }, { "code": null, "e": 17353, "s": 17279, "text": "Embed the points in λ-space and consider each point as a separate cluster" }, { "code": null, "e": 17427, "s": 17353, "text": "Find the shortest distance between two points from two different clusters" }, { "code": null, "e": 17450, "s": 17427, "text": "Merge the two clusters" }, { "code": null, "e": 17502, "s": 17450, "text": "Go back to step (2) until there is only one cluster" }, { "code": null, "e": 17627, "s": 17502, "text": "If this sounds familiar, it’s the classical agglomerative clustering. This is just the single linkage clustering in λ-space!" }, { "code": null, "e": 17872, "s": 17627, "text": "Doing single linkage clustering in Euclidean space can be sensitive to noise since noisy points can form spurious bridges across islands. By embedding the points in λ-space, the “repelling effect” makes the clustering much more robust to noise." }, { "code": null, "e": 18042, "s": 17872, "text": "Single linkage clustering is conveniently equivalent to building a minimum spanning tree! So we can use all the efficient ways of constructing the MST from graph theory." }, { "code": null, "e": 18167, "s": 18042, "text": "Now we go through notes regarding the main parameters of HDBSCAN, min_samples and min_cluster_size , and HDBSCAN in general." }, { "code": null, "e": 18242, "s": 18167, "text": "Recall our simulated data X, where we are trying to estimate the true PDF." }, { "code": null, "e": 18415, "s": 18242, "text": "We try to estimate this using the core distances, which is the distance to the K-th nearest neighbor. The hyperparameter K is referred to as min_samples in the HDBSCAN API." }, { "code": null, "e": 18578, "s": 18415, "text": "These are just empirical observations from the simulated data. We compare the plot we have above with the estimated PDF based on different values of min_samples ." }, { "code": null, "e": 18848, "s": 18578, "text": "As you can see, setting min_samples too low will result in very noisy estimates for the PDF since the core distances become sensitive to local variations in density. This can lead to spurious clusters or some big cluster can end up fragmenting into many small clusters." }, { "code": null, "e": 19133, "s": 18848, "text": "Setting min_samples too high can smoothen the PDF too much. The finer details of the PDF are lost, but at least you are able to capture the bigger more global structures of the underlying distribution. In the example above, the two small clusters were “blurred” into just one cluster." }, { "code": null, "e": 19519, "s": 19133, "text": "Determining the optimal value for min_samples might be difficult, and is ultimately data-dependent. Don’t be mislead by the high value of min_samples that we are using here. We used 1-d simulated data that has smooth variations in density across the domain and only 3 clusters. Typical real-world data are wholly different characteristics and smaller values for min_samples are enough." }, { "code": null, "e": 19747, "s": 19519, "text": "The insight on the smoothing effect definitely applicable in other datasets. Increasing the value of min_samples smoothens the estimated distribution so that small peaks flattened and we get to focus only on the denser regions." }, { "code": null, "e": 20066, "s": 19747, "text": "The simplest intuition for what min_samples does is provide a measure of how conservative you want you clustering to be. The larger the value of min_samples you provide, the more conservative the clustering – more points will be declared as noise, and clusters will be restricted to progressively more dense areas. [7]" }, { "code": null, "e": 20250, "s": 20066, "text": "Be cautious, one possible side-effect of this is that it might require longer running times because you have to find more “nearest neighbors” per point, and might require more memory." }, { "code": null, "e": 20423, "s": 20250, "text": "Notice that the underlying PDF that we are trying to estimate is very smooth, but because we are trying to estimate with a sample, we expect some variance in our estimates." }, { "code": null, "e": 20523, "s": 20423, "text": "This results in a “bumpy” estimated PDF. Let’s focus on a small area of the PDF to illustrate this." }, { "code": null, "e": 20644, "s": 20523, "text": "What is the effect of this bumpiness in the hierarchy tree? Well, this affects the persistence measures of the clusters." }, { "code": null, "e": 20967, "s": 20644, "text": "Because the little bumps are interpreted as mini-clusters, the persistence measures of the true clusters are divided into small segments. Without removing the bumps, the main cluster may not be seen by the excess of mass method. Instead of seeing a large smooth mountain, it sees it as a collection of numerous mini-peaks." }, { "code": null, "e": 21236, "s": 20967, "text": "To solve this, we flatten these small bumps. This is implemented by “trimming” the clusters that are not big enough in the hierarchy tree. The effect of this is that the excess of mass method is no longer distracted by the small bumps and can now see the main cluster." }, { "code": null, "e": 21478, "s": 21236, "text": "min_cluster_size dictates the maximum size of a “bump” before it is considered a peak. By increasing the value of min_cluster_size you are, in a way, smoothening the estimated PDF so that the true peaks of the distributions become prominent." }, { "code": null, "e": 21676, "s": 21478, "text": "Since we have access to the true PDF of X, we know a good value of min_samples which will result in a smooth estimated PDF. If the estimates are good, then the min_cluster_size is not as important." }, { "code": null, "e": 21843, "s": 21676, "text": "Let’s say we used a smaller value for min_samples and set it to 100. If you look at the PDF plot it has the general shape of the PDF but there is noticeable variance." }, { "code": null, "e": 21922, "s": 21843, "text": "Even though we know there should only be 3 peaks, we see a lot of small peaks." }, { "code": null, "e": 22332, "s": 21922, "text": "If you see a more extreme version of this, perhaps you can’t even see the colors of the bars anymore, then that would mean that the hierarchy tree is complex. Maybe it’s because of the variance of the estimates or maybe that’s really how the data is structured. One way can address this is by increasing min_cluster_size, which helps HDBSCAN simplify the tree and concentrate on bigger more global structures." }, { "code": null, "e": 22522, "s": 22332, "text": "Although we’ve established that HDBSCAN can find clusters even with some arbitrary shape, it doesn’t mean there is no need for any data transformations. It really depends on your use cases." }, { "code": null, "e": 22732, "s": 22522, "text": "Scaling certain features can increase or decrease the influence of that feature. Also, some transformations such as log and square root transform can change the shape of the underlying distribution altogether." }, { "code": null, "e": 22955, "s": 22732, "text": "Another insight that should be noted is that classical ways of assessing and summarizing clusters may not be as meaningful when using HDSCAN. Some metrics such as the silhouette score work best when the clusters are round." }, { "code": null, "e": 23116, "s": 22955, "text": "For the “moons” dataset in sklearn, K-means has a better silhouette score than the result of HDBSCAN even though we see that the clusters in HDBSCAN are better." }, { "code": null, "e": 23362, "s": 23116, "text": "This also applies in summarizing the clusters by getting the mean of all the points of the cluster. This is very useful for K-means and is a good prototype of the cluster. But for HDBSCAN, it can be problematic because the clusters aren’t round." }, { "code": null, "e": 23716, "s": 23362, "text": "The mean point can be far from the actual cluster! This can be very misleading and can lead to wrong insight. You might want to use something like a medoid which is a point that is part of the cluster that is closest to all other points. But be careful, you can lose too much information to try to summarize a complex shape with just one point in space." }, { "code": null, "e": 23882, "s": 23716, "text": "This all really depends on what kind of clusters you prefer and the underlying data you are processing. See Henning’s talk [5] for an overview on cluster assessment." }, { "code": null, "e": 24011, "s": 23882, "text": "We’re done! We have discussed the core ideas of HDBSCAN! We will breeze through some specific implementation details as a recap." }, { "code": null, "e": 24075, "s": 24011, "text": "A rough sketch of the HDBSCAN’s implementation goes as follows:" }, { "code": null, "e": 24270, "s": 24075, "text": "Compute the core distances per pointsUse the mutual_reachability(a, b) as a distance metric for each a, bConstruct a minimum spanning treePrune the treeChoose the clusters using “excess of mass”" }, { "code": null, "e": 24308, "s": 24270, "text": "Compute the core distances per points" }, { "code": null, "e": 24377, "s": 24308, "text": "Use the mutual_reachability(a, b) as a distance metric for each a, b" }, { "code": null, "e": 24411, "s": 24377, "text": "Construct a minimum spanning tree" }, { "code": null, "e": 24426, "s": 24411, "text": "Prune the tree" }, { "code": null, "e": 24469, "s": 24426, "text": "Choose the clusters using “excess of mass”" }, { "code": null, "e": 24528, "s": 24469, "text": "This basically is the way we “estimate the underlying pdf”" }, { "code": null, "e": 24664, "s": 24528, "text": "The mutual reachability distance is a summary at what level of λ two points together will connect. This is what we use as a new metric." }, { "code": null, "e": 24855, "s": 24664, "text": "Building the minimum spanning tree is equivalent to single linkage clustering in λ-space, which is equivalent to iterating through every possible level-set and keeping track of the clusters." }, { "code": null, "e": 25092, "s": 24855, "text": "Briefly, since what we have is just an estimate PDF, we expect to have some variance. So even if the underlying distribution is very smooth, the estimated PDF can be very bumpy, and therefore result to a very complicated hierarchy tree." }, { "code": null, "e": 25246, "s": 25092, "text": "We use the parameter min_cluster_size to smoothen the curves of the estimated distribution and as a result, simplifying the tree into the condensed_tree_" }, { "code": null, "e": 25404, "s": 25246, "text": "Using the condensed tree, we can estimate the persistence of each cluster and then calculate for the optimal clustering as discussed in the previous section." }, { "code": null, "e": 25472, "s": 25404, "text": "[1] https://hdbscan.readthedocs.io/en/latest/how_hdbscan_works.html" }, { "code": null, "e": 25596, "s": 25472, "text": "[2] McInnes, Leland, and John Healy. “Accelerated hierarchical density clustering.” arXiv preprint arXiv:1705.07321 (2017)." }, { "code": null, "e": 25690, "s": 25596, "text": "[3] John Healy. HDBSCAN, Fast Density Based Clustering, the How and the Why. PyData NYC. 2018" }, { "code": null, "e": 25869, "s": 25690, "text": "[4] Hastie, Trevor, Robert Tibshirani, and Jerome Friedman. The elements of statistical learning: data mining, inference, and prediction. Springer Science & Business Media, 2009." }, { "code": null, "e": 25948, "s": 25869, "text": "[5] Christian Hennig. Assessing the quality of a clustering. PyData NYC. 2018." }, { "code": null, "e": 26037, "s": 25948, "text": "[6] Alessandro Rinaldo. DeBaCl: a Density-based Clustering Algorithm and its Properties." }, { "code": null, "e": 26107, "s": 26037, "text": "[7] https://hdbscan.readthedocs.io/en/latest/parameter_selection.html" }, { "code": null, "e": 26336, "s": 26107, "text": "[8] Campello, Ricardo JGB, Davoud Moulavi, and Jörg Sander. “Density-based clustering based on hierarchical density estimates.” Pacific-Asia conference on knowledge discovery and data mining. Springer, Berlin, Heidelberg, 2013." } ]
Removing empty fields from MongoDB
To remove empty fields, use deleteMany(). Let us first create a collection with documents − > db.removeEmptyFieldsDemo.insertOne({"StudentName":""}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92b9578f00858fb12e919") } > db.removeEmptyFieldsDemo.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92b9878f00858fb12e91a") } > db.removeEmptyFieldsDemo.insertOne({"StudentName":""}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92b9c78f00858fb12e91b") } > db.removeEmptyFieldsDemo.insertOne({"StudentName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92ba078f00858fb12e91c") } Following is the query to display all documents from a collection with the help of find() method − > db.removeEmptyFieldsDemo.find(); This will produce the following output − { "_id" : ObjectId("5ce92b9578f00858fb12e919"), "StudentName" : "" } { "_id" : ObjectId("5ce92b9878f00858fb12e91a"), "StudentName" : "Chris" } { "_id" : ObjectId("5ce92b9c78f00858fb12e91b"), "StudentName" : "" } { "_id" : ObjectId("5ce92ba078f00858fb12e91c"), "StudentName" : "Robert" } Following is the query to remove empty fields from MongoDB − > db.removeEmptyFieldsDemo.updateMany({"StudentName": ""}, { $unset : {"StudentName" : 1 }}); { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 } Let us check the document once again − > db.removeEmptyFieldsDemo.find(); This will produce the following output − { "_id" : ObjectId("5ce92b9578f00858fb12e919") } { "_id" : ObjectId("5ce92b9878f00858fb12e91a"), "StudentName" : "Chris" } { "_id" : ObjectId("5ce92b9c78f00858fb12e91b") } { "_id" : ObjectId("5ce92ba078f00858fb12e91c"), "StudentName" : "Robert" }
[ { "code": null, "e": 1154, "s": 1062, "text": "To remove empty fields, use deleteMany(). Let us first create a collection with documents −" }, { "code": null, "e": 1737, "s": 1154, "text": "> db.removeEmptyFieldsDemo.insertOne({\"StudentName\":\"\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce92b9578f00858fb12e919\")\n}\n> db.removeEmptyFieldsDemo.insertOne({\"StudentName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce92b9878f00858fb12e91a\")\n}\n> db.removeEmptyFieldsDemo.insertOne({\"StudentName\":\"\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce92b9c78f00858fb12e91b\")\n}\n> db.removeEmptyFieldsDemo.insertOne({\"StudentName\":\"Robert\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce92ba078f00858fb12e91c\")\n}" }, { "code": null, "e": 1836, "s": 1737, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1871, "s": 1836, "text": "> db.removeEmptyFieldsDemo.find();" }, { "code": null, "e": 1912, "s": 1871, "text": "This will produce the following output −" }, { "code": null, "e": 2199, "s": 1912, "text": "{ \"_id\" : ObjectId(\"5ce92b9578f00858fb12e919\"), \"StudentName\" : \"\" }\n{ \"_id\" : ObjectId(\"5ce92b9878f00858fb12e91a\"), \"StudentName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5ce92b9c78f00858fb12e91b\"), \"StudentName\" : \"\" }\n{ \"_id\" : ObjectId(\"5ce92ba078f00858fb12e91c\"), \"StudentName\" : \"Robert\" }" }, { "code": null, "e": 2260, "s": 2199, "text": "Following is the query to remove empty fields from MongoDB −" }, { "code": null, "e": 2421, "s": 2260, "text": "> db.removeEmptyFieldsDemo.updateMany({\"StudentName\": \"\"}, { $unset : {\"StudentName\" : 1 }});\n{ \"acknowledged\" : true, \"matchedCount\" : 2, \"modifiedCount\" : 2 }" }, { "code": null, "e": 2460, "s": 2421, "text": "Let us check the document once again −" }, { "code": null, "e": 2495, "s": 2460, "text": "> db.removeEmptyFieldsDemo.find();" }, { "code": null, "e": 2536, "s": 2495, "text": "This will produce the following output −" }, { "code": null, "e": 2783, "s": 2536, "text": "{ \"_id\" : ObjectId(\"5ce92b9578f00858fb12e919\") }\n{ \"_id\" : ObjectId(\"5ce92b9878f00858fb12e91a\"), \"StudentName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5ce92b9c78f00858fb12e91b\") }\n{ \"_id\" : ObjectId(\"5ce92ba078f00858fb12e91c\"), \"StudentName\" : \"Robert\" }" } ]
Causal Inference via CausalImpact | by Pranav Prathvikumar | Towards Data Science
Wikipedia defines it as the process of drawing a conclusion about a causal connection based on the conditions of the occurrence of an effect. In simpler words, Causal Inference is about determining the impact of an event/change on the desired outcome metric. Some instances of this being, if a newly launched marketing event has had an impact on the sales of the company or whether a new law has had an impact on how people behaved. While looking at graphs and comparing pre and post periods can give a good idea, but in most cases, this is simply not good enough. Especially in cases where there is a lot at stake, such as a multimillion-dollar marketing budget. Determining the causal impact of an event becomes even more critical in the fields of medicine or public policy, where such decisions can impact millions of people. Suppose there was an event/treatment that took place, such as a marketing event. Let's represent it by this pill: By observing we know that this is the outcome after the treatment : What is also important is to know what would have happened if the event did not take place. Let’s represent the outcome that would have happened otherwise with this: Now by comparing the two possible outcomes we can infer or measure the impact of the event. We can say that the customer being happy instead of sad is the impact of the treatment. But the question in the real world is, how do we do that? How can we simultaneously know what happened and what might have happened? In such a case how do we determine the causal inference of such an event? Let’s make it more clear by tabulating it and comparing the various scenarios: Let there be two people, 1 and 2, and they are both being exposed to the treatment/event. By exposing them both to the treatment we can also observe the outcomes presented. But then we do not know what the possible outcomes otherwise might have been. As it is not possible to know it, the next best thing we can do is estimate the other possible outcome. A randomized controlled trial is a scientific experiment for determining the impact of a treatment on the desired outcomes. This is usually employed in the medical fields and is considered as the gold standard. In an RCT people are randomly selected and divided into two groups, where one is exposed to the treatment and the other is not. Due to the randomness involved, both groups are considered similar and any differences in the outcomes can be attributed to the difference in treatments. Again, tabulating the above for a clearer understanding: Now there are four people, randomly selected and divided. Half are exposed to the treatment and the other half is not. The potential outcomes of the two groups are estimated based on the outcome of the other group. This estimated outcome is what is often known as a counter factual. While RCT is the best possible way to estimate causal inference, it might not be possible in all cases. Maybe conducting an RCT is too expensive or too difficult. For instance, it might be too difficult to conduct an RCT in a small country as it is difficult to separate into test and control. Or maybe a RCT was not done at all and a retrospective study is now being conducted to understand the impact. In such a case how do we estimate the outcome or the counter factual. It’s a library released by Google for performing causal inferences in these kinds of cases. This library is available only in R, so I will run through the logic behind it and how it works. It takes care of such situations with the help of what is known as synthetic controls. Take this graph of the Swiss Franc(CHF) to the Euro(EUR). For a long time, the Swiss Franc was pegged to the Euro and its value was stable. But after it was unpegged in 2015 it saw huge fluctuations. In this case, do we need a RCT so that we can determine what the Swiss Franc would have behaved like if it had not been unpegged? No. It is simple to say that it would have continued to be relatively stable with very few fluctuations. Now, this is what is known as a synthetic control. Now, this is possible here as it is a simple time series. Take for instance this graph: This is a more complex time series graph being influenced by multiple factors. Even state of the art techniques such as LSTM would find it difficult to predict it accurately. In this case, how do we predict the counter factual/synthetic control? We can make use of other variables or covariates to help in estimating the synthetic control. The trick here is to find the covariates which are correlated to the desired metric but are not affected by the treatment. In the above graph y is the desired metric and x1 and x2 below represent the two covariates. In the pre-period, we train and test a ML model to predict the desired metric using the covariates. In the post-period, we use the same model to predict the desired metric using the covariates. The predicted outcome is the synthetic control here. The actual outcome is then compared with the synthetic controls and the difference between the two is estimated to be the impact of the event on the outcome. The above is how Google’s CausalImpact works in short. Now you can experiment with various models to see which works. This can be done by dividing the pre-period of your data into a training and validation section to identify the best model. The Google package uses a Bayesian Structured Time Series model. For those of you who are unaware of how Bayesian Statistics works, I have written an article that you can access via this link. In short, Bayesian Statistics works by incorporating a prior belief on how something behaves like and over time updates the beliefs based on new data. Most time series models, are just that, a time series model. They cannot take into account the external factors which affects the changes and fluctuations. The advantage of the Bayesian time series model is that it takes into account both the time series aspect as well as the external factors which influence the outcome. It incorporates the external factors or the covariates in this case by taking them as priors for the model. This way it can account for both the temporal evolution as well as the external factors while predicting. Let's see a use of the CausalImpact package with some dummy data. library(CausalImpact)set.seed(1)x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100)x2 <- 25 + arima.sim(model = list(ma = 0.246), n = 100) I am importing the package and simulating two time series with the help of the arima.sim command. These will be the covariates. y <- 1.2 * x1 + 0.8*x2 + rnorm(100)y[71:100] <- y[71:100] + 10 Here I am creating a new time series y which is a function of our two time series x1 and x2. For the last 30 observations, I am adding an extra to the value to simulate the effects of an event/treatment. time.points <- seq.Date(as.Date("2020-01-01"), by = 1, length.out = 100)data <- zoo(cbind(y, x1, x2), time.points)matplot(data, type = "l") Adding the date component to the series and plotting it. pre.period <- as.Date(c("2020-01-01", "2020-03-10"))post.period <- as.Date(c("2020-03-11", "2020-04-09"))impact <- CausalImpact(data, pre.period, post.period) I define the pre and post periods based on where I added the treatment effects and then pass on the data and information to the package. plot(impact) The first plot superimposes the original data and the predictions at every point along with the confidence interval. The second plot displays the difference between the original and predicted data at every point along with the confidence interval. The third plot displays the cumulative effect of the treatment by summing up the pointwise differences. The ‘summary(impact)’ command can be used to give a tabular overview, while the ‘summary(impact, “report”) gives a written report of the findings. From the above, we get a better idea of the effect of the treatment along with the confidence intervals. The summary even gives the probability of the change due to the treatment itself so that we know that it is not any spurious relation or change. Causal Inference is a tricky problem that we data scientists rarely talk about. While this might be due to the fact that we generally don’t have to deal with this, still it is always good to know how to solve such a problem. It never hurts to have one more tool in our toolkit, one more weapon in our arsenal. Provided that the condition of finding covariates not influenced by the treatment is satisfied, this can indeed be a powerful technique to use in such scenarios. I came across this technique when we were taking part in the NUS-NUHS-MIT Healthcare Datathon of 2019. Our problem statement revolved around estimating the impact of an event on outcomes, i.e. Causal Inference. By using this package we were able to successfully complete our task and also got the first place in the datathon. Below is the pic of our amazing team made up of the best teammates possible without which this would not have been possible: You can connect with me on LinkedIn as well.
[ { "code": null, "e": 1001, "s": 172, "text": "Wikipedia defines it as the process of drawing a conclusion about a causal connection based on the conditions of the occurrence of an effect. In simpler words, Causal Inference is about determining the impact of an event/change on the desired outcome metric. Some instances of this being, if a newly launched marketing event has had an impact on the sales of the company or whether a new law has had an impact on how people behaved. While looking at graphs and comparing pre and post periods can give a good idea, but in most cases, this is simply not good enough. Especially in cases where there is a lot at stake, such as a multimillion-dollar marketing budget. Determining the causal impact of an event becomes even more critical in the fields of medicine or public policy, where such decisions can impact millions of people." }, { "code": null, "e": 1115, "s": 1001, "text": "Suppose there was an event/treatment that took place, such as a marketing event. Let's represent it by this pill:" }, { "code": null, "e": 1183, "s": 1115, "text": "By observing we know that this is the outcome after the treatment :" }, { "code": null, "e": 1349, "s": 1183, "text": "What is also important is to know what would have happened if the event did not take place. Let’s represent the outcome that would have happened otherwise with this:" }, { "code": null, "e": 1529, "s": 1349, "text": "Now by comparing the two possible outcomes we can infer or measure the impact of the event. We can say that the customer being happy instead of sad is the impact of the treatment." }, { "code": null, "e": 1736, "s": 1529, "text": "But the question in the real world is, how do we do that? How can we simultaneously know what happened and what might have happened? In such a case how do we determine the causal inference of such an event?" }, { "code": null, "e": 1815, "s": 1736, "text": "Let’s make it more clear by tabulating it and comparing the various scenarios:" }, { "code": null, "e": 2066, "s": 1815, "text": "Let there be two people, 1 and 2, and they are both being exposed to the treatment/event. By exposing them both to the treatment we can also observe the outcomes presented. But then we do not know what the possible outcomes otherwise might have been." }, { "code": null, "e": 2170, "s": 2066, "text": "As it is not possible to know it, the next best thing we can do is estimate the other possible outcome." }, { "code": null, "e": 2663, "s": 2170, "text": "A randomized controlled trial is a scientific experiment for determining the impact of a treatment on the desired outcomes. This is usually employed in the medical fields and is considered as the gold standard. In an RCT people are randomly selected and divided into two groups, where one is exposed to the treatment and the other is not. Due to the randomness involved, both groups are considered similar and any differences in the outcomes can be attributed to the difference in treatments." }, { "code": null, "e": 2720, "s": 2663, "text": "Again, tabulating the above for a clearer understanding:" }, { "code": null, "e": 2935, "s": 2720, "text": "Now there are four people, randomly selected and divided. Half are exposed to the treatment and the other half is not. The potential outcomes of the two groups are estimated based on the outcome of the other group." }, { "code": null, "e": 3003, "s": 2935, "text": "This estimated outcome is what is often known as a counter factual." }, { "code": null, "e": 3407, "s": 3003, "text": "While RCT is the best possible way to estimate causal inference, it might not be possible in all cases. Maybe conducting an RCT is too expensive or too difficult. For instance, it might be too difficult to conduct an RCT in a small country as it is difficult to separate into test and control. Or maybe a RCT was not done at all and a retrospective study is now being conducted to understand the impact." }, { "code": null, "e": 3477, "s": 3407, "text": "In such a case how do we estimate the outcome or the counter factual." }, { "code": null, "e": 3753, "s": 3477, "text": "It’s a library released by Google for performing causal inferences in these kinds of cases. This library is available only in R, so I will run through the logic behind it and how it works. It takes care of such situations with the help of what is known as synthetic controls." }, { "code": null, "e": 4083, "s": 3753, "text": "Take this graph of the Swiss Franc(CHF) to the Euro(EUR). For a long time, the Swiss Franc was pegged to the Euro and its value was stable. But after it was unpegged in 2015 it saw huge fluctuations. In this case, do we need a RCT so that we can determine what the Swiss Franc would have behaved like if it had not been unpegged?" }, { "code": null, "e": 4087, "s": 4083, "text": "No." }, { "code": null, "e": 4297, "s": 4087, "text": "It is simple to say that it would have continued to be relatively stable with very few fluctuations. Now, this is what is known as a synthetic control. Now, this is possible here as it is a simple time series." }, { "code": null, "e": 4327, "s": 4297, "text": "Take for instance this graph:" }, { "code": null, "e": 4573, "s": 4327, "text": "This is a more complex time series graph being influenced by multiple factors. Even state of the art techniques such as LSTM would find it difficult to predict it accurately. In this case, how do we predict the counter factual/synthetic control?" }, { "code": null, "e": 4790, "s": 4573, "text": "We can make use of other variables or covariates to help in estimating the synthetic control. The trick here is to find the covariates which are correlated to the desired metric but are not affected by the treatment." }, { "code": null, "e": 4883, "s": 4790, "text": "In the above graph y is the desired metric and x1 and x2 below represent the two covariates." }, { "code": null, "e": 4983, "s": 4883, "text": "In the pre-period, we train and test a ML model to predict the desired metric using the covariates." }, { "code": null, "e": 5288, "s": 4983, "text": "In the post-period, we use the same model to predict the desired metric using the covariates. The predicted outcome is the synthetic control here. The actual outcome is then compared with the synthetic controls and the difference between the two is estimated to be the impact of the event on the outcome." }, { "code": null, "e": 5530, "s": 5288, "text": "The above is how Google’s CausalImpact works in short. Now you can experiment with various models to see which works. This can be done by dividing the pre-period of your data into a training and validation section to identify the best model." }, { "code": null, "e": 5874, "s": 5530, "text": "The Google package uses a Bayesian Structured Time Series model. For those of you who are unaware of how Bayesian Statistics works, I have written an article that you can access via this link. In short, Bayesian Statistics works by incorporating a prior belief on how something behaves like and over time updates the beliefs based on new data." }, { "code": null, "e": 6411, "s": 5874, "text": "Most time series models, are just that, a time series model. They cannot take into account the external factors which affects the changes and fluctuations. The advantage of the Bayesian time series model is that it takes into account both the time series aspect as well as the external factors which influence the outcome. It incorporates the external factors or the covariates in this case by taking them as priors for the model. This way it can account for both the temporal evolution as well as the external factors while predicting." }, { "code": null, "e": 6477, "s": 6411, "text": "Let's see a use of the CausalImpact package with some dummy data." }, { "code": null, "e": 6621, "s": 6477, "text": "library(CausalImpact)set.seed(1)x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100)x2 <- 25 + arima.sim(model = list(ma = 0.246), n = 100)" }, { "code": null, "e": 6749, "s": 6621, "text": "I am importing the package and simulating two time series with the help of the arima.sim command. These will be the covariates." }, { "code": null, "e": 6812, "s": 6749, "text": "y <- 1.2 * x1 + 0.8*x2 + rnorm(100)y[71:100] <- y[71:100] + 10" }, { "code": null, "e": 7016, "s": 6812, "text": "Here I am creating a new time series y which is a function of our two time series x1 and x2. For the last 30 observations, I am adding an extra to the value to simulate the effects of an event/treatment." }, { "code": null, "e": 7156, "s": 7016, "text": "time.points <- seq.Date(as.Date(\"2020-01-01\"), by = 1, length.out = 100)data <- zoo(cbind(y, x1, x2), time.points)matplot(data, type = \"l\")" }, { "code": null, "e": 7213, "s": 7156, "text": "Adding the date component to the series and plotting it." }, { "code": null, "e": 7372, "s": 7213, "text": "pre.period <- as.Date(c(\"2020-01-01\", \"2020-03-10\"))post.period <- as.Date(c(\"2020-03-11\", \"2020-04-09\"))impact <- CausalImpact(data, pre.period, post.period)" }, { "code": null, "e": 7509, "s": 7372, "text": "I define the pre and post periods based on where I added the treatment effects and then pass on the data and information to the package." }, { "code": null, "e": 7522, "s": 7509, "text": "plot(impact)" }, { "code": null, "e": 7639, "s": 7522, "text": "The first plot superimposes the original data and the predictions at every point along with the confidence interval." }, { "code": null, "e": 7770, "s": 7639, "text": "The second plot displays the difference between the original and predicted data at every point along with the confidence interval." }, { "code": null, "e": 7874, "s": 7770, "text": "The third plot displays the cumulative effect of the treatment by summing up the pointwise differences." }, { "code": null, "e": 8021, "s": 7874, "text": "The ‘summary(impact)’ command can be used to give a tabular overview, while the ‘summary(impact, “report”) gives a written report of the findings." }, { "code": null, "e": 8271, "s": 8021, "text": "From the above, we get a better idea of the effect of the treatment along with the confidence intervals. The summary even gives the probability of the change due to the treatment itself so that we know that it is not any spurious relation or change." }, { "code": null, "e": 8743, "s": 8271, "text": "Causal Inference is a tricky problem that we data scientists rarely talk about. While this might be due to the fact that we generally don’t have to deal with this, still it is always good to know how to solve such a problem. It never hurts to have one more tool in our toolkit, one more weapon in our arsenal. Provided that the condition of finding covariates not influenced by the treatment is satisfied, this can indeed be a powerful technique to use in such scenarios." }, { "code": null, "e": 9194, "s": 8743, "text": "I came across this technique when we were taking part in the NUS-NUHS-MIT Healthcare Datathon of 2019. Our problem statement revolved around estimating the impact of an event on outcomes, i.e. Causal Inference. By using this package we were able to successfully complete our task and also got the first place in the datathon. Below is the pic of our amazing team made up of the best teammates possible without which this would not have been possible:" } ]
C# factorial
To calculate factorial in C#, you can use while loop and loop through until the number is not equal to 1. Here n is the value for which you want the factorial − int res = 1; while (n != 1) { res = res * n; n = n - 1; } Above, let’s say we want 5! (5 factorial) For that, n=5, Loop Iteration 1 − n=5 res = res*n i.e res =5; Loop Iteration 2 − n=4 res = res*n i.e. res = 5*4 = 20 Loop Iteration 3 − n=3 res = res*n i.e. res = 20*3 = 60 In this way, all the iterations will give the result as 120 for 5! as shown in the following example. Live Demo using System; namespace MyApplication { class Factorial { public int display(int n) { int res = 1; while (n != 1) { res = res * n; n = n - 1; } return res; } static void Main(string[] args) { int value = 5; int ret; Factorial fact = new Factorial(); ret = fact.display(value); Console.WriteLine("Value is : {0}", ret ); Console.ReadLine(); } } } Value is : 120
[ { "code": null, "e": 1168, "s": 1062, "text": "To calculate factorial in C#, you can use while loop and loop through until the number is not equal to 1." }, { "code": null, "e": 1223, "s": 1168, "text": "Here n is the value for which you want the factorial −" }, { "code": null, "e": 1287, "s": 1223, "text": "int res = 1;\nwhile (n != 1) {\n res = res * n;\n n = n - 1;\n}" }, { "code": null, "e": 1329, "s": 1287, "text": "Above, let’s say we want 5! (5 factorial)" }, { "code": null, "e": 1344, "s": 1329, "text": "For that, n=5," }, { "code": null, "e": 1363, "s": 1344, "text": "Loop Iteration 1 −" }, { "code": null, "e": 1391, "s": 1363, "text": "n=5\nres = res*n i.e res =5;" }, { "code": null, "e": 1410, "s": 1391, "text": "Loop Iteration 2 −" }, { "code": null, "e": 1446, "s": 1410, "text": "n=4\nres = res*n i.e. res = 5*4 = 20" }, { "code": null, "e": 1465, "s": 1446, "text": "Loop Iteration 3 −" }, { "code": null, "e": 1502, "s": 1465, "text": "n=3\nres = res*n i.e. res = 20*3 = 60" }, { "code": null, "e": 1604, "s": 1502, "text": "In this way, all the iterations will give the result as 120 for 5! as shown in the following example." }, { "code": null, "e": 1614, "s": 1604, "text": "Live Demo" }, { "code": null, "e": 2104, "s": 1614, "text": "using System;\nnamespace MyApplication {\n class Factorial {\n public int display(int n) {\n int res = 1;\n while (n != 1) {\n res = res * n;\n n = n - 1;\n }\n return res;\n }\n static void Main(string[] args) {\n int value = 5;\n int ret;\n Factorial fact = new Factorial();\n ret = fact.display(value);\n Console.WriteLine(\"Value is : {0}\", ret );\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2119, "s": 2104, "text": "Value is : 120" } ]
Support Vector Machines (SVM) clearly explained: A python tutorial for classification problems with 3D plots | by Serafeim Loukas | Towards Data Science
Everyone has heard about the famous and widely-used Support Vector Machines (SVMs). The original SVM algorithm was invented by Vladimir N. Vapnik and Alexey Ya. Chervonenkis in 1963. SVMs are supervised machine learning models that are usually employed for classification (SVC — Support Vector Classification) or regression (SVR — Support Vector Regression) problems. Depending on the characteristics of target variable (that we wish to predict), our problem is going to be a classification task if we have a discrete target variable (e.g. class labels), or a regression task if we have a continuous target variable (e.g. house prices). SVMs are more commonly used for classification problems and for this reason, in this article, I will only focus on the SVC models. In this article, I am not going to go through every step of the algorithm (due to the numerous amount of online resources) but instead, I am going to explain the most important concepts and terms around SVMs. The SVCs aim to find the best hyperplane (also called decision boundary) that best separates (splits) a dataset into two classes/groups (binary classification problem). Depending of the number of the input features/variables, the decision boundary can be a line (if we had only 2 features) or a hyperplane if we have more than 2 features in our dataset. To get the main idea think the following: Each observation (or sample/data-point) is plotted in an N-dimensional space with Nbeing the number of features/variables in our dataset. In that space, the separating hyperplane is an (N-1)-dimensional subspace. A hyperplane is an (N-1)-dimensional subspace for an N-dimensional space. So, as stated before, for an 2-dimensional space the decision boundary is going to be just a line as shown below. Mathematically, we can define the decision boundary as follows: The Support vectors are just the samples (data-points) that are located nearest to the separating hyperplane. These samples would alter the position of the separating hyperplane, in the event of their removal. Thus, these are the most important samples that define the location and orientation of best decision boundary. Several different lines (or generally, different decision boundaries) could separate our classes. But which of all is the best one? The distance between the hyperplane and the nearest data points (samples) is known as the SVM margin. The goal is to choose a hyperplane with the greatest possible margin between the hyperplane and any support vector. SVM algorithm finds the best decision boundary such as the margin is maximized. Here the best line is the yellow line as shown below. In summary, SVMs pick the decision boundary that maximizes the distance to the support vectors. The decision boundary is drawn in a way that the distance to support vectors are maximized. If the decision boundary is too close to the support vectors then, it will be sensitive to noise and not generalize well. Sometimes, we might want to allow (on purpose) some margin of error (misclassification). This is the main idea behind the “soft margin”. The soft margin implementation allows some samples to be misclassified or be on the wrong side of decision boundary allowing highly generalized model. A soft margin SVM solves the following optimization problem: Increase the distance of decision boundary to the support vectors (i.e. the margin) and Maximize the number of points that are correctly classified in the training set. It is clear that there is a trade-off between these two optimization goals. This trade-off is controlled by the famous C parameter. Briefly, if C is small, the penalty for misclassified data-points is low so a decision boundary with a large margin is chosen at the expense of a greater number of misclassifications. If C is large, SVM tries to minimize the number of misclassified samples and results in a decision boundary with a smaller margin. If we have a dataset that is linearly separable then SVMs job is usually easy. However, in real life, in most of the cases we have a linearly non-separable dataset at hand and this is when the kernel trick provides some magic. The kernel trick projects the original data points in a higher dimensional space in order to make them linearly separable (in that higher dimensional space). Thus, by using the kernel trick we can make our non linearly-separable data, linearly separable in a higher dimensional space. The kernel trick is based on some Kernel functions that measure similarity of the samples. The trick does not actually transform the data points to a new, high dimensional feature space, explicitly. The kernel-SVM computes the decision boundary in terms of similarity measures in a high-dimensional feature space without actually doing the projection. Some famous kernel functions include linear, polynomial, radial basis function (RBF), and sigmoid kernels. Reminder: The Iris dataset consists of 150 samples of flowers each having 4 features/variables (i.e. sepal width/length and petal width/length). Let’s plot the decision boundary in 2D (we will only use 2 features of the dataset): from sklearn.svm import SVCimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasetsiris = datasets.load_iris()# Select 2 features / variablesX = iris.data[:, :2] # we only take the first two features.y = iris.targetfeature_names = iris.feature_names[:2]classes = iris.target_namesdef make_meshgrid(x, y, h=.02): x_min, x_max = x.min() — 1, x.max() + 1 y_min, y_max = y.min() — 1, y.max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) return xx, yydef plot_contours(ax, clf, xx, yy, **params): Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) out = ax.contourf(xx, yy, Z, **params) return out# The classification SVC modelmodel = svm.SVC(kernel="linear")clf = model.fit(X, y)fig, ax = plt.subplots()# title for the plotstitle = (‘Decision surface of linear SVC ‘)# Set-up grid for plotting.X0, X1 = X[:, 0], X[:, 1]xx, yy = make_meshgrid(X0, X1)plot_contours(ax, clf, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors="k")ax.set_ylabel("{}".format(feature_names[0]))ax.set_xlabel("{}".format(feature_names[1]))ax.set_xticks(())ax.set_yticks(())ax.set_title(title)plt.show() In the iris dataset, we have 3 classes of flowers and 4 features. Here we only used 2 features (so we have a 2-dimensional feature space) and we plotted the decision boundary of the linear SVC model. The colors of the points correspond to the classes/groups. Let’s plot the decision boundary in 3D (we will only use 3features of the dataset): from sklearn.svm import SVCimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasetsfrom mpl_toolkits.mplot3d import Axes3Diris = datasets.load_iris()X = iris.data[:, :3] # we only take the first three features.Y = iris.target#make it binary classification problemX = X[np.logical_or(Y==0,Y==1)]Y = Y[np.logical_or(Y==0,Y==1)]model = svm.SVC(kernel='linear')clf = model.fit(X, Y)# The equation of the separating plane is given by all x so that np.dot(svc.coef_[0], x) + b = 0.# Solve for w3 (z)z = lambda x,y: (-clf.intercept_[0]-clf.coef_[0][0]*x -clf.coef_[0][1]*y) / clf.coef_[0][2]tmp = np.linspace(-5,5,30)x,y = np.meshgrid(tmp,tmp)fig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.plot3D(X[Y==0,0], X[Y==0,1], X[Y==0,2],'ob')ax.plot3D(X[Y==1,0], X[Y==1,1], X[Y==1,2],'sr')ax.plot_surface(x, y, z(x,y))ax.view_init(30, 60)plt.show() In the iris dataset, we have 3 classes of flowers and 4 features. Here we only used 3 features (so we have a 3-dimensional feature space) and only 2 classes (binary classification problem). We then plotted the decision boundary of the linear SVC model. The colors of the points correspond to the 2 classes/groups. import numpy as npimport matplotlib.pyplot as pltfrom sklearn import svmnp.random.seed(2)# we create 40 linearly separable pointsX = np.r_[np.random.randn(20, 2) — [2, 2], np.random.randn(20, 2) + [2, 2]]Y = [0] * 20 + [1] * 20# fit the modelclf = svm.SVC(kernel=’linear’, C=1)clf.fit(X, Y)# get the separating hyperplanew = clf.coef_[0]a = -w[0] / w[1]xx = np.linspace(-5, 5)yy = a * xx — (clf.intercept_[0]) / w[1]margin = 1 / np.sqrt(np.sum(clf.coef_ ** 2))yy_down = yy — np.sqrt(1 + a ** 2) * marginyy_up = yy + np.sqrt(1 + a ** 2) * marginplt.figure(1, figsize=(4, 3))plt.clf()plt.plot(xx, yy, "k-")plt.plot(xx, yy_down, "k-")plt.plot(xx, yy_up, "k-")plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors="none", zorder=10, edgecolors="k")plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired, edgecolors="k")plt.xlabel("x1")plt.ylabel("x2")plt.show() The double-circled points represent the support vectors. towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com If you liked and found this article useful, follow me! Questions? Post them as a comment and I will reply as soon as possible. [1] https://www.nature.com/articles/nbt1206-1565 [1] https://en.wikipedia.org/wiki/Support_vector_machine [2] https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html LinkedIn: https://www.linkedin.com/in/serafeim-loukas/ ResearchGate: https://www.researchgate.net/profile/Serafeim_Loukas EPFL profile: https://people.epfl.ch/serafeim.loukas Stack Overflow: https://stackoverflow.com/users/5025009/seralouk
[ { "code": null, "e": 354, "s": 171, "text": "Everyone has heard about the famous and widely-used Support Vector Machines (SVMs). The original SVM algorithm was invented by Vladimir N. Vapnik and Alexey Ya. Chervonenkis in 1963." }, { "code": null, "e": 808, "s": 354, "text": "SVMs are supervised machine learning models that are usually employed for classification (SVC — Support Vector Classification) or regression (SVR — Support Vector Regression) problems. Depending on the characteristics of target variable (that we wish to predict), our problem is going to be a classification task if we have a discrete target variable (e.g. class labels), or a regression task if we have a continuous target variable (e.g. house prices)." }, { "code": null, "e": 939, "s": 808, "text": "SVMs are more commonly used for classification problems and for this reason, in this article, I will only focus on the SVC models." }, { "code": null, "e": 1148, "s": 939, "text": "In this article, I am not going to go through every step of the algorithm (due to the numerous amount of online resources) but instead, I am going to explain the most important concepts and terms around SVMs." }, { "code": null, "e": 1317, "s": 1148, "text": "The SVCs aim to find the best hyperplane (also called decision boundary) that best separates (splits) a dataset into two classes/groups (binary classification problem)." }, { "code": null, "e": 1502, "s": 1317, "text": "Depending of the number of the input features/variables, the decision boundary can be a line (if we had only 2 features) or a hyperplane if we have more than 2 features in our dataset." }, { "code": null, "e": 1757, "s": 1502, "text": "To get the main idea think the following: Each observation (or sample/data-point) is plotted in an N-dimensional space with Nbeing the number of features/variables in our dataset. In that space, the separating hyperplane is an (N-1)-dimensional subspace." }, { "code": null, "e": 1831, "s": 1757, "text": "A hyperplane is an (N-1)-dimensional subspace for an N-dimensional space." }, { "code": null, "e": 1945, "s": 1831, "text": "So, as stated before, for an 2-dimensional space the decision boundary is going to be just a line as shown below." }, { "code": null, "e": 2009, "s": 1945, "text": "Mathematically, we can define the decision boundary as follows:" }, { "code": null, "e": 2330, "s": 2009, "text": "The Support vectors are just the samples (data-points) that are located nearest to the separating hyperplane. These samples would alter the position of the separating hyperplane, in the event of their removal. Thus, these are the most important samples that define the location and orientation of best decision boundary." }, { "code": null, "e": 2462, "s": 2330, "text": "Several different lines (or generally, different decision boundaries) could separate our classes. But which of all is the best one?" }, { "code": null, "e": 2814, "s": 2462, "text": "The distance between the hyperplane and the nearest data points (samples) is known as the SVM margin. The goal is to choose a hyperplane with the greatest possible margin between the hyperplane and any support vector. SVM algorithm finds the best decision boundary such as the margin is maximized. Here the best line is the yellow line as shown below." }, { "code": null, "e": 3124, "s": 2814, "text": "In summary, SVMs pick the decision boundary that maximizes the distance to the support vectors. The decision boundary is drawn in a way that the distance to support vectors are maximized. If the decision boundary is too close to the support vectors then, it will be sensitive to noise and not generalize well." }, { "code": null, "e": 3412, "s": 3124, "text": "Sometimes, we might want to allow (on purpose) some margin of error (misclassification). This is the main idea behind the “soft margin”. The soft margin implementation allows some samples to be misclassified or be on the wrong side of decision boundary allowing highly generalized model." }, { "code": null, "e": 3473, "s": 3412, "text": "A soft margin SVM solves the following optimization problem:" }, { "code": null, "e": 3561, "s": 3473, "text": "Increase the distance of decision boundary to the support vectors (i.e. the margin) and" }, { "code": null, "e": 3642, "s": 3561, "text": "Maximize the number of points that are correctly classified in the training set." }, { "code": null, "e": 4089, "s": 3642, "text": "It is clear that there is a trade-off between these two optimization goals. This trade-off is controlled by the famous C parameter. Briefly, if C is small, the penalty for misclassified data-points is low so a decision boundary with a large margin is chosen at the expense of a greater number of misclassifications. If C is large, SVM tries to minimize the number of misclassified samples and results in a decision boundary with a smaller margin." }, { "code": null, "e": 4316, "s": 4089, "text": "If we have a dataset that is linearly separable then SVMs job is usually easy. However, in real life, in most of the cases we have a linearly non-separable dataset at hand and this is when the kernel trick provides some magic." }, { "code": null, "e": 4474, "s": 4316, "text": "The kernel trick projects the original data points in a higher dimensional space in order to make them linearly separable (in that higher dimensional space)." }, { "code": null, "e": 4601, "s": 4474, "text": "Thus, by using the kernel trick we can make our non linearly-separable data, linearly separable in a higher dimensional space." }, { "code": null, "e": 5060, "s": 4601, "text": "The kernel trick is based on some Kernel functions that measure similarity of the samples. The trick does not actually transform the data points to a new, high dimensional feature space, explicitly. The kernel-SVM computes the decision boundary in terms of similarity measures in a high-dimensional feature space without actually doing the projection. Some famous kernel functions include linear, polynomial, radial basis function (RBF), and sigmoid kernels." }, { "code": null, "e": 5205, "s": 5060, "text": "Reminder: The Iris dataset consists of 150 samples of flowers each having 4 features/variables (i.e. sepal width/length and petal width/length)." }, { "code": null, "e": 5290, "s": 5205, "text": "Let’s plot the decision boundary in 2D (we will only use 2 features of the dataset):" }, { "code": null, "e": 6523, "s": 5290, "text": "from sklearn.svm import SVCimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasetsiris = datasets.load_iris()# Select 2 features / variablesX = iris.data[:, :2] # we only take the first two features.y = iris.targetfeature_names = iris.feature_names[:2]classes = iris.target_namesdef make_meshgrid(x, y, h=.02): x_min, x_max = x.min() — 1, x.max() + 1 y_min, y_max = y.min() — 1, y.max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) return xx, yydef plot_contours(ax, clf, xx, yy, **params): Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) out = ax.contourf(xx, yy, Z, **params) return out# The classification SVC modelmodel = svm.SVC(kernel=\"linear\")clf = model.fit(X, y)fig, ax = plt.subplots()# title for the plotstitle = (‘Decision surface of linear SVC ‘)# Set-up grid for plotting.X0, X1 = X[:, 0], X[:, 1]xx, yy = make_meshgrid(X0, X1)plot_contours(ax, clf, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors=\"k\")ax.set_ylabel(\"{}\".format(feature_names[0]))ax.set_xlabel(\"{}\".format(feature_names[1]))ax.set_xticks(())ax.set_yticks(())ax.set_title(title)plt.show()" }, { "code": null, "e": 6782, "s": 6523, "text": "In the iris dataset, we have 3 classes of flowers and 4 features. Here we only used 2 features (so we have a 2-dimensional feature space) and we plotted the decision boundary of the linear SVC model. The colors of the points correspond to the classes/groups." }, { "code": null, "e": 6866, "s": 6782, "text": "Let’s plot the decision boundary in 3D (we will only use 3features of the dataset):" }, { "code": null, "e": 7742, "s": 6866, "text": "from sklearn.svm import SVCimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasetsfrom mpl_toolkits.mplot3d import Axes3Diris = datasets.load_iris()X = iris.data[:, :3] # we only take the first three features.Y = iris.target#make it binary classification problemX = X[np.logical_or(Y==0,Y==1)]Y = Y[np.logical_or(Y==0,Y==1)]model = svm.SVC(kernel='linear')clf = model.fit(X, Y)# The equation of the separating plane is given by all x so that np.dot(svc.coef_[0], x) + b = 0.# Solve for w3 (z)z = lambda x,y: (-clf.intercept_[0]-clf.coef_[0][0]*x -clf.coef_[0][1]*y) / clf.coef_[0][2]tmp = np.linspace(-5,5,30)x,y = np.meshgrid(tmp,tmp)fig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.plot3D(X[Y==0,0], X[Y==0,1], X[Y==0,2],'ob')ax.plot3D(X[Y==1,0], X[Y==1,1], X[Y==1,2],'sr')ax.plot_surface(x, y, z(x,y))ax.view_init(30, 60)plt.show()" }, { "code": null, "e": 8056, "s": 7742, "text": "In the iris dataset, we have 3 classes of flowers and 4 features. Here we only used 3 features (so we have a 3-dimensional feature space) and only 2 classes (binary classification problem). We then plotted the decision boundary of the linear SVC model. The colors of the points correspond to the 2 classes/groups." }, { "code": null, "e": 8955, "s": 8056, "text": "import numpy as npimport matplotlib.pyplot as pltfrom sklearn import svmnp.random.seed(2)# we create 40 linearly separable pointsX = np.r_[np.random.randn(20, 2) — [2, 2], np.random.randn(20, 2) + [2, 2]]Y = [0] * 20 + [1] * 20# fit the modelclf = svm.SVC(kernel=’linear’, C=1)clf.fit(X, Y)# get the separating hyperplanew = clf.coef_[0]a = -w[0] / w[1]xx = np.linspace(-5, 5)yy = a * xx — (clf.intercept_[0]) / w[1]margin = 1 / np.sqrt(np.sum(clf.coef_ ** 2))yy_down = yy — np.sqrt(1 + a ** 2) * marginyy_up = yy + np.sqrt(1 + a ** 2) * marginplt.figure(1, figsize=(4, 3))plt.clf()plt.plot(xx, yy, \"k-\")plt.plot(xx, yy_down, \"k-\")plt.plot(xx, yy_up, \"k-\")plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors=\"none\", zorder=10, edgecolors=\"k\")plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired, edgecolors=\"k\")plt.xlabel(\"x1\")plt.ylabel(\"x2\")plt.show()" }, { "code": null, "e": 9012, "s": 8955, "text": "The double-circled points represent the support vectors." }, { "code": null, "e": 9035, "s": 9012, "text": "towardsdatascience.com" }, { "code": null, "e": 9058, "s": 9035, "text": "towardsdatascience.com" }, { "code": null, "e": 9081, "s": 9058, "text": "towardsdatascience.com" }, { "code": null, "e": 9104, "s": 9081, "text": "towardsdatascience.com" }, { "code": null, "e": 9127, "s": 9104, "text": "towardsdatascience.com" }, { "code": null, "e": 9182, "s": 9127, "text": "If you liked and found this article useful, follow me!" }, { "code": null, "e": 9254, "s": 9182, "text": "Questions? Post them as a comment and I will reply as soon as possible." }, { "code": null, "e": 9303, "s": 9254, "text": "[1] https://www.nature.com/articles/nbt1206-1565" }, { "code": null, "e": 9360, "s": 9303, "text": "[1] https://en.wikipedia.org/wiki/Support_vector_machine" }, { "code": null, "e": 9435, "s": 9360, "text": "[2] https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html" }, { "code": null, "e": 9490, "s": 9435, "text": "LinkedIn: https://www.linkedin.com/in/serafeim-loukas/" }, { "code": null, "e": 9557, "s": 9490, "text": "ResearchGate: https://www.researchgate.net/profile/Serafeim_Loukas" }, { "code": null, "e": 9610, "s": 9557, "text": "EPFL profile: https://people.epfl.ch/serafeim.loukas" } ]
Find and Draw Contours using OpenCV in Python
For the purpose of image analysis we use the Opencv (Open Source Computer Vision Library) python library. The library name that has to be imported after installing opencv is cv2. In the below example we find the contours present in an image files. Contours help us identify the shapes present in an image. Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity. The findContours function in OPenCV helps us identify the contours. Similarly the drawContours function help us draw the contours. Below is the syntax of both of them. cv.FindContours(image, mode=CV_RETR_LIST, method=CV_CHAIN_APPROX_SIMPLE) Where image is the name of the image Mode is Contour retrieval mode Method is Contour approximation method cv.DrawContours(img, contours, contourIdx, colour, thickness) Where image is the name of the image contours – All the input contours. contourIdx – Parameter indicating a contour to draw. If it is negative, all the contours are drawn. color – Color of the contours thickness is how thick are the lines drawing the contour In the below example we use the image below as our input image. Then run the below program to get the contours around it. We can find three shapes in the above diagram. We can draw contours around all or some of them using the below program. import cv2 # Load an image image = cv2.imread(“path to image file”) # Changing the colour-space LUV = cv2.cvtColor(image, cv2.COLOR_BGR2LUV) # Find edges edges = cv2.Canny(LUV, 10, 100) # Find Contours contours, hierarchy = cv2.findContours(edges,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Find Number of contours print("Number of Contours is: " + str(len(contours))) # Draw yellow border around two contours cv2.drawContours(image, contours, 0, (0, 230, 255), 6) cv2.drawContours(image, contours, 2, (0, 230, 255), 6) # Show the image with contours cv2.imshow('Contours', image) cv2.waitKey(0) Running the above code gives us the following result − Number of Contours found = 3 And we get the below diagram showing the output.
[ { "code": null, "e": 1241, "s": 1062, "text": "For the purpose of image analysis we use the Opencv (Open Source Computer Vision Library) python library. The library name that has to be imported after installing opencv is cv2." }, { "code": null, "e": 1659, "s": 1241, "text": "In the below example we find the contours present in an image files. Contours help us identify the shapes present in an image. Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity. The findContours function in OPenCV helps us identify the contours. Similarly the drawContours function help us draw the contours. Below is the syntax of both of them." }, { "code": null, "e": 2161, "s": 1659, "text": "cv.FindContours(image, mode=CV_RETR_LIST, method=CV_CHAIN_APPROX_SIMPLE)\nWhere\nimage is the name of the image\nMode is Contour retrieval mode\nMethod is Contour approximation method\n\ncv.DrawContours(img, contours, contourIdx, colour, thickness)\nWhere\nimage is the name of the image\ncontours – All the input contours.\ncontourIdx – Parameter indicating a contour to draw. If it is negative, all the contours are drawn.\ncolor – Color of the contours\nthickness is how thick are the lines drawing the contour" }, { "code": null, "e": 2283, "s": 2161, "text": "In the below example we use the image below as our input image. Then run the below program to get the contours around it." }, { "code": null, "e": 2403, "s": 2283, "text": "We can find three shapes in the above diagram. We can draw contours around all or some of them using the below program." }, { "code": null, "e": 2999, "s": 2403, "text": "import cv2\n# Load an image\nimage = cv2.imread(“path to image file”)\n# Changing the colour-space\nLUV = cv2.cvtColor(image, cv2.COLOR_BGR2LUV)\n# Find edges\nedges = cv2.Canny(LUV, 10, 100)\n# Find Contours\ncontours, hierarchy = cv2.findContours(edges,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n# Find Number of contours\nprint(\"Number of Contours is: \" + str(len(contours)))\n# Draw yellow border around two contours\ncv2.drawContours(image, contours, 0, (0, 230, 255), 6)\ncv2.drawContours(image, contours, 2, (0, 230, 255), 6)\n# Show the image with contours\ncv2.imshow('Contours', image)\ncv2.waitKey(0)" }, { "code": null, "e": 3054, "s": 2999, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3083, "s": 3054, "text": "Number of Contours found = 3" }, { "code": null, "e": 3132, "s": 3083, "text": "And we get the below diagram showing the output." } ]
Java if-else-if ladder statement
An if statement can be followed by an optional else if...elsestatement, which is very useful to test various conditions using single if...else if statement. When using if, else if, else statements there are a few points to keep in mind. An if can have zero or one else's and it must come after any else if's. An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested. Once an else if succeeds, none of the remaining else if's or else's will be tested. Following is the syntax of an if...else statement − if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true }else if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true }else if(Boolean_expression 3) { // Executes when the Boolean expression 3 is true }else { // Executes when the none of the above condition is true. } Live Demo public class Test { public static void main(String args[]) { int x = 30; if( x == 10 ) { System.out.print("Value of X is 10"); }else if( x == 20 ) { System.out.print("Value of X is 20"); }else if( x == 30 ) { System.out.print("Value of X is 30"); }else { System.out.print("This is else statement"); } } } This will produce the following result − Value of X is 30
[ { "code": null, "e": 1219, "s": 1062, "text": "An if statement can be followed by an optional else if...elsestatement, which is very useful to test various conditions using single if...else if statement." }, { "code": null, "e": 1299, "s": 1219, "text": "When using if, else if, else statements there are a few points to keep in mind." }, { "code": null, "e": 1371, "s": 1299, "text": "An if can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 1443, "s": 1371, "text": "An if can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 1517, "s": 1443, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 1591, "s": 1517, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 1675, "s": 1591, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 1759, "s": 1675, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 1811, "s": 1759, "text": "Following is the syntax of an if...else statement −" }, { "code": null, "e": 2134, "s": 1811, "text": "if(Boolean_expression 1) {\n // Executes when the Boolean expression 1 is true\n}else if(Boolean_expression 2) {\n // Executes when the Boolean expression 2 is true\n}else if(Boolean_expression 3) {\n // Executes when the Boolean expression 3 is true\n}else {\n // Executes when the none of the above condition is true.\n}" }, { "code": null, "e": 2144, "s": 2134, "text": "Live Demo" }, { "code": null, "e": 2528, "s": 2144, "text": "public class Test {\n public static void main(String args[]) {\n int x = 30;\n\n if( x == 10 ) {\n System.out.print(\"Value of X is 10\");\n }else if( x == 20 ) {\n System.out.print(\"Value of X is 20\");\n }else if( x == 30 ) {\n System.out.print(\"Value of X is 30\");\n }else {\n System.out.print(\"This is else statement\");\n }\n }\n}" }, { "code": null, "e": 2569, "s": 2528, "text": "This will produce the following result −" }, { "code": null, "e": 2586, "s": 2569, "text": "Value of X is 30" } ]
Error-First Callback in Node.js - GeeksforGeeks
16 Feb, 2022 Error-First Callback in Node.js is a function which either returns an error object or any successful data returned by the function. The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first argument.The second argument of the callback function is reserved for any successful data returned by the function. If no error occurred then the error object will be set to null. The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first argument. The second argument of the callback function is reserved for any successful data returned by the function. If no error occurred then the error object will be set to null. Below is the implementation of Error-First Callback: Create a file with the name index.js. The file requires an fs module. We will be implementing an error-first callback function on methods of the fs module. fs module can be used in the program by using the below command: const fs = require("fs"); The file can be executed by using the below command: node index.js We will be using fs.readFile() to show error-first callback function. Example 1: Javascript const fs = require("fs"); // This file does not existsconst file = "file.txt"; // Error first callback// function with two// arguments error and dataconst ErrorFirstCallback = (err, data) => { if (err) { return console.log(err); } console.log("Function successfully executed");}; // function execution// This will return// error because file do// not existfs.readFile(file, ErrorFirstCallback); Output: Example 2: Javascript const fs = require("fs"); // This file existsconst file = "file.txt"; // Error first callback// function with two// arguments error and dataconst ErrorFirstCallback = (err, data) => { if (err) { return console.log(err); } console.log("Function successfully executed"); console.log(data.toString());}; // function execution// This will return// data objectfs.readFile(file, ErrorFirstCallback); Output: adnanirshad158 sagar0719kumar Node.js-Basics Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Express.js express.Router() Function JWT Authentication with Node.js Mongoose Populate() Method Express.js req.params Property Difference between npm i and npm ci in Node.js Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 25026, "s": 24998, "text": "\n16 Feb, 2022" }, { "code": null, "e": 25158, "s": 25026, "text": "Error-First Callback in Node.js is a function which either returns an error object or any successful data returned by the function." }, { "code": null, "e": 25504, "s": 25158, "text": "The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first argument.The second argument of the callback function is reserved for any successful data returned by the function. If no error occurred then the error object will be set to null." }, { "code": null, "e": 25680, "s": 25504, "text": "The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first argument." }, { "code": null, "e": 25851, "s": 25680, "text": "The second argument of the callback function is reserved for any successful data returned by the function. If no error occurred then the error object will be set to null." }, { "code": null, "e": 25904, "s": 25851, "text": "Below is the implementation of Error-First Callback:" }, { "code": null, "e": 26125, "s": 25904, "text": "Create a file with the name index.js. The file requires an fs module. We will be implementing an error-first callback function on methods of the fs module. fs module can be used in the program by using the below command:" }, { "code": null, "e": 26151, "s": 26125, "text": "const fs = require(\"fs\");" }, { "code": null, "e": 26204, "s": 26151, "text": "The file can be executed by using the below command:" }, { "code": null, "e": 26218, "s": 26204, "text": "node index.js" }, { "code": null, "e": 26290, "s": 26218, "text": "We will be using fs.readFile() to show error-first callback function. " }, { "code": null, "e": 26301, "s": 26290, "text": "Example 1:" }, { "code": null, "e": 26312, "s": 26301, "text": "Javascript" }, { "code": "const fs = require(\"fs\"); // This file does not existsconst file = \"file.txt\"; // Error first callback// function with two// arguments error and dataconst ErrorFirstCallback = (err, data) => { if (err) { return console.log(err); } console.log(\"Function successfully executed\");}; // function execution// This will return// error because file do// not existfs.readFile(file, ErrorFirstCallback);", "e": 26713, "s": 26312, "text": null }, { "code": null, "e": 26721, "s": 26713, "text": "Output:" }, { "code": null, "e": 26732, "s": 26721, "text": "Example 2:" }, { "code": null, "e": 26743, "s": 26732, "text": "Javascript" }, { "code": "const fs = require(\"fs\"); // This file existsconst file = \"file.txt\"; // Error first callback// function with two// arguments error and dataconst ErrorFirstCallback = (err, data) => { if (err) { return console.log(err); } console.log(\"Function successfully executed\"); console.log(data.toString());}; // function execution// This will return// data objectfs.readFile(file, ErrorFirstCallback);", "e": 27144, "s": 26743, "text": null }, { "code": null, "e": 27152, "s": 27144, "text": "Output:" }, { "code": null, "e": 27167, "s": 27152, "text": "adnanirshad158" }, { "code": null, "e": 27182, "s": 27167, "text": "sagar0719kumar" }, { "code": null, "e": 27197, "s": 27182, "text": "Node.js-Basics" }, { "code": null, "e": 27204, "s": 27197, "text": "Picked" }, { "code": null, "e": 27212, "s": 27204, "text": "Node.js" }, { "code": null, "e": 27229, "s": 27212, "text": "Web Technologies" }, { "code": null, "e": 27327, "s": 27229, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27364, "s": 27327, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27396, "s": 27364, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 27423, "s": 27396, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27454, "s": 27423, "text": "Express.js req.params Property" }, { "code": null, "e": 27501, "s": 27454, "text": "Difference between npm i and npm ci in Node.js" }, { "code": null, "e": 27543, "s": 27501, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27586, "s": 27543, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27636, "s": 27586, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27698, "s": 27636, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
SQLAlchemy ORM - Textual SQL
Earlier, textual SQL using text() function has been explained from the perspective of core expression language of SQLAlchemy. Now we shall discuss it from ORM point of view. Literal strings can be used flexibly with Query object by specifying their use with the text() construct. Most applicable methods accept it. For example, filter() and order_by(). In the example given below, the filter() method translates the string “id<3” to the WHERE id<3 from sqlalchemy import text for cust in session.query(Customers).filter(text("id<3")): print(cust.name) The raw SQL expression generated shows conversion of filter to WHERE clause with the code illustrated below − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE id<3 From our sample data in Customers table, two rows will be selected and name column will be printed as follows − Ravi Kumar Komal Pande To specify bind parameters with string-based SQL, use a colon,and to specify the values, use the params() method. cust = session.query(Customers).filter(text("id = :value")).params(value = 1).one() The effective SQL displayed on Python console will be as given below − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE id = ? To use an entirely string-based statement, a text() construct representing a complete statement can be passed to from_statement(). session.query(Customers).from_statement(text("SELECT * FROM customers")).all() The result of above code will be a basic SELECT statement as given below − SELECT * FROM customers Obviously, all records in customers table will be selected. The text() construct allows us to link its textual SQL to Core or ORM-mapped column expressions positionally. We can achieve this by passing column expressions as positional arguments to the TextClause.columns() method. stmt = text("SELECT name, id, name, address, email FROM customers") stmt = stmt.columns(Customers.id, Customers.name) session.query(Customers.id, Customers.name).from_statement(stmt).all() The id and name columns of all rows will be selected even though the SQLite engine executes following expression generated by above code shows all columns in text() method − SELECT name, id, name, address, email FROM customers 21 Lectures 1.5 hours Jack Chan Print Add Notes Bookmark this page
[ { "code": null, "e": 2514, "s": 2340, "text": "Earlier, textual SQL using text() function has been explained from the perspective of core expression language of SQLAlchemy. Now we shall discuss it from ORM point of view." }, { "code": null, "e": 2693, "s": 2514, "text": "Literal strings can be used flexibly with Query object by specifying their use with the text() construct. Most applicable methods accept it. For example, filter() and order_by()." }, { "code": null, "e": 2788, "s": 2693, "text": "In the example given below, the filter() method translates the string “id<3” to the WHERE id<3" }, { "code": null, "e": 2895, "s": 2788, "text": "from sqlalchemy import text\nfor cust in session.query(Customers).filter(text(\"id<3\")):\n print(cust.name)" }, { "code": null, "e": 3005, "s": 2895, "text": "The raw SQL expression generated shows conversion of filter to WHERE clause with the code illustrated below −" }, { "code": null, "e": 3181, "s": 3005, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE id<3" }, { "code": null, "e": 3293, "s": 3181, "text": "From our sample data in Customers table, two rows will be selected and name column will be printed as follows −" }, { "code": null, "e": 3317, "s": 3293, "text": "Ravi Kumar\nKomal Pande\n" }, { "code": null, "e": 3431, "s": 3317, "text": "To specify bind parameters with string-based SQL, use a colon,and to specify the values, use the params() method." }, { "code": null, "e": 3515, "s": 3431, "text": "cust = session.query(Customers).filter(text(\"id = :value\")).params(value = 1).one()" }, { "code": null, "e": 3586, "s": 3515, "text": "The effective SQL displayed on Python console will be as given below −" }, { "code": null, "e": 3764, "s": 3586, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE id = ?" }, { "code": null, "e": 3895, "s": 3764, "text": "To use an entirely string-based statement, a text() construct representing a complete statement can be passed to from_statement()." }, { "code": null, "e": 3974, "s": 3895, "text": "session.query(Customers).from_statement(text(\"SELECT * FROM customers\")).all()" }, { "code": null, "e": 4049, "s": 3974, "text": "The result of above code will be a basic SELECT statement as given below −" }, { "code": null, "e": 4073, "s": 4049, "text": "SELECT * FROM customers" }, { "code": null, "e": 4133, "s": 4073, "text": "Obviously, all records in customers table will be selected." }, { "code": null, "e": 4353, "s": 4133, "text": "The text() construct allows us to link its textual SQL to Core or ORM-mapped column expressions positionally. We can achieve this by passing column expressions as positional arguments to the TextClause.columns() method." }, { "code": null, "e": 4542, "s": 4353, "text": "stmt = text(\"SELECT name, id, name, address, email FROM customers\")\nstmt = stmt.columns(Customers.id, Customers.name)\nsession.query(Customers.id, Customers.name).from_statement(stmt).all()" }, { "code": null, "e": 4716, "s": 4542, "text": "The id and name columns of all rows will be selected even though the SQLite engine executes following expression generated by above code shows all columns in text() method −" }, { "code": null, "e": 4769, "s": 4716, "text": "SELECT name, id, name, address, email FROM customers" }, { "code": null, "e": 4804, "s": 4769, "text": "\n 21 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4815, "s": 4804, "text": " Jack Chan" }, { "code": null, "e": 4822, "s": 4815, "text": " Print" }, { "code": null, "e": 4833, "s": 4822, "text": " Add Notes" } ]
Mahotas - RGB to XYZ Conversion - GeeksforGeeks
10 Dec, 2021 In this article we will see how we can covert rgb image to xyz image in mahotas. An RGB image, sometimes referred to as a truecolor image, is stored in MATLAB as an m-by-n-by-3 data array that defines red, green, and blue color components for each individual pixel. Xyz is an additive color space based on how the eye interprets stimulus from light. Unlike other additive rgb like Rgb, Xyz is a purely mathematical space and the primary components are “imaginary”, meaning we can’t create the represented color in the physical by shining any sort of lights representing x, y, and z. In this tutorial we will use “lena” image, below is the command to load it. mahotas.demos.load('lena') Below is the lena image In order to do this we will use mahotas.colors.rgb2xyzmethod Syntax : mahotas.colors.rgb2xyz(img)Argument :It takes image object as argumentReturn : It returns image object Below is the implementation Python3 # importing required librariesimport mahotasimport mahotas.demosfrom pylab import gray, imshow, showimport numpy as np # loading imageimg = mahotas.demos.load('lena') # showing imageprint("Image")imshow(img)show() # rgb to labnew_img = mahotas.colors.rgb2xyz(img) # showing new imageprint("New Image")imshow(new_img)show() Strong : Image New Image Another example Python3 # importing required librariesimport mahotasimport numpy as npimport matplotlib.pyplot as pltimport os # loading imageimg = mahotas.imread('dog_image.png') # filtering imageimg = img[:, :, :3] # showing imageprint("Image")imshow(img)show() # rgb to labnew_img = mahotas.colors.rgb2xyz(img) # showing new imageprint("New Image")imshow(new_img)show() Strong : Image New Image simmytarika5 simranarora5sos surinderdawra388 Python-Mahotas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23975, "s": 23947, "text": "\n10 Dec, 2021" }, { "code": null, "e": 24635, "s": 23975, "text": "In this article we will see how we can covert rgb image to xyz image in mahotas. An RGB image, sometimes referred to as a truecolor image, is stored in MATLAB as an m-by-n-by-3 data array that defines red, green, and blue color components for each individual pixel. Xyz is an additive color space based on how the eye interprets stimulus from light. Unlike other additive rgb like Rgb, Xyz is a purely mathematical space and the primary components are “imaginary”, meaning we can’t create the represented color in the physical by shining any sort of lights representing x, y, and z. In this tutorial we will use “lena” image, below is the command to load it. " }, { "code": null, "e": 24662, "s": 24635, "text": "mahotas.demos.load('lena')" }, { "code": null, "e": 24687, "s": 24662, "text": "Below is the lena image " }, { "code": null, "e": 24749, "s": 24687, "text": "In order to do this we will use mahotas.colors.rgb2xyzmethod " }, { "code": null, "e": 24863, "s": 24749, "text": "Syntax : mahotas.colors.rgb2xyz(img)Argument :It takes image object as argumentReturn : It returns image object " }, { "code": null, "e": 24892, "s": 24863, "text": "Below is the implementation " }, { "code": null, "e": 24900, "s": 24892, "text": "Python3" }, { "code": "# importing required librariesimport mahotasimport mahotas.demosfrom pylab import gray, imshow, showimport numpy as np # loading imageimg = mahotas.demos.load('lena') # showing imageprint(\"Image\")imshow(img)show() # rgb to labnew_img = mahotas.colors.rgb2xyz(img) # showing new imageprint(\"New Image\")imshow(new_img)show()", "e": 25226, "s": 24900, "text": null }, { "code": null, "e": 25236, "s": 25226, "text": "Strong : " }, { "code": null, "e": 25242, "s": 25236, "text": "Image" }, { "code": null, "e": 25252, "s": 25242, "text": "New Image" }, { "code": null, "e": 25269, "s": 25252, "text": "Another example " }, { "code": null, "e": 25277, "s": 25269, "text": "Python3" }, { "code": "# importing required librariesimport mahotasimport numpy as npimport matplotlib.pyplot as pltimport os # loading imageimg = mahotas.imread('dog_image.png') # filtering imageimg = img[:, :, :3] # showing imageprint(\"Image\")imshow(img)show() # rgb to labnew_img = mahotas.colors.rgb2xyz(img) # showing new imageprint(\"New Image\")imshow(new_img)show()", "e": 25633, "s": 25277, "text": null }, { "code": null, "e": 25643, "s": 25633, "text": "Strong : " }, { "code": null, "e": 25649, "s": 25643, "text": "Image" }, { "code": null, "e": 25659, "s": 25649, "text": "New Image" }, { "code": null, "e": 25672, "s": 25659, "text": "simmytarika5" }, { "code": null, "e": 25688, "s": 25672, "text": "simranarora5sos" }, { "code": null, "e": 25705, "s": 25688, "text": "surinderdawra388" }, { "code": null, "e": 25720, "s": 25705, "text": "Python-Mahotas" }, { "code": null, "e": 25727, "s": 25720, "text": "Python" }, { "code": null, "e": 25825, "s": 25727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25834, "s": 25825, "text": "Comments" }, { "code": null, "e": 25847, "s": 25834, "text": "Old Comments" }, { "code": null, "e": 25865, "s": 25847, "text": "Python Dictionary" }, { "code": null, "e": 25900, "s": 25865, "text": "Read a file line by line in Python" }, { "code": null, "e": 25922, "s": 25900, "text": "Enumerate() in Python" }, { "code": null, "e": 25954, "s": 25922, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25984, "s": 25954, "text": "Iterate over a list in Python" }, { "code": null, "e": 26026, "s": 25984, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26052, "s": 26026, "text": "Python String | replace()" }, { "code": null, "e": 26095, "s": 26052, "text": "Python program to convert a list to string" }, { "code": null, "e": 26139, "s": 26095, "text": "Reading and Writing to text files in Python" } ]
How to deal with CORS error in express Node.js Project ? - GeeksforGeeks
25 Jul, 2021 CORS, also known as Cross-Origin Resource Sharing, should be enabled if you want to make a request between your client and server when they are on different URLs. Let us consider client to be on http://localhost:5500 and the server on http://localhost:5000. Now if you try to make a request from your client to the server you will get the error stating that blocked by the CORS policy. How To Enable CORS? We will use cors, a node.js package to enable CORS in express Node.js Project. Project Setup and Module Installation: Step 1: Create a Node.js application and name it gfg-cors using the following command. mkdir gfg-cors && cd gfg-cors npm init Step 1: Create a Node.js application and name it gfg-cors using the following command. mkdir gfg-cors && cd gfg-cors npm init Step 2: Install the dependency modules using the following command.npm i express cors npm i express cors Step 3: Create client directory and server.js file in the root directory. Then create index.html and script.js in the client directory. Step 3: Create client directory and server.js file in the root directory. Then create index.html and script.js in the client directory. Project Directory: It will look like this. Example:Write down the following code in the index.html, script.js, and server.js files. index.html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>gfg-cors</title> <script src="script.js"></script> </head><body> </body></html> script.js fetch('http://localhost:5000/gfg-articles').then((res) => res.json()).then((gfg_articles) => console.log(gfg_articles)); server.js // Requiring moduleconst express = require('express');const cors = require('cors'); // Creating express app objectconst app = express(); // CORS is enabled for all originsapp.use(cors()); // Example api app.get('/gfg-articles', (req, res) => res.json('gfg-articles')); // Port Numberconst port = 5000; // Server setupapp.listen(port, () => `Server running on port ${port}`); Note: If you want to allow the selected origins to access your site then you need to configure cors as shown below. server.js // Requiring moduleconst express = require('express');const cors = require('cors'); // Creating express app objectconst app = express(); // CORS is enabled for the selected originslet corsOptions = { origin: [ 'http://localhost:5500', 'http://localhost:3000' ]}; // Using cors as a middlewareapp.get('/gfg-articles',cors(corsOptions), (req,res) => res.json('gfg-articles')) // Port numberconst port = 5000; // Server setupapp.listen(port, () => `Server running on port ${port}`); If you just want to allow a particular origin to access your site, then corsOptions will be as follows: let corsOptions = { origin: 'http://localhost:5500' }; Step to run the application: Run the server.js using the following command. node server.js Output: Open index.html and then check the following output in the console. Express.js NodeJS-Questions Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? Mongoose Populate() Method How to connect Node.js with React.js ? How to Convert CSV to JSON file having Comma Separated values in Node.js ? Express.js req.params Property Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24557, "s": 24529, "text": "\n25 Jul, 2021" }, { "code": null, "e": 24720, "s": 24557, "text": "CORS, also known as Cross-Origin Resource Sharing, should be enabled if you want to make a request between your client and server when they are on different URLs." }, { "code": null, "e": 24943, "s": 24720, "text": "Let us consider client to be on http://localhost:5500 and the server on http://localhost:5000. Now if you try to make a request from your client to the server you will get the error stating that blocked by the CORS policy." }, { "code": null, "e": 24963, "s": 24943, "text": "How To Enable CORS?" }, { "code": null, "e": 25042, "s": 24963, "text": "We will use cors, a node.js package to enable CORS in express Node.js Project." }, { "code": null, "e": 25081, "s": 25042, "text": "Project Setup and Module Installation:" }, { "code": null, "e": 25209, "s": 25081, "text": "Step 1: Create a Node.js application and name it gfg-cors using the following command. mkdir gfg-cors && cd gfg-cors\nnpm init " }, { "code": null, "e": 25298, "s": 25209, "text": "Step 1: Create a Node.js application and name it gfg-cors using the following command. " }, { "code": null, "e": 25338, "s": 25298, "text": "mkdir gfg-cors && cd gfg-cors\nnpm init " }, { "code": null, "e": 25424, "s": 25338, "text": "Step 2: Install the dependency modules using the following command.npm i express cors" }, { "code": null, "e": 25443, "s": 25424, "text": "npm i express cors" }, { "code": null, "e": 25579, "s": 25443, "text": "Step 3: Create client directory and server.js file in the root directory. Then create index.html and script.js in the client directory." }, { "code": null, "e": 25715, "s": 25579, "text": "Step 3: Create client directory and server.js file in the root directory. Then create index.html and script.js in the client directory." }, { "code": null, "e": 25758, "s": 25715, "text": "Project Directory: It will look like this." }, { "code": null, "e": 25849, "s": 25760, "text": "Example:Write down the following code in the index.html, script.js, and server.js files." }, { "code": null, "e": 25860, "s": 25849, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>gfg-cors</title> <script src=\"script.js\"></script> </head><body> </body></html>", "e": 26157, "s": 25860, "text": null }, { "code": null, "e": 26167, "s": 26157, "text": "script.js" }, { "code": "fetch('http://localhost:5000/gfg-articles').then((res) => res.json()).then((gfg_articles) => console.log(gfg_articles));", "e": 26288, "s": 26167, "text": null }, { "code": null, "e": 26298, "s": 26288, "text": "server.js" }, { "code": "// Requiring moduleconst express = require('express');const cors = require('cors'); // Creating express app objectconst app = express(); // CORS is enabled for all originsapp.use(cors()); // Example api app.get('/gfg-articles', (req, res) => res.json('gfg-articles')); // Port Numberconst port = 5000; // Server setupapp.listen(port, () => `Server running on port ${port}`);", "e": 26682, "s": 26298, "text": null }, { "code": null, "e": 26798, "s": 26682, "text": "Note: If you want to allow the selected origins to access your site then you need to configure cors as shown below." }, { "code": null, "e": 26808, "s": 26798, "text": "server.js" }, { "code": "// Requiring moduleconst express = require('express');const cors = require('cors'); // Creating express app objectconst app = express(); // CORS is enabled for the selected originslet corsOptions = { origin: [ 'http://localhost:5500', 'http://localhost:3000' ]}; // Using cors as a middlewareapp.get('/gfg-articles',cors(corsOptions), (req,res) => res.json('gfg-articles')) // Port numberconst port = 5000; // Server setupapp.listen(port, () => `Server running on port ${port}`);", "e": 27299, "s": 26808, "text": null }, { "code": null, "e": 27403, "s": 27299, "text": "If you just want to allow a particular origin to access your site, then corsOptions will be as follows:" }, { "code": null, "e": 27462, "s": 27403, "text": "let corsOptions = {\n origin: 'http://localhost:5500'\n};" }, { "code": null, "e": 27538, "s": 27462, "text": "Step to run the application: Run the server.js using the following command." }, { "code": null, "e": 27553, "s": 27538, "text": "node server.js" }, { "code": null, "e": 27629, "s": 27553, "text": "Output: Open index.html and then check the following output in the console." }, { "code": null, "e": 27640, "s": 27629, "text": "Express.js" }, { "code": null, "e": 27657, "s": 27640, "text": "NodeJS-Questions" }, { "code": null, "e": 27665, "s": 27657, "text": "Node.js" }, { "code": null, "e": 27682, "s": 27665, "text": "Web Technologies" }, { "code": null, "e": 27780, "s": 27682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27789, "s": 27780, "text": "Comments" }, { "code": null, "e": 27802, "s": 27789, "text": "Old Comments" }, { "code": null, "e": 27859, "s": 27802, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 27886, "s": 27859, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27925, "s": 27886, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 28000, "s": 27925, "text": "How to Convert CSV to JSON file having Comma Separated values in Node.js ?" }, { "code": null, "e": 28031, "s": 28000, "text": "Express.js req.params Property" }, { "code": null, "e": 28087, "s": 28031, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28149, "s": 28087, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28192, "s": 28149, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28242, "s": 28192, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to multiply a polynomial to another using NumPy in Python? - GeeksforGeeks
29 Aug, 2020 In this article, we will make a NumPy program to multiply one polynomial to another. Two polynomials are given as input and the result is the multiplication of two polynomials. The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}. Let take two polynomials p(x) and q(x) then multiply these to get r(x) = p(x) * q(x) as a result of multiplication of two input polynomials. If p(x) = A3 x2 + A2 x + A1 and q(x) = B3 x2 + B2 x + B1 then result is r(x) = p(x) * q(x) and output is ( (A1 * B1), (A2 * B1) + (A2 * B1), (A3 * B1) + (A2 * B2) + (A1 * B3), (A2 * B2) + (A3 * B2), (A3 * B3) ). This can be calculated using the polymul() method of NumPy. This method evaluates the product of two polynomials and returns the polynomial resulting from the multiplication of two input polynomials ‘p1’ and ‘p2’. Syntax: numpy.polymul(p1, p2) Below is the implementation with some examples : Example 1: Python3 # importing packageimport numpy # define the polynomials# p(x) = 5(x**2) + (-2)x +5 px = (5, -2, 5)# q(x) = 2(x**2) + (-5)x +2qx = (2, -5, 2) # mul the polynomialsrx = numpy.polynomial.polynomial.polymul(px, qx) # print the resultant polynomialprint(rx) Output : [ 10. -29. 30. -29. 10.] Example 2 : Python3 # importing packageimport numpy # define the polynomials# p(x) = 2.2px = (0, 0, 2.2) # q(x) = 9.8(x**2) + 4qx = (9.8, 0, 4) # mul the polynomialsrx = numpy.polynomial.polynomial.polymul(px, qx) # print the resultant polynomialprint(rx) Output : [ 0. 0. 21.56 0. 8.8 ] Example 3 : Python3 # importing packageimport numpy # define the polynomials# p(x) = (5/3)xpx = (0, 5/3, 0) # q(x) = (-7/4)(x**2) + (9/5)qx = (-7/4, 0, 9/5) # mul the polynomialsrx = numpy.polynomial.polynomial.polymul(px, qx) # print the resultant polynomialprint(rx) Output : [ 0. -2.91666667 0. 3. ] Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24078, "s": 23901, "text": "In this article, we will make a NumPy program to multiply one polynomial to another. Two polynomials are given as input and the result is the multiplication of two polynomials." }, { "code": null, "e": 24196, "s": 24078, "text": "The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}." }, { "code": null, "e": 24337, "s": 24196, "text": "Let take two polynomials p(x) and q(x) then multiply these to get r(x) = p(x) * q(x) as a result of multiplication of two input polynomials." }, { "code": null, "e": 24559, "s": 24337, "text": "If p(x) = A3 x2 + A2 x + A1 \nand \nq(x) = B3 x2 + B2 x + B1 \n\nthen result is r(x) = p(x) * q(x) \n\nand output is \n\n( (A1 * B1), (A2 * B1) + (A2 * B1),\n(A3 * B1) + (A2 * B2) + (A1 * B3), \n(A2 * B2) + (A3 * B2), (A3 * B3) ).\n" }, { "code": null, "e": 24773, "s": 24559, "text": "This can be calculated using the polymul() method of NumPy. This method evaluates the product of two polynomials and returns the polynomial resulting from the multiplication of two input polynomials ‘p1’ and ‘p2’." }, { "code": null, "e": 24781, "s": 24773, "text": "Syntax:" }, { "code": null, "e": 24803, "s": 24781, "text": "numpy.polymul(p1, p2)" }, { "code": null, "e": 24852, "s": 24803, "text": "Below is the implementation with some examples :" }, { "code": null, "e": 24863, "s": 24852, "text": "Example 1:" }, { "code": null, "e": 24871, "s": 24863, "text": "Python3" }, { "code": "# importing packageimport numpy # define the polynomials# p(x) = 5(x**2) + (-2)x +5 px = (5, -2, 5)# q(x) = 2(x**2) + (-5)x +2qx = (2, -5, 2) # mul the polynomialsrx = numpy.polynomial.polynomial.polymul(px, qx) # print the resultant polynomialprint(rx)", "e": 25129, "s": 24871, "text": null }, { "code": null, "e": 25138, "s": 25129, "text": "Output :" }, { "code": null, "e": 25167, "s": 25138, "text": "[ 10. -29. 30. -29. 10.] \n" }, { "code": null, "e": 25179, "s": 25167, "text": "Example 2 :" }, { "code": null, "e": 25187, "s": 25179, "text": "Python3" }, { "code": "# importing packageimport numpy # define the polynomials# p(x) = 2.2px = (0, 0, 2.2) # q(x) = 9.8(x**2) + 4qx = (9.8, 0, 4) # mul the polynomialsrx = numpy.polynomial.polynomial.polymul(px, qx) # print the resultant polynomialprint(rx)", "e": 25427, "s": 25187, "text": null }, { "code": null, "e": 25436, "s": 25427, "text": "Output :" }, { "code": null, "e": 25474, "s": 25436, "text": "[ 0. 0. 21.56 0. 8.8 ]\n" }, { "code": null, "e": 25486, "s": 25474, "text": "Example 3 :" }, { "code": null, "e": 25494, "s": 25486, "text": "Python3" }, { "code": "# importing packageimport numpy # define the polynomials# p(x) = (5/3)xpx = (0, 5/3, 0) # q(x) = (-7/4)(x**2) + (9/5)qx = (-7/4, 0, 9/5) # mul the polynomialsrx = numpy.polynomial.polynomial.polymul(px, qx) # print the resultant polynomialprint(rx)", "e": 25747, "s": 25494, "text": null }, { "code": null, "e": 25756, "s": 25747, "text": "Output :" }, { "code": null, "e": 25807, "s": 25756, "text": "[ 0. -2.91666667 0. 3. ]\n" }, { "code": null, "e": 25842, "s": 25807, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 25855, "s": 25842, "text": "Python-numpy" }, { "code": null, "e": 25862, "s": 25855, "text": "Python" }, { "code": null, "e": 25960, "s": 25862, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25969, "s": 25960, "text": "Comments" }, { "code": null, "e": 25982, "s": 25969, "text": "Old Comments" }, { "code": null, "e": 26014, "s": 25982, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26070, "s": 26014, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26112, "s": 26070, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26154, "s": 26112, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26190, "s": 26154, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26212, "s": 26190, "text": "Defaultdict in Python" }, { "code": null, "e": 26251, "s": 26212, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26278, "s": 26251, "text": "Python Classes and Objects" }, { "code": null, "e": 26309, "s": 26278, "text": "Python | os.path.join() method" } ]
Merge operations using STL in C++ | merge(), includes(), set_union(), set_intersection(), set_difference(), ., inplace_merge, - GeeksforGeeks
03 Mar, 2022 Some of the merge operation classes are provided in C++ STL under the header file “algorithm”, which facilitates several merge operations in a easy manner. Some of them are mentioned below. merge(beg1, end1, beg2, end2, beg3) :- This function merges two sorted containers and stores in new container in sorted order (merge sort). It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container. includes(beg1, end1, beg2, end2) :- This function is used to check whether one sorted container elements are including other sorted container elements or not. Returns true if 1st container includes 2nd container else returns false. merge(beg1, end1, beg2, end2, beg3) :- This function merges two sorted containers and stores in new container in sorted order (merge sort). It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container. includes(beg1, end1, beg2, end2) :- This function is used to check whether one sorted container elements are including other sorted container elements or not. Returns true if 1st container includes 2nd container else returns false. CPP // C++ code to demonstrate the working of// merge() and include()#include<iostream>#include<algorithm> // merge operations#include<vector> // for vectorusing namespace std;int main(){ // Initializing 1st vector vector<int> v1 = {1, 3, 4, 5, 20, 30}; // Initializing 2nd vector vector<int> v2 = {1, 5, 6, 7, 25, 30}; // Declaring resultant vector // for merging vector<int> v3(12); // Using merge() to merge vectors v1 and v2 // and storing result in v3 merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin()); // Displaying resultant container cout << "The new container after merging is :\n"; for (int &x : v3) cout << x << " "; cout << endl; // Initializing new vector vector<int> v4 = {1, 3, 4, 5, 6, 20, 25, 30}; // Using include() to check if v4 contains v1 includes(v4.begin(), v4.end(), v1.begin(), v1.end())? cout << "v4 includes v1": cout << "v4 does'nt include v1"; return 0; } Output Output The new container after merging is : 1 1 3 4 5 5 6 7 20 25 30 30 v4 includes v1 inplace_merge(beg1, beg2, end) :- This function is used to sort two consecutively placed sorted ranges in a single container. It takes 3 arguments, iterator to beginning of 1st sorted range, iterator to beginning of 2nd sorted range, and iterator to last position. inplace_merge(beg1, beg2, end) :- This function is used to sort two consecutively placed sorted ranges in a single container. It takes 3 arguments, iterator to beginning of 1st sorted range, iterator to beginning of 2nd sorted range, and iterator to last position. CPP // C++ code to demonstrate the working of// inplace_merge()#include<iostream>#include<algorithm> // merge operations#include<vector> // for vectorusing namespace std;int main(){ // Initializing 1st vector vector<int> v1 = {1, 3, 4, 5, 20, 30}; // Initializing 2nd vector vector<int> v2 = {1, 5, 6, 7, 25, 30}; // Declaring resultant vector // for inplace_merge() vector<int> v3(12); // using copy to copy both vectors into // one container auto it = copy(v1.begin(), v1.end(), v3.begin()); copy(v2.begin(), v2.end(), it); // Using inplace_merge() to sort the container inplace_merge(v3.begin(),it,v3.end()); // Displaying resultant container cout << "The new container after inplace_merging is :\n"; for (int &x : v3) cout << x << " "; cout << endl; return 0; } Output: Output: The new container after inplace_merging is : 1 1 3 4 5 5 6 7 20 25 30 30 set_union(beg1, end1, beg2, end2, beg3) :- This function computes the set union of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size.set_intersection(beg1, end1, beg2, end2, beg3) :- This function computes the set intersection of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size. One way to implement set-union and set-intersection in sorted ranges can be found here set_union(beg1, end1, beg2, end2, beg3) :- This function computes the set union of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size. set_intersection(beg1, end1, beg2, end2, beg3) :- This function computes the set intersection of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size. One way to implement set-union and set-intersection in sorted ranges can be found here CPP // C++ code to demonstrate the working of// set_union() and set_intersection()#include<iostream>#include<algorithm> // for merge operations#include<vector> // for vectorusing namespace std;int main(){ // Initializing 1st vector vector<int> v1 = {1, 3, 4, 5, 20, 30}; // Initializing 2nd vector vector<int> v2 = {1, 5, 6, 7, 25, 30}; // Declaring resultant vector // for union vector<int> v3(10); // Declaring resultant vector // for intersection vector<int> v4(10); // using set_union() to compute union of 2 // containers v1 and v2 and store result in v3 auto it = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin()); // using set_intersection() to compute intersection // of 2 containers v1 and v2 and store result in v4 auto it1 = set_intersection(v1.begin(),v1.end(), v2.begin(), v2.end(), v4.begin()); // resizing new container v3.resize(it - v3.begin()); // resizing new container v4.resize(it1 - v4.begin()); // Displaying set union cout << "Union of two containers is : "; for (int &x : v3) cout << x << " "; cout << endl; // Displaying set intersection cout << "Intersection of two containers is : "; for (int &x : v4) cout << x << " "; cout << endl; return 0; } Output: Output: Union of two containers is : 1 3 4 5 6 7 20 25 30 Intersection of two containers is : 1 5 30 set_difference(beg1, end1, beg2, end2, beg3) :- This function computes the set difference of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size.set_symmetric_difference(beg1, end1, beg2, end2, beg3) :- This function computes the set symmetric difference of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size. set_difference(beg1, end1, beg2, end2, beg3) :- This function computes the set difference of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size. set_symmetric_difference(beg1, end1, beg2, end2, beg3) :- This function computes the set symmetric difference of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size. CPP // C++ code to demonstrate the working of// set_difference() and set_symmetric_difference()#include<iostream>#include<algorithm> // for merge operations#include<vector> // for vectorusing namespace std;int main(){ // Initializing 1st vector vector<int> v1 = {1, 3, 4, 5, 20, 30}; // Initializing 2nd vector vector<int> v2 = {1, 5, 6, 7, 25, 30}; // Declaring resultant vector // for difference vector<int> v3(10); // Declaring resultant vector // for symmetric_difference vector<int> v4(10); // using set_difference() to compute difference // of 2 containers v1 and v2. auto it = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin()); // using set_symmetric_difference() to compute // symmetric_difference/ of 2 containers auto it1 = set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), v4.begin()); // resizing new container v3.resize(it - v3.begin()); // resizing new container v4.resize(it1 - v4.begin()); // Displaying set difference cout << "Difference of two containers is : "; for (int &x : v3) cout << x << " "; cout << endl; // Displaying set symmetric_difference cout << "symmetric_difference of two containers is : "; for (int &x : v4) cout << x << " "; cout << endl; return 0; } Output: Output: Difference of two containers is : 3 4 20 Symmetric difference of two containers is : 3 4 6 7 20 25 This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. surinderdawra388 cpp-algorithm-library CPP-Library Merge Sort STL C Language C++ Mathematical Mathematical STL Merge Sort CPP 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 Arrow operator -> in C/C++ with Examples 'this' pointer in C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ Constructors in C++
[ { "code": null, "e": 23919, "s": 23891, "text": "\n03 Mar, 2022" }, { "code": null, "e": 24111, "s": 23919, "text": "Some of the merge operation classes are provided in C++ STL under the header file “algorithm”, which facilitates several merge operations in a easy manner. Some of them are mentioned below. " }, { "code": null, "e": 24631, "s": 24111, "text": "merge(beg1, end1, beg2, end2, beg3) :- This function merges two sorted containers and stores in new container in sorted order (merge sort). It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container. includes(beg1, end1, beg2, end2) :- This function is used to check whether one sorted container elements are including other sorted container elements or not. Returns true if 1st container includes 2nd container else returns false. " }, { "code": null, "e": 24919, "s": 24631, "text": "merge(beg1, end1, beg2, end2, beg3) :- This function merges two sorted containers and stores in new container in sorted order (merge sort). It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container. " }, { "code": null, "e": 25152, "s": 24919, "text": "includes(beg1, end1, beg2, end2) :- This function is used to check whether one sorted container elements are including other sorted container elements or not. Returns true if 1st container includes 2nd container else returns false. " }, { "code": null, "e": 25156, "s": 25152, "text": "CPP" }, { "code": "// C++ code to demonstrate the working of// merge() and include()#include<iostream>#include<algorithm> // merge operations#include<vector> // for vectorusing namespace std;int main(){ // Initializing 1st vector vector<int> v1 = {1, 3, 4, 5, 20, 30}; // Initializing 2nd vector vector<int> v2 = {1, 5, 6, 7, 25, 30}; // Declaring resultant vector // for merging vector<int> v3(12); // Using merge() to merge vectors v1 and v2 // and storing result in v3 merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin()); // Displaying resultant container cout << \"The new container after merging is :\\n\"; for (int &x : v3) cout << x << \" \"; cout << endl; // Initializing new vector vector<int> v4 = {1, 3, 4, 5, 6, 20, 25, 30}; // Using include() to check if v4 contains v1 includes(v4.begin(), v4.end(), v1.begin(), v1.end())? cout << \"v4 includes v1\": cout << \"v4 does'nt include v1\"; return 0; }", "e": 26114, "s": 25156, "text": null }, { "code": null, "e": 26123, "s": 26114, "text": "Output " }, { "code": null, "e": 26132, "s": 26123, "text": "Output " }, { "code": null, "e": 26213, "s": 26132, "text": "The new container after merging is :\n1 1 3 4 5 5 6 7 20 25 30 30 \nv4 includes v1" }, { "code": null, "e": 26480, "s": 26213, "text": " inplace_merge(beg1, beg2, end) :- This function is used to sort two consecutively placed sorted ranges in a single container. It takes 3 arguments, iterator to beginning of 1st sorted range, iterator to beginning of 2nd sorted range, and iterator to last position. " }, { "code": null, "e": 26748, "s": 26482, "text": "inplace_merge(beg1, beg2, end) :- This function is used to sort two consecutively placed sorted ranges in a single container. It takes 3 arguments, iterator to beginning of 1st sorted range, iterator to beginning of 2nd sorted range, and iterator to last position. " }, { "code": null, "e": 26752, "s": 26748, "text": "CPP" }, { "code": "// C++ code to demonstrate the working of// inplace_merge()#include<iostream>#include<algorithm> // merge operations#include<vector> // for vectorusing namespace std;int main(){ // Initializing 1st vector vector<int> v1 = {1, 3, 4, 5, 20, 30}; // Initializing 2nd vector vector<int> v2 = {1, 5, 6, 7, 25, 30}; // Declaring resultant vector // for inplace_merge() vector<int> v3(12); // using copy to copy both vectors into // one container auto it = copy(v1.begin(), v1.end(), v3.begin()); copy(v2.begin(), v2.end(), it); // Using inplace_merge() to sort the container inplace_merge(v3.begin(),it,v3.end()); // Displaying resultant container cout << \"The new container after inplace_merging is :\\n\"; for (int &x : v3) cout << x << \" \"; cout << endl; return 0; }", "e": 27544, "s": 26752, "text": null }, { "code": null, "e": 27554, "s": 27544, "text": "Output: " }, { "code": null, "e": 27564, "s": 27554, "text": "Output: " }, { "code": null, "e": 27638, "s": 27564, "text": "The new container after inplace_merging is :\n1 1 3 4 5 5 6 7 20 25 30 30 " }, { "code": null, "e": 28625, "s": 27638, "text": " set_union(beg1, end1, beg2, end2, beg3) :- This function computes the set union of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size.set_intersection(beg1, end1, beg2, end2, beg3) :- This function computes the set intersection of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size. One way to implement set-union and set-intersection in sorted ranges can be found here " }, { "code": null, "e": 29069, "s": 28627, "text": "set_union(beg1, end1, beg2, end2, beg3) :- This function computes the set union of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size." }, { "code": null, "e": 29614, "s": 29069, "text": "set_intersection(beg1, end1, beg2, end2, beg3) :- This function computes the set intersection of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size. One way to implement set-union and set-intersection in sorted ranges can be found here " }, { "code": null, "e": 29618, "s": 29614, "text": "CPP" }, { "code": "// C++ code to demonstrate the working of// set_union() and set_intersection()#include<iostream>#include<algorithm> // for merge operations#include<vector> // for vectorusing namespace std;int main(){ // Initializing 1st vector vector<int> v1 = {1, 3, 4, 5, 20, 30}; // Initializing 2nd vector vector<int> v2 = {1, 5, 6, 7, 25, 30}; // Declaring resultant vector // for union vector<int> v3(10); // Declaring resultant vector // for intersection vector<int> v4(10); // using set_union() to compute union of 2 // containers v1 and v2 and store result in v3 auto it = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin()); // using set_intersection() to compute intersection // of 2 containers v1 and v2 and store result in v4 auto it1 = set_intersection(v1.begin(),v1.end(), v2.begin(), v2.end(), v4.begin()); // resizing new container v3.resize(it - v3.begin()); // resizing new container v4.resize(it1 - v4.begin()); // Displaying set union cout << \"Union of two containers is : \"; for (int &x : v3) cout << x << \" \"; cout << endl; // Displaying set intersection cout << \"Intersection of two containers is : \"; for (int &x : v4) cout << x << \" \"; cout << endl; return 0; }", "e": 30908, "s": 29618, "text": null }, { "code": null, "e": 30918, "s": 30908, "text": "Output: " }, { "code": null, "e": 30928, "s": 30918, "text": "Output: " }, { "code": null, "e": 31023, "s": 30928, "text": "Union of two containers is : 1 3 4 5 6 7 20 25 30 \nIntersection of two containers is : 1 5 30 " }, { "code": null, "e": 31948, "s": 31023, "text": " set_difference(beg1, end1, beg2, end2, beg3) :- This function computes the set difference of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size.set_symmetric_difference(beg1, end1, beg2, end2, beg3) :- This function computes the set symmetric difference of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size. " }, { "code": null, "e": 32402, "s": 31950, "text": "set_difference(beg1, end1, beg2, end2, beg3) :- This function computes the set difference of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size." }, { "code": null, "e": 32875, "s": 32402, "text": "set_symmetric_difference(beg1, end1, beg2, end2, beg3) :- This function computes the set symmetric difference of two containers and stores in new container .It returns the iterator to the last element of resultant container. It takes 5 arguments, first and last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of resultant container . The containers should be sorted and it is necessary that new container is resized to suitable size. " }, { "code": null, "e": 32879, "s": 32875, "text": "CPP" }, { "code": "// C++ code to demonstrate the working of// set_difference() and set_symmetric_difference()#include<iostream>#include<algorithm> // for merge operations#include<vector> // for vectorusing namespace std;int main(){ // Initializing 1st vector vector<int> v1 = {1, 3, 4, 5, 20, 30}; // Initializing 2nd vector vector<int> v2 = {1, 5, 6, 7, 25, 30}; // Declaring resultant vector // for difference vector<int> v3(10); // Declaring resultant vector // for symmetric_difference vector<int> v4(10); // using set_difference() to compute difference // of 2 containers v1 and v2. auto it = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin()); // using set_symmetric_difference() to compute // symmetric_difference/ of 2 containers auto it1 = set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), v4.begin()); // resizing new container v3.resize(it - v3.begin()); // resizing new container v4.resize(it1 - v4.begin()); // Displaying set difference cout << \"Difference of two containers is : \"; for (int &x : v3) cout << x << \" \"; cout << endl; // Displaying set symmetric_difference cout << \"symmetric_difference of two containers is : \"; for (int &x : v4) cout << x << \" \"; cout << endl; return 0; }", "e": 34187, "s": 32879, "text": null }, { "code": null, "e": 34197, "s": 34187, "text": "Output: " }, { "code": null, "e": 34207, "s": 34197, "text": "Output: " }, { "code": null, "e": 34308, "s": 34207, "text": "Difference of two containers is : 3 4 20 \nSymmetric difference of two containers is : 3 4 6 7 20 25 " }, { "code": null, "e": 34734, "s": 34312, "text": "This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34751, "s": 34734, "text": "surinderdawra388" }, { "code": null, "e": 34773, "s": 34751, "text": "cpp-algorithm-library" }, { "code": null, "e": 34785, "s": 34773, "text": "CPP-Library" }, { "code": null, "e": 34796, "s": 34785, "text": "Merge Sort" }, { "code": null, "e": 34800, "s": 34796, "text": "STL" }, { "code": null, "e": 34811, "s": 34800, "text": "C Language" }, { "code": null, "e": 34815, "s": 34811, "text": "C++" }, { "code": null, "e": 34828, "s": 34815, "text": "Mathematical" }, { "code": null, "e": 34841, "s": 34828, "text": "Mathematical" }, { "code": null, "e": 34845, "s": 34841, "text": "STL" }, { "code": null, "e": 34856, "s": 34845, "text": "Merge Sort" }, { "code": null, "e": 34860, "s": 34856, "text": "CPP" }, { "code": null, "e": 34958, "s": 34860, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34967, "s": 34958, "text": "Comments" }, { "code": null, "e": 34980, "s": 34967, "text": "Old Comments" }, { "code": null, "e": 35018, "s": 34980, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 35044, "s": 35018, "text": "Exception Handling in C++" }, { "code": null, "e": 35064, "s": 35044, "text": "Multithreading in C" }, { "code": null, "e": 35105, "s": 35064, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 35127, "s": 35105, "text": "'this' pointer in C++" }, { "code": null, "e": 35145, "s": 35127, "text": "Vector in C++ STL" }, { "code": null, "e": 35191, "s": 35145, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 35234, "s": 35191, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 35253, "s": 35234, "text": "Inheritance in C++" } ]
C++ IOS Library - Iword
It is used to get integer element of extensible array and returns a reference to the object of type long which corresponds to index idx in the internal extensible array. If idx is an index to a new element and the internal extensible array is not long enough (or is not yet allocated), the function extends it (or allocates it) with as many zero-initialized elements as necessary. The reference returned is guaranteed to be valid at least until another operation is performed on the stream object, including another call to iword. Once another operation is performed, the reference may become invalid, although a subsequent call to this same function with the same idx argument returns a reference to the same value within the internal extensible array. The internal extensible array is a general-purpose array of objects of type long (if accessed with member iword) or void* (if accessed with member pword). Libraries may implement this array in diverse ways: iword and pword may or may not share a unique array, and they may not even be arrays, but some other data structure. Following is the declaration for ios_base::iword function. long& iword (int idx); idx − An index value for an element of the internal extensible array. Some implementations expect idx to be a value previously returned by member xalloc. A reference to the element in the internal extensible array whose index is idx. This value is returned as a reference to an object of type long.or else a valid long& initialized to 0L is returned, and (if the stream object inherits from basic_ios) the badbit state flag is set. Basic guarantee − if an exception is thrown, the stream is in a valid state. May modify the stream object. The returned value may also be used to modify it. Concurrent access to the same stream object may cause data races. In below example explains about ios_base::iword function. #include <iostream> std::ostream& Counter (std::ostream& os) { const static int index = os.xalloc(); return os << ++os.iword(index); } int main() { std::cout << Counter << ": first line\n"; std::cout << Counter << ": second line\n"; std::cout << Counter << ": third line\n"; std::cerr << Counter << ": error line\n"; return 0; } Let us compile and run the above program, this will produce the following result − 1: first line 2: second line 3: third line 1: error line Print Add Notes Bookmark this page
[ { "code": null, "e": 2773, "s": 2603, "text": "It is used to get integer element of extensible array and returns a reference to the object of type long which corresponds to index idx in the internal extensible array." }, { "code": null, "e": 2984, "s": 2773, "text": "If idx is an index to a new element and the internal extensible array is not long enough (or is not yet allocated), the function extends it (or allocates it) with as many zero-initialized elements as necessary." }, { "code": null, "e": 3357, "s": 2984, "text": "The reference returned is guaranteed to be valid at least until another operation is performed on the stream object, including another call to iword. Once another operation is performed, the reference may become invalid, although a subsequent call to this same function with the same idx argument returns a reference to the same value within the internal extensible array." }, { "code": null, "e": 3681, "s": 3357, "text": "The internal extensible array is a general-purpose array of objects of type long (if accessed with member iword) or void* (if accessed with member pword). Libraries may implement this array in diverse ways: iword and pword may or may not share a unique array, and they may not even be arrays, but some other data structure." }, { "code": null, "e": 3740, "s": 3681, "text": "Following is the declaration for ios_base::iword function." }, { "code": null, "e": 3763, "s": 3740, "text": "long& iword (int idx);" }, { "code": null, "e": 3917, "s": 3763, "text": "idx − An index value for an element of the internal extensible array. Some implementations expect idx to be a value previously returned by member xalloc." }, { "code": null, "e": 4195, "s": 3917, "text": "A reference to the element in the internal extensible array whose index is idx. This value is returned as a reference to an object of type long.or else a valid long& initialized to 0L is returned, and (if the stream object inherits from basic_ios) the badbit state flag is set." }, { "code": null, "e": 4272, "s": 4195, "text": "Basic guarantee − if an exception is thrown, the stream is in a valid state." }, { "code": null, "e": 4418, "s": 4272, "text": "May modify the stream object. The returned value may also be used to modify it. Concurrent access to the same stream object may cause data races." }, { "code": null, "e": 4476, "s": 4418, "text": "In below example explains about ios_base::iword function." }, { "code": null, "e": 4836, "s": 4476, "text": "#include <iostream> \n\nstd::ostream& Counter (std::ostream& os) {\n const static int index = os.xalloc();\n return os << ++os.iword(index);\n}\n\nint main() {\n std::cout << Counter << \": first line\\n\";\n std::cout << Counter << \": second line\\n\";\n std::cout << Counter << \": third line\\n\";\n \n std::cerr << Counter << \": error line\\n\";\n return 0;\n}" }, { "code": null, "e": 4919, "s": 4836, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 4977, "s": 4919, "text": "1: first line\n2: second line\n3: third line\n1: error line\n" }, { "code": null, "e": 4984, "s": 4977, "text": " Print" }, { "code": null, "e": 4995, "s": 4984, "text": " Add Notes" } ]
Breadth-first search traversal in Javascript
BFS visits the neighbor vertices before visiting the child vertices, and a queue is used in the search process. Following is how a BFS works − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue. If no adjacent vertex is found, remove the first vertex from the queue. Repeat Rule 1 and Rule 2 until the queue is empty. Let us look at an illustration of how BFS Traversal works: At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm we keep on dequeuing in order to get all unvisited nodes. When the queue gets emptied, the program is over. Let's look at how we can implement this in JavaScript. BFS(node) { // Create a Queue and add our initial node in it let q = new Queue(this.nodes.length); let explored = new Set(); q.enqueue(node); // Mark the first node as explored explored. add(node); // We'll continue till our queue gets empty while (!q.isEmpty()) { let t = q.dequeue(); // Log every element that comes out of the Queue console.log(t); // 1. In the edges object, we search for nodes this node is directly connected to. // 2. We filter out the nodes that have already been explored. // 3. Then we mark each unexplored node as explored and add it to the queue. this.edges[t] .filter(n => !explored.has(n)) .forEach(n => { explored.add(n); q.enqueue(n); }); } } You can test this function using − let g = new Graph(); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addNode("E"); g.addNode("F"); g.addNode("G"); g.addEdge("A", "C"); g.addEdge("A", "B"); g.addEdge("A", "D"); g.addEdge("D", "E"); g.addEdge("E", "F"); g.addEdge("B", "G"); g.BFS("A"); This will give the output − A C B D G E F
[ { "code": null, "e": 1205, "s": 1062, "text": "BFS visits the neighbor vertices before visiting the child vertices, and a queue is used in the search process. Following is how a BFS works −" }, { "code": null, "e": 1296, "s": 1205, "text": "Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue." }, { "code": null, "e": 1368, "s": 1296, "text": "If no adjacent vertex is found, remove the first vertex from the queue." }, { "code": null, "e": 1419, "s": 1368, "text": "Repeat Rule 1 and Rule 2 until the queue is empty." }, { "code": null, "e": 1478, "s": 1419, "text": "Let us look at an illustration of how BFS Traversal works:" }, { "code": null, "e": 1674, "s": 1478, "text": "At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm we keep on dequeuing in order to get all unvisited nodes. When the queue gets emptied, the program is over." }, { "code": null, "e": 1730, "s": 1674, "text": "Let's look at how we can implement this in JavaScript. " }, { "code": null, "e": 2513, "s": 1730, "text": "BFS(node) {\n // Create a Queue and add our initial node in it\n let q = new Queue(this.nodes.length);\n let explored = new Set();\n q.enqueue(node);\n\n // Mark the first node as explored explored.\n add(node);\n\n // We'll continue till our queue gets empty\n while (!q.isEmpty()) {\n let t = q.dequeue();\n\n // Log every element that comes out of the Queue\n console.log(t);\n\n // 1. In the edges object, we search for nodes this node is directly connected to.\n // 2. We filter out the nodes that have already been explored.\n // 3. Then we mark each unexplored node as explored and add it to the queue.\n this.edges[t]\n .filter(n => !explored.has(n))\n .forEach(n => {\n explored.add(n);\n q.enqueue(n);\n });\n }\n}" }, { "code": null, "e": 2548, "s": 2513, "text": "You can test this function using −" }, { "code": null, "e": 2821, "s": 2548, "text": "let g = new Graph();\ng.addNode(\"A\");\ng.addNode(\"B\");\ng.addNode(\"C\");\ng.addNode(\"D\");\ng.addNode(\"E\");\ng.addNode(\"F\");\ng.addNode(\"G\");\n\ng.addEdge(\"A\", \"C\");\ng.addEdge(\"A\", \"B\");\ng.addEdge(\"A\", \"D\");\ng.addEdge(\"D\", \"E\");\ng.addEdge(\"E\", \"F\");\ng.addEdge(\"B\", \"G\");\n\ng.BFS(\"A\");" }, { "code": null, "e": 2849, "s": 2821, "text": "This will give the output −" }, { "code": null, "e": 2863, "s": 2849, "text": "A\nC\nB\nD\nG\nE\nF" } ]
AI as a Movie Maker. How I created an entire short movie... | by Merzmensch | Towards Data Science
It ’s been a blast. I remember watching “Sunspring” — again and again. Fascinated and mesmerized by the absurd dialogues, I was trying to comprehend what’s going on in this short movie. But the meaning used to slip away. Because it was written by AI. Benjamin was the name of the author. Behind this name was a recurrent neural network LSTM hidden, developed by Ross Goodwin, an AI researcher and poet. The movie was directed by BAFTA-nominated British filmmaker Oscar Sharp and featured a Thomas Middleditch among others. Even if the plot consisted of absurdist and seemingly random phrases, our human brain was trying to get it. Cogito, ergo sum — I think therefore I am. Ross’ must-read essays about AI and creativity were highly inspiring for me. If you haven’t a chance, do read this. medium.com medium.com With his experiments (and later with his AI-generated book “1 the Road”), Ross proved what is possible to achieve with Artificial Intelligence. And also this realization was a crucial one: AI is neither just a tool nor an entire replacement for a writer. You need a symbiosis to create art together with AI. We’ve seen how many creative uses of Machine Learning are possible. With the 3D Ken Burns Effect, we can make animated dream visions, converting a photo to a spatial camera flight. With GPT-2 by OpenAI, we can write entire stories. But what if we combine all the approaches to one single artwork? And so I did it and generated a short movie completely with AI. ...But before you watch it: do you have an idea, what do you need to create a movie? You surely can waive some elements for arthouse quality, but usually, you need the following ingredients to make a movie (even if a short one): the Plot the Camera / Visuals the Actors the Music You also need an original idea and (in most cases) still unused media assets. So how can we apply the Machine Learning approach to fulfill all of these points? As previously mentioned, GPT-2 is a powerful NLP model (pre-trained on 40 GB text with 1.5 billion parameters) to generate writings. Its main flaw — and the major advantage — is the surreal character of created contents. They usually don’t make sense (at least for knowledge transfer needs — in a literary context they can be a decent object of interpretation). And: every time a new unique text is generated. Let’s see which ways GPT-3 will take in the future (OpenAI published this new giant model with 175 billion parameters, which at the moment cannot be fine-tuned due to its excessive dimensions). For my needs I used a GPT-2 Colab Notebook with Java Interface by Manuel Romero: colab.research.google.com There are several different notebooks, allowing you to fine-tune GPT-2 or train on your texts, but I’ve chosen this particular Colab Notebook for its user-friendly and robust structure, and support of the entire 1.5 billion parameter model. For my movie I entered the following prompt: Empty room.A man enters the room.He looks out of the window and says: "It still hasn't begun".The woman enters. She has a white dress on and a book in her hand.The woman: "I am waiting as well."The man: "For how long?"The woman: "For a while." GPT-2 provided me with various texts, but the one I’ve selected was an amazing piece of an absurdist theater play, somewhere between Beckett, Mrozek and David Lynch: Empty room.A man enters the room.He looks out of the window and says: "It still hasn't begun".The woman enters. She has a white dress on and a book in her hand.The woman: "I am waiting as well."The man: "For how long?"The woman: "For a while."The man: "Ah, you know, I'm a very patient man."The woman: "I know, of course."The man: "I'm going to have to be less patient, then." The woman starts to laugh; the laughter has an ominous edge that only she can feel."In my defence," she says, "I never actually told you what it was I was going to tell you."The man, suddenly, remembers: "That's right."The woman: "So you are lying behind me." The man is surprised by the abruptness of the accusation. He does not, however, feel any anger; as he has noticed in previous encounters, it is the woman who is most convincing when she's saying the lies.The man: "But it was not what you expected."The woman: "Oh...no." She is trying to sound convincing.He wants to ask her about her mother. The woman: "Do you think she'll be willing to lie?"The man turns down the opportunity.The woman: "Maybe...""Why?""Maybe she's still grieving." She is smiling when she says this, and the man doesn't think she'll be the first to smile when the truth comes out.He gives up. "No."The woman: "It's not over." The man has not got to see her family again. He had hoped to return to his work. He has nothing else to do. He wants to be a man. It convinced me also because of ambiguous communication levels. It’s as if there is a huge story hidden behind all those sparse phrases (human brain does wonders during interpretation, indeed). So I had a screenplay. I am a fan of StyleGAN2, but especially in its implementation in ArtBreeder (at least in the section “Portraits”). You can generate new faces, you can make transitions or even animations (read more about using Artbreeder here). So I created a bunch of images for faces (see here the assets) of the Man, the Woman, and some Room pictures. It was a tricky thing to align the face modification to the story part (e.g. in the “laughter moments” etc.), but after various trials and errors, it worked for me. Here are just some assets used for the visuals: Sure, you can use the First Order Motion Model for dynamical face animations (using yourself with your Andy Serkis skills): But for my absurdist and minimalist style, the face morphing was most appropriate. The faces were already made, but something was still missing: voices. Voice generation is one of probably the oldest Machine Learning approaches. My favorite was MelNet — a Model with unbelievable quality. Just listen to the samples (trained on professional speakers or also celebrities datasets). Alas, MelNet wasn’t available as a working repository or Colab Notebook. My second choice was Amazon Polly. Being a part of Amazon AWS AI/ML-Services Polly provides a broad quantity of voices in various languages. The downside is: most of them have rather a charisma of an anchorman and are not always suitable for fictional content. I used one voice for my AI-generated video “Predictions”: Still, the non-emotional voice is not really convincing, if used in some dialogues. Then I discovered Replica Studios. They provide at the moment a small collection, but the voices have astonishing quality. Some of them can be rather used for anchorman need, but another bear already theatrical power within. I’ve chosen these three voices — Deckard for Narrator, Carlos for Man, and Audrey for Woman. You also can experiment with the emotional features of various voices, you even can train them your voice, but these three were perfect for my needs. The use of Replica Studios is pretty easy. You sort the phrases in chronological order and apply the appropriate voices to the characters: It’s possible to export the voices to mp3-files for your project. AI-generated music achieved new levels of quality this year after OpenAI released JukeBox — a library of 7k songs and music pieces, being generated with pre-trained models on various musicians and songwriters (read also here). Many of them are pretty glitchy (like this nightmarish “Mozart” piece). But many of them are beautiful. And especially combined with AI-generated visuals they evoke strange feelings within. I am using them for my series “Breath ZeroX”: For our video something cinematic should pass, so I looked up the music trained on Hans Zimmer (and changed the speed a little bit): The rest was rather hard work of a cutter — for my video I used Premiere Pro and amounts of coffee. Probably the most tricky thing was stretching the videos in time and synchronize them with the plot (original face transitions by ArtBreeder were between 8–30 sec long). Advice: I used “Time Interpolation: Optical Flow”. It creates new frames between the existent and makes the footage fluent. Sometimes it generates glitches — but they are always welcome if it’s about digitally generated films! And now: here it is. I wonder which new audio-visual treasures will come with new ML-approaches. Let‘s stay tuned!
[ { "code": null, "e": 297, "s": 46, "text": "It ’s been a blast. I remember watching “Sunspring” — again and again. Fascinated and mesmerized by the absurd dialogues, I was trying to comprehend what’s going on in this short movie. But the meaning used to slip away. Because it was written by AI." }, { "code": null, "e": 569, "s": 297, "text": "Benjamin was the name of the author. Behind this name was a recurrent neural network LSTM hidden, developed by Ross Goodwin, an AI researcher and poet. The movie was directed by BAFTA-nominated British filmmaker Oscar Sharp and featured a Thomas Middleditch among others." }, { "code": null, "e": 720, "s": 569, "text": "Even if the plot consisted of absurdist and seemingly random phrases, our human brain was trying to get it. Cogito, ergo sum — I think therefore I am." }, { "code": null, "e": 836, "s": 720, "text": "Ross’ must-read essays about AI and creativity were highly inspiring for me. If you haven’t a chance, do read this." }, { "code": null, "e": 847, "s": 836, "text": "medium.com" }, { "code": null, "e": 858, "s": 847, "text": "medium.com" }, { "code": null, "e": 1166, "s": 858, "text": "With his experiments (and later with his AI-generated book “1 the Road”), Ross proved what is possible to achieve with Artificial Intelligence. And also this realization was a crucial one: AI is neither just a tool nor an entire replacement for a writer. You need a symbiosis to create art together with AI." }, { "code": null, "e": 1234, "s": 1166, "text": "We’ve seen how many creative uses of Machine Learning are possible." }, { "code": null, "e": 1347, "s": 1234, "text": "With the 3D Ken Burns Effect, we can make animated dream visions, converting a photo to a spatial camera flight." }, { "code": null, "e": 1398, "s": 1347, "text": "With GPT-2 by OpenAI, we can write entire stories." }, { "code": null, "e": 1527, "s": 1398, "text": "But what if we combine all the approaches to one single artwork? And so I did it and generated a short movie completely with AI." }, { "code": null, "e": 1612, "s": 1527, "text": "...But before you watch it: do you have an idea, what do you need to create a movie?" }, { "code": null, "e": 1756, "s": 1612, "text": "You surely can waive some elements for arthouse quality, but usually, you need the following ingredients to make a movie (even if a short one):" }, { "code": null, "e": 1765, "s": 1756, "text": "the Plot" }, { "code": null, "e": 1786, "s": 1765, "text": "the Camera / Visuals" }, { "code": null, "e": 1797, "s": 1786, "text": "the Actors" }, { "code": null, "e": 1807, "s": 1797, "text": "the Music" }, { "code": null, "e": 1885, "s": 1807, "text": "You also need an original idea and (in most cases) still unused media assets." }, { "code": null, "e": 1967, "s": 1885, "text": "So how can we apply the Machine Learning approach to fulfill all of these points?" }, { "code": null, "e": 2377, "s": 1967, "text": "As previously mentioned, GPT-2 is a powerful NLP model (pre-trained on 40 GB text with 1.5 billion parameters) to generate writings. Its main flaw — and the major advantage — is the surreal character of created contents. They usually don’t make sense (at least for knowledge transfer needs — in a literary context they can be a decent object of interpretation). And: every time a new unique text is generated." }, { "code": null, "e": 2571, "s": 2377, "text": "Let’s see which ways GPT-3 will take in the future (OpenAI published this new giant model with 175 billion parameters, which at the moment cannot be fine-tuned due to its excessive dimensions)." }, { "code": null, "e": 2652, "s": 2571, "text": "For my needs I used a GPT-2 Colab Notebook with Java Interface by Manuel Romero:" }, { "code": null, "e": 2678, "s": 2652, "text": "colab.research.google.com" }, { "code": null, "e": 2919, "s": 2678, "text": "There are several different notebooks, allowing you to fine-tune GPT-2 or train on your texts, but I’ve chosen this particular Colab Notebook for its user-friendly and robust structure, and support of the entire 1.5 billion parameter model." }, { "code": null, "e": 2964, "s": 2919, "text": "For my movie I entered the following prompt:" }, { "code": null, "e": 3208, "s": 2964, "text": "Empty room.A man enters the room.He looks out of the window and says: \"It still hasn't begun\".The woman enters. She has a white dress on and a book in her hand.The woman: \"I am waiting as well.\"The man: \"For how long?\"The woman: \"For a while.\"" }, { "code": null, "e": 3374, "s": 3208, "text": "GPT-2 provided me with various texts, but the one I’ve selected was an amazing piece of an absurdist theater play, somewhere between Beckett, Mrozek and David Lynch:" }, { "code": null, "e": 4787, "s": 3374, "text": "Empty room.A man enters the room.He looks out of the window and says: \"It still hasn't begun\".The woman enters. She has a white dress on and a book in her hand.The woman: \"I am waiting as well.\"The man: \"For how long?\"The woman: \"For a while.\"The man: \"Ah, you know, I'm a very patient man.\"The woman: \"I know, of course.\"The man: \"I'm going to have to be less patient, then.\" The woman starts to laugh; the laughter has an ominous edge that only she can feel.\"In my defence,\" she says, \"I never actually told you what it was I was going to tell you.\"The man, suddenly, remembers: \"That's right.\"The woman: \"So you are lying behind me.\" The man is surprised by the abruptness of the accusation. He does not, however, feel any anger; as he has noticed in previous encounters, it is the woman who is most convincing when she's saying the lies.The man: \"But it was not what you expected.\"The woman: \"Oh...no.\" She is trying to sound convincing.He wants to ask her about her mother. The woman: \"Do you think she'll be willing to lie?\"The man turns down the opportunity.The woman: \"Maybe...\"\"Why?\"\"Maybe she's still grieving.\" She is smiling when she says this, and the man doesn't think she'll be the first to smile when the truth comes out.He gives up. \"No.\"The woman: \"It's not over.\" The man has not got to see her family again. He had hoped to return to his work. He has nothing else to do. He wants to be a man." }, { "code": null, "e": 4981, "s": 4787, "text": "It convinced me also because of ambiguous communication levels. It’s as if there is a huge story hidden behind all those sparse phrases (human brain does wonders during interpretation, indeed)." }, { "code": null, "e": 5004, "s": 4981, "text": "So I had a screenplay." }, { "code": null, "e": 5119, "s": 5004, "text": "I am a fan of StyleGAN2, but especially in its implementation in ArtBreeder (at least in the section “Portraits”)." }, { "code": null, "e": 5342, "s": 5119, "text": "You can generate new faces, you can make transitions or even animations (read more about using Artbreeder here). So I created a bunch of images for faces (see here the assets) of the Man, the Woman, and some Room pictures." }, { "code": null, "e": 5507, "s": 5342, "text": "It was a tricky thing to align the face modification to the story part (e.g. in the “laughter moments” etc.), but after various trials and errors, it worked for me." }, { "code": null, "e": 5555, "s": 5507, "text": "Here are just some assets used for the visuals:" }, { "code": null, "e": 5679, "s": 5555, "text": "Sure, you can use the First Order Motion Model for dynamical face animations (using yourself with your Andy Serkis skills):" }, { "code": null, "e": 5762, "s": 5679, "text": "But for my absurdist and minimalist style, the face morphing was most appropriate." }, { "code": null, "e": 5832, "s": 5762, "text": "The faces were already made, but something was still missing: voices." }, { "code": null, "e": 6133, "s": 5832, "text": "Voice generation is one of probably the oldest Machine Learning approaches. My favorite was MelNet — a Model with unbelievable quality. Just listen to the samples (trained on professional speakers or also celebrities datasets). Alas, MelNet wasn’t available as a working repository or Colab Notebook." }, { "code": null, "e": 6394, "s": 6133, "text": "My second choice was Amazon Polly. Being a part of Amazon AWS AI/ML-Services Polly provides a broad quantity of voices in various languages. The downside is: most of them have rather a charisma of an anchorman and are not always suitable for fictional content." }, { "code": null, "e": 6452, "s": 6394, "text": "I used one voice for my AI-generated video “Predictions”:" }, { "code": null, "e": 6536, "s": 6452, "text": "Still, the non-emotional voice is not really convincing, if used in some dialogues." }, { "code": null, "e": 6571, "s": 6536, "text": "Then I discovered Replica Studios." }, { "code": null, "e": 6761, "s": 6571, "text": "They provide at the moment a small collection, but the voices have astonishing quality. Some of them can be rather used for anchorman need, but another bear already theatrical power within." }, { "code": null, "e": 6854, "s": 6761, "text": "I’ve chosen these three voices — Deckard for Narrator, Carlos for Man, and Audrey for Woman." }, { "code": null, "e": 7004, "s": 6854, "text": "You also can experiment with the emotional features of various voices, you even can train them your voice, but these three were perfect for my needs." }, { "code": null, "e": 7143, "s": 7004, "text": "The use of Replica Studios is pretty easy. You sort the phrases in chronological order and apply the appropriate voices to the characters:" }, { "code": null, "e": 7209, "s": 7143, "text": "It’s possible to export the voices to mp3-files for your project." }, { "code": null, "e": 7436, "s": 7209, "text": "AI-generated music achieved new levels of quality this year after OpenAI released JukeBox — a library of 7k songs and music pieces, being generated with pre-trained models on various musicians and songwriters (read also here)." }, { "code": null, "e": 7626, "s": 7436, "text": "Many of them are pretty glitchy (like this nightmarish “Mozart” piece). But many of them are beautiful. And especially combined with AI-generated visuals they evoke strange feelings within." }, { "code": null, "e": 7672, "s": 7626, "text": "I am using them for my series “Breath ZeroX”:" }, { "code": null, "e": 7805, "s": 7672, "text": "For our video something cinematic should pass, so I looked up the music trained on Hans Zimmer (and changed the speed a little bit):" }, { "code": null, "e": 8075, "s": 7805, "text": "The rest was rather hard work of a cutter — for my video I used Premiere Pro and amounts of coffee. Probably the most tricky thing was stretching the videos in time and synchronize them with the plot (original face transitions by ArtBreeder were between 8–30 sec long)." }, { "code": null, "e": 8302, "s": 8075, "text": "Advice: I used “Time Interpolation: Optical Flow”. It creates new frames between the existent and makes the footage fluent. Sometimes it generates glitches — but they are always welcome if it’s about digitally generated films!" }, { "code": null, "e": 8323, "s": 8302, "text": "And now: here it is." } ]
Python - How to search for a string in text files? - GeeksforGeeks
24 Jan, 2021 In this article, we are going to see how to search for a particular string in a text file. Consider below text File : Example 1: we are going to search string line by line if the string found then we will print that string and line number. Steps: Open a file. Set variables index and flag to zero. Run a loop through the file line by line. In that loop check condition using the ‘in’ operator for string present in line or not. If found flag to 0. After loop again check condition for the flag is set or not. If set string found then print a string and line number otherwise simply print the message ‘String not found’. Close a file. Code: Python3 string1 = 'coding' # opening a text filefile1 = open("geeks.txt", "r") # setting flag and index to 0flag = 0index = 0 # Loop through the file line by linefor line in file1: index + = 1 # checking string is present in line or not if string1 in line: flag = 1 break # checking condition for string found or notif flag == 0: print('String', string1 , 'Not Found') else: print('String', string1, 'Found In Line', index) # closing text file file1.close() Output: Example 2: We are just finding string is present in the file or not. Step: open a file. Read a file and store it in a variable. check condition using ‘in’ operator for string present in the file or not. If the condition true then print the message ‘string is found’ otherwise print ‘string not found’. Close a file. Python3 string1 = 'portal' # opening a text filefile1 = open("geeks.txt", "r") # read file contentreadfile = file1.read() # checking condition for string found or notif string1 in readfile: print('String', string1, 'Found In File')else: print('String', string1 , 'Not Found') # closing a filefile1.close() Output: Picked Python file-handling-programs python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Python OOPs Concepts Different ways to create Pandas Dataframe sum() function in Python How to Install PIP on Windows ? Stack in Python Bar Plot in Matplotlib Defaultdict in Python Graph Plotting in Python | Set 1
[ { "code": null, "e": 24843, "s": 24815, "text": "\n24 Jan, 2021" }, { "code": null, "e": 24934, "s": 24843, "text": "In this article, we are going to see how to search for a particular string in a text file." }, { "code": null, "e": 24961, "s": 24934, "text": "Consider below text File :" }, { "code": null, "e": 25083, "s": 24961, "text": "Example 1: we are going to search string line by line if the string found then we will print that string and line number." }, { "code": null, "e": 25090, "s": 25083, "text": "Steps:" }, { "code": null, "e": 25103, "s": 25090, "text": "Open a file." }, { "code": null, "e": 25141, "s": 25103, "text": "Set variables index and flag to zero." }, { "code": null, "e": 25183, "s": 25141, "text": "Run a loop through the file line by line." }, { "code": null, "e": 25291, "s": 25183, "text": "In that loop check condition using the ‘in’ operator for string present in line or not. If found flag to 0." }, { "code": null, "e": 25463, "s": 25291, "text": "After loop again check condition for the flag is set or not. If set string found then print a string and line number otherwise simply print the message ‘String not found’." }, { "code": null, "e": 25477, "s": 25463, "text": "Close a file." }, { "code": null, "e": 25483, "s": 25477, "text": "Code:" }, { "code": null, "e": 25491, "s": 25483, "text": "Python3" }, { "code": "string1 = 'coding' # opening a text filefile1 = open(\"geeks.txt\", \"r\") # setting flag and index to 0flag = 0index = 0 # Loop through the file line by linefor line in file1: index + = 1 # checking string is present in line or not if string1 in line: flag = 1 break # checking condition for string found or notif flag == 0: print('String', string1 , 'Not Found') else: print('String', string1, 'Found In Line', index) # closing text file file1.close() ", "e": 26001, "s": 25491, "text": null }, { "code": null, "e": 26009, "s": 26001, "text": "Output:" }, { "code": null, "e": 26078, "s": 26009, "text": "Example 2: We are just finding string is present in the file or not." }, { "code": null, "e": 26084, "s": 26078, "text": "Step:" }, { "code": null, "e": 26097, "s": 26084, "text": "open a file." }, { "code": null, "e": 26137, "s": 26097, "text": "Read a file and store it in a variable." }, { "code": null, "e": 26212, "s": 26137, "text": "check condition using ‘in’ operator for string present in the file or not." }, { "code": null, "e": 26311, "s": 26212, "text": "If the condition true then print the message ‘string is found’ otherwise print ‘string not found’." }, { "code": null, "e": 26325, "s": 26311, "text": "Close a file." }, { "code": null, "e": 26333, "s": 26325, "text": "Python3" }, { "code": "string1 = 'portal' # opening a text filefile1 = open(\"geeks.txt\", \"r\") # read file contentreadfile = file1.read() # checking condition for string found or notif string1 in readfile: print('String', string1, 'Found In File')else: print('String', string1 , 'Not Found') # closing a filefile1.close() ", "e": 26645, "s": 26333, "text": null }, { "code": null, "e": 26653, "s": 26645, "text": "Output:" }, { "code": null, "e": 26660, "s": 26653, "text": "Picked" }, { "code": null, "e": 26690, "s": 26660, "text": "Python file-handling-programs" }, { "code": null, "e": 26711, "s": 26690, "text": "python-file-handling" }, { "code": null, "e": 26718, "s": 26711, "text": "Python" }, { "code": null, "e": 26816, "s": 26718, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26825, "s": 26816, "text": "Comments" }, { "code": null, "e": 26838, "s": 26825, "text": "Old Comments" }, { "code": null, "e": 26856, "s": 26838, "text": "Python Dictionary" }, { "code": null, "e": 26878, "s": 26856, "text": "Enumerate() in Python" }, { "code": null, "e": 26899, "s": 26878, "text": "Python OOPs Concepts" }, { "code": null, "e": 26941, "s": 26899, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26966, "s": 26941, "text": "sum() function in Python" }, { "code": null, "e": 26998, "s": 26966, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27014, "s": 26998, "text": "Stack in Python" }, { "code": null, "e": 27037, "s": 27014, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27059, "s": 27037, "text": "Defaultdict in Python" } ]
Find the smallest positive number missing from an unsorted array | Set 1 - GeeksforGeeks
11 Apr, 2022 You are given an unsorted array with both positive and negative elements. You have to find the smallest positive number missing from the array in O(n) time using constant extra space. You can modify the original array. Examples Input: {2, 3, 7, 6, 8, -1, -10, 15} Output: 1 Input: { 2, 3, -7, 6, 8, 1, -10, 15 } Output: 4 Input: {1, 1, 0, -1, -2} Output: 2 A naive method to solve this problem is to search all positive integers, starting from 1 in the given array. We may have to search at most n+1 numbers in the given array. So this solution takes O(n^2) in worst case. We can use sorting to solve it in lesser time complexity. We can sort the array in O(nLogn) time. Once the array is sorted, then all we need to do is a linear scan of the array. So this approach takes O(nLogn + n) time which is O(nLogn). We can also use hashing. We can build a hash table of all positive elements in the given array. Once the hash table is built. We can look in the hash table for all positive integers, starting from 1. As soon as we find a number which is not there in hash table, we return it. This approach may take O(n) time on average, but it requires O(n) extra space. A O(n) time and O(1) extra space solution: The idea is similar to this post. We use array elements as index. To mark presence of an element x, we change the value at the index x to negative. But this approach doesn’t work if there are non-positive (-ve and 0) numbers. So we segregate positive from negative numbers as first step and then apply the approach. Following is the two step algorithm. 1) Segregate positive numbers from others i.e., move all non-positive numbers to left side. In the following code, segregate() function does this part. 2) Now we can ignore non-positive elements and consider only the part of array which contains all positive elements. We traverse the array containing all positive numbers and to mark presence of an element x, we change the sign of value at index x to negative. We traverse the array again and print the first index which has positive value. In the following code, findMissingPositive() function does this part. Note that in findMissingPositive, we have subtracted 1 from the values as indexes start from 0 in C. C++ C Java Python3 C# Javascript /* C++ program to find the smallest positive missing number */#include <bits/stdc++.h>using namespace std; /* Utility to swap to integers */void swap(int* a, int* b){ int temp; temp = *a; *a = *b; *b = temp;} /* Utility function that puts allnon-positive (0 and negative) numbers on leftside of arr[] and return count of such numbers */int segregate(int arr[], int size){ int j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { swap(&arr[i], &arr[j]); // increment count of // non-positive integers j++; } } return j;} /* Find the smallest positive missing numberin an array that contains all positive integers */int findMissingPositive(int arr[], int size){ int i; // Mark arr[i] as visited by // making arr[arr[i] - 1] negative. // Note that 1 is subtracted // because index start // from 0 and positive numbers start from 1 for (i = 0; i < size; i++) { if (abs(arr[i]) - 1 < size && arr[abs(arr[i]) - 1] > 0) arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]; } // Return the first index // value at which is positive for (i = 0; i < size; i++) if (arr[i] > 0) // 1 is added because // indexes start from 0 return i + 1; return size + 1;} /* Find the smallest positive missingnumber in an array that containsboth positive and negative integers */int findMissing(int arr[], int size){ // First separate positive // and negative numbers int shift = segregate(arr, size); // Shift the array and call // findMissingPositive for // positive part return findMissingPositive(arr + shift, size - shift);} // Driver codeint main(){ int arr[] = { 0, 10, 2, -10, -20 }; int arr_size = sizeof(arr) / sizeof(arr[0]); int missing = findMissing(arr, arr_size); cout << "The smallest positive missing number is " << missing; return 0;} // This is code is contributed by rathbhupendra /* C program to find the smallest positive missing number */#include <stdio.h>#include <stdlib.h> /* Utility to swap to integers */void swap(int* a, int* b){ int temp; temp = *a; *a = *b; *b = temp;} /* Utility function that puts allnon-positive (0 and negative) numbers on leftside of arr[] and return count of such numbers */int segregate(int arr[], int size){ int j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { swap(&arr[i], &arr[j]); j++; // increment count of non-positive integers } } return j;} /* Find the smallest positive missing numberin an array that contains all positive integers */int findMissingPositive(int arr[], int size){ int i; // Mark arr[i] as visited by // making arr[arr[i] - 1] negative. // Note that 1 is subtracted // because index start // from 0 and positive numbers start from 1 for (i = 0; i < size; i++) { if (abs(arr[i]) - 1 < size && arr[abs(arr[i]) - 1] > 0) arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]; } // Return the first index value at which is positive for (i = 0; i < size; i++) if (arr[i] > 0) // 1 is added because indexes start from 0 return i + 1; return size + 1;} /* Find the smallest positive missingnumber in an array that containsboth positive and negative integers */int findMissing(int arr[], int size){ // First separate positive and negative numbers int shift = segregate(arr, size); // Shift the array and call findMissingPositive for // positive part return findMissingPositive(arr + shift, size - shift);} // Driver codeint main(){ int arr[] = { 0, 10, 2, -10, -20 }; int arr_size = sizeof(arr) / sizeof(arr[0]); int missing = findMissing(arr, arr_size); printf("The smallest positive missing number is %d ", missing); getchar(); return 0;} // Java program to find the smallest// positive missing numberimport java.util.*; class Main { /* Utility function that puts all non-positive (0 and negative) numbers on left side of arr[] and return count of such numbers */ static int segregate(int arr[], int size) { int j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { int temp; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // increment count of non-positive // integers j++; } } return j; } /* Find the smallest positive missing number in an array that contains all positive integers */ static int findMissingPositive(int arr[], int size) { int i; // Mark arr[i] as visited by making // arr[arr[i] - 1] negative. Note that // 1 is subtracted because index start // from 0 and positive numbers start from 1 for (i = 0; i < size; i++) { int x = Math.abs(arr[i]); if (x - 1 < size && arr[x - 1] > 0) arr[x - 1] = -arr[x - 1]; } // Return the first index value at which // is positive for (i = 0; i < size; i++) if (arr[i] > 0) return i + 1; // 1 is added because indexes // start from 0 return size + 1; } /* Find the smallest positive missing number in an array that contains both positive and negative integers */ static int findMissing(int arr[], int size) { // First separate positive and // negative numbers int shift = segregate(arr, size); int arr2[] = new int[size - shift]; int j = 0; for (int i = shift; i < size; i++) { arr2[j] = arr[i]; j++; } // Shift the array and call // findMissingPositive for // positive part return findMissingPositive(arr2, j); } // Driver code public static void main(String[] args) { int arr[] = { 0, 10, 2, -10, -20 }; int arr_size = arr.length; int missing = findMissing(arr, arr_size); System.out.println("The smallest positive missing number is " + missing); }} ''' Python3 program to find thesmallest positive missing number ''' ''' Utility function that puts allnon-positive (0 and negative) numbers on leftside of arr[] and return count of such numbers '''def segregate(arr, size): j = 0 for i in range(size): if (arr[i] <= 0): arr[i], arr[j] = arr[j], arr[i] j += 1 # increment count of non-positive integers return j ''' Find the smallest positive missing numberin an array that contains all positive integers '''def findMissingPositive(arr, size): # Mark arr[i] as visited by # making arr[arr[i] - 1] negative. # Note that 1 is subtracted # because index start # from 0 and positive numbers start from 1 for i in range(size): if (abs(arr[i]) - 1 < size and arr[abs(arr[i]) - 1] > 0): arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1] # Return the first index value at which is positive for i in range(size): if (arr[i] > 0): # 1 is added because indexes start from 0 return i + 1 return size + 1 ''' Find the smallest positive missingnumber in an array that containsboth positive and negative integers '''def findMissing(arr, size): # First separate positive and negative numbers shift = segregate(arr, size) # Shift the array and call findMissingPositive for # positive part return findMissingPositive(arr[shift:], size - shift) # Driver codearr = [ 0, 10, 2, -10, -20 ]arr_size = len(arr)missing = findMissing(arr, arr_size)print("The smallest positive missing number is ", missing) # This code is contributed by Shubhamsingh10 // C# program to find the smallest// positive missing numberusing System; class main { // Utility function that puts all // non-positive (0 and negative) // numbers on left side of arr[] // and return count of such numbers static int segregate(int[] arr, int size) { int j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { int temp; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // increment count of non-positive // integers j++; } } return j; } // Find the smallest positive missing // number in an array that contains // all positive integers static int findMissingPositive(int[] arr, int size) { int i; // Mark arr[i] as visited by making // arr[arr[i] - 1] negative. Note that // 1 is subtracted as index start from // 0 and positive numbers start from 1 for (i = 0; i < size; i++) { if (Math.Abs(arr[i]) - 1 < size && arr[ Math.Abs(arr[i]) - 1] > 0) arr[ Math.Abs(arr[i]) - 1] = -arr[ Math.Abs(arr[i]) - 1]; } // Return the first index value at // which is positive for (i = 0; i < size; i++) if (arr[i] > 0) return i + 1; // 1 is added because indexes // start from 0 return size + 1; } // Find the smallest positive // missing number in array that // contains both positive and // negative integers static int findMissing(int[] arr, int size) { // First separate positive and // negative numbers int shift = segregate(arr, size); int[] arr2 = new int[size - shift]; int j = 0; for (int i = shift; i < size; i++) { arr2[j] = arr[i]; j++; } // Shift the array and call // findMissingPositive for // positive part return findMissingPositive(arr2, j); } // Driver code public static void Main() { int[] arr = { 0, 10, 2, -10, -20 }; int arr_size = arr.Length; int missing = findMissing(arr, arr_size); Console.WriteLine("The smallest positive missing number is " + missing); }} // This code is contributed by Anant Agarwal. <script>// Javascript program to find the smallest// positive missing number /* Utility function that puts all non-positive (0 and negative) numbers on left side of arr[] and return count of such numbers */function segregate(arr,size){ let j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { let temp; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // increment count of non-positive // integers j++; } } return j;} /* Find the smallest positive missing number in an array that contains all positive integers */function findMissingPositive(arr,size){ let i; // Mark arr[i] as visited by making // arr[arr[i] - 1] negative. Note that // 1 is subtracted because index start // from 0 and positive numbers start from 1 for (i = 0; i < size; i++) { let x = Math.abs(arr[i]); if (x - 1 < size && arr[x - 1] > 0) arr[x - 1] = -arr[x - 1]; } // Return the first index value at which // is positive for (i = 0; i < size; i++) if (arr[i] > 0) return i + 1; // 1 is added because indexes // start from 0 return size + 1;} /* Find the smallest positive missing number in an array that contains both positive and negative integers */function findMissing(arr,size){ // First separate positive and // negative numbers let shift = segregate(arr, size); let arr2 = new Array(size - shift); let j = 0; for (let i = shift; i < size; i++) { arr2[j] = arr[i]; j++; } // Shift the array and call // findMissingPositive for // positive part return findMissingPositive(arr2, j);} // Driver codelet arr = [0, 10, 2, -10, -20];let arr_size = arr.length;let missing = findMissing(arr, arr_size);document.write("The smallest positive missing number is " + missing); // This code is contributed by rag2127</script> The smallest positive missing number is 1 Note that this method modifies the original array. We can change the sign of elements in the segregated array to get the same set of elements back. But we still loose the order of elements. If we want to keep the original array as it was, then we can create a copy of the array and run this approach on the temp array. Another approach: In this problem, we have created a list full of 0’s with size of the max() value of our given array. Now, whenever we encounter any positive value in our original array, we change the index value of our list to 1. So, after we are done, we simply iterate through our modified list, the first 0 we encounter, its (index value + 1) should be our answer since index in python starts from 0. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the first missing positive// number from the given unsorted arrayint firstMissingPos(int A[], int n){ // To mark the occurrence of elements bool present[n + 1] = { false }; // Mark the occurrences for (int i = 0; i < n; i++) { // Only mark the required elements // All non-positive elements and // the elements greater n + 1 will never // be the answer // For example, the array will be {1, 2, 3} // in the worst case and the result // will be 4 which is n + 1 if (A[i] > 0 && A[i] <= n) present[A[i]] = true; } // Find the first element which didn't // appear in the original array for (int i = 1; i <= n; i++) if (!present[i]) return i; // If the original array was of the // type {1, 2, 3} in its sorted form return n + 1;} // Driver codeint main(){ int A[] = { 0, 10, 2, -10, -20 }; int size = sizeof(A) / sizeof(A[0]); cout << firstMissingPos(A, size);} // This code is contributed by gp6 // Java Program to find the smallest// positive missing numberimport java.util.*;public class GFG { static int solution(int[] A) { int n = A.length; //Let this 1e6 be the maximum element provided in the array; int N=1000010; // To mark the occurrence of elements boolean[] present = new boolean[N]; int maxele=Integer.MIN_VALUE; // Mark the occurrences for (int i = 0; i < n; i++) { // Only mark the required elements // All non-positive elements and // the elements greater n + 1 will never // be the answer // For example, the array will be {1, 2, 3} // in the worst case and the result // will be 4 which is n + 1 if (A[i] > 0 && A[i] <= n) present[A[i]] = true; //find the maximum element so that if all the elements are in order can directly return the next number maxele=Math.max(maxele,A[i]); } // Find the first element which didn't // appear in the original array for (int i = 1; i < N; i++) if (!present[i]) return i; // If the original array was of the // type {1, 2, 3} in its sorted form return maxele + 1; } // Driver Code public static void main(String[] args) { int A[] = { 0, 10, 2, -10, -20 }; System.out.println(solution(A)); int arr[]={-2,-1,0,1,2,3,4}; System.out.println(solution(arr)); }}// This code is contributed by Arava Sai Teja # Python3 Program to find the smallest# positive missing number def solution(A): # Our original array m = max(A) # Storing maximum value if m < 1: # In case all values in our array are negative return 1 if len(A) == 1: # If it contains only one element return 2 if A[0] == 1 else 1 l = [0] * m for i in range(len(A)): if A[i] > 0: if l[A[i] - 1] != 1: # Changing the value status at the index of our list l[A[i] - 1] = 1 for i in range(len(l)): # Encountering first 0, i.e, the element with least value if l[i] == 0: return i + 1 # In case all values are filled between 1 and m return i + 2 # Driver CodeA = [0, 10, 2, -10, -20]print(solution(A)) // C# Program to find the smallest// positive missing numberusing System;using System.Linq; class GFG { static int solution(int[] A) { // Our original array int m = A.Max(); // Storing maximum value // In case all values in our array are negative if (m < 1) { return 1; } if (A.Length == 1) { // If it contains only one element if (A[0] == 1) { return 2; } else { return 1; } } int i = 0; int[] l = new int[m]; for (i = 0; i < A.Length; i++) { if (A[i] > 0) { // Changing the value status at the index of // our list if (l[A[i] - 1] != 1) { l[A[i] - 1] = 1; } } } // Encountering first 0, i.e, the element with least // value for (i = 0; i < l.Length; i++) { if (l[i] == 0) { return i + 1; } } // In case all values are filled between 1 and m return i + 2; } // Driver code public static void Main() { int[] A = { 0, 10, 2, -10, -20 }; Console.WriteLine(solution(A)); }} // This code is contributed by PrinciRaj1992 <?php// PHP Program to find the smallest// positive missing number function solution($A){//Our original array $m = max($A); //Storing maximum value if ($m < 1) { // In case all values in our array are negative return 1; } if (sizeof($A) == 1) { //If it contains only one element if ($A[0] == 1) return 2 ; else return 1 ; } $l = array_fill(0, $m, NULL); for($i = 0; $i < sizeof($A); $i++) { if( $A[$i] > 0) { if ($l[$A[$i] - 1] != 1) { //Changing the value status at the index of our list $l[$A[$i] - 1] = 1; } } } for ($i = 0;$i < sizeof($l); $i++) { //Encountering first 0, i.e, the element with least value if ($l[$i] == 0) return $i+1; } //In case all values are filled between 1 and m return $i+2; } // Driver Code$A = array(0, 10, 2, -10, -20);echo solution($A);return 0;?> <script>// Javascript Program to find the smallest// positive missing number function solution(A) { let n = A.length; // To mark the occurrence of elements let present = new Array(n+1); for(let i=0;i<n+1;i++) { present[i]=false; } // Mark the occurrences for (let i = 0; i < n; i++) { // Only mark the required elements // All non-positive elements and // the elements greater n + 1 will never // be the answer // For example, the array will be {1, 2, 3} // in the worst case and the result // will be 4 which is n + 1 if (A[i] > 0 && A[i] <= n) { present[A[i]] = true; } } // Find the first element which didn't // appear in the original array for (let i = 1; i <= n; i++) { if (!present[i]) { return i; } } // If the original array was of the // type {1, 2, 3} in its sorted form return n + 1; } // Driver Code let A=[0, 10, 2, -10, -20] document.write(solution(A)); </script> 1 Another Approach: The smallest positive integer is 1. First we will check if 1 is present in the array or not. If it is not present then 1 is the answer. If present then, again traverse the array. The largest possible answer is N+1 where N is the size of array. This will happen when array have all the elements from 1 to N. When we are traversing the array, if we find any number less than 1 or greater than N, then we will change it to 1. This will not change anything as answer will always between 1 to N+1. Now our array has elements from 1 to N. Now, for every ith number, increase arr[ (arr[i]-1) ] by N. But this will increase the value more than N. So, we will access the array by arr[(arr[i]-1)%N]. What we have done is for each value we have increased value at that index by N. We will find now which index has value less than N+1. Then i+1 will be our answer. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function for finding the first missing positive number int firstMissingPositive(int arr[], int n){ int ptr = 0; // Check if 1 is present in array or not for (int i = 0; i < n; i++) { if (arr[i] == 1) { ptr = 1; break; } } // If 1 is not present if (ptr == 0) return 1; // Changing values to 1 for (int i = 0; i < n; i++) if (arr[i] <= 0 || arr[i] > n) arr[i] = 1; // Updating indices according to values for (int i = 0; i < n; i++) arr[(arr[i] - 1) % n] += n; // Finding which index has value less than n for (int i = 0; i < n; i++) if (arr[i] <= n) return i + 1; // If array has values from 1 to n return n + 1;} // Driver codeint main(){ int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); int ans = firstMissingPositive(arr, n); cout << ans; return 0;} // C program for the above approach#include <stdio.h>#include <stdlib.h> // Function for finding the first// missing positive numberint firstMissingPositive(int arr[], int n){ int ptr = 0; // Check if 1 is present in array or not for(int i = 0; i < n; i++) { if (arr[i] == 1) { ptr = 1; break; } } // If 1 is not present if (ptr == 0) return 1; // Changing values to 1 for(int i = 0; i < n; i++) if (arr[i] <= 0 || arr[i] > n) arr[i] = 1; // Updating indices according to values for(int i = 0; i < n; i++) arr[(arr[i] - 1) % n] += n; // Finding which index has value less than n for(int i = 0; i < n; i++) if (arr[i] <= n) return i + 1; // If array has values from 1 to n return n + 1;} // Driver codeint main(){ int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); int ans = firstMissingPositive(arr, n); printf("%d", ans); return 0;} // This code is contributed by shailjapriya // Java program for the above approachimport java.util.Arrays; class GFG{ // Function for finding the first// missing positive numberstatic int firstMissingPositive(int arr[], int n){ int ptr = 0; // Check if 1 is present in array or not for(int i = 0; i < n; i++) { if (arr[i] == 1) { ptr = 1; break; } } // If 1 is not present if (ptr == 0) return (1); // Changing values to 1 for(int i = 0; i < n; i++) if (arr[i] <= 0 || arr[i] > n) arr[i] = 1; // Updating indices according to values for(int i = 0; i < n; i++) arr[(arr[i] - 1) % n] += n; // Finding which index has value less than n for(int i = 0; i < n; i++) if (arr[i] <= n) return (i + 1); // If array has values from 1 to n return (n + 1);} // Driver Codepublic static void main(String[] args){ int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }; int n = arr.length; int ans = firstMissingPositive(arr, n); System.out.println(ans);}} // This code is contributed by shailjapriya # Python3 program for the above approach # Function for finding the first missing# positive numberdef firstMissingPositive(arr, n): ptr = 0 # Check if 1 is present in array or not for i in range(n): if arr[i] == 1: ptr = 1 break # If 1 is not present if ptr == 0: return(1) # Changing values to 1 for i in range(n): if arr[i] <= 0 or arr[i] > n: arr[i] = 1 # Updating indices according to values for i in range(n): arr[(arr[i] - 1) % n] += n # Finding which index has value less than n for i in range(n): if arr[i] <= n: return(i + 1) # If array has values from 1 to n return(n + 1) # Driver Code # Given arrayA = [ 2, 3, -7, 6, 8, 1, -10, 15 ] # Size of the arrayN = len(A) # Function callprint(firstMissingPositive(A, N)) # This code is contributed by shailjapriya // C# program for the above approachusing System;using System.Linq; class GFG{ // Function for finding the first missing// positive number static int firstMissingPositive(int[] arr, int n){ int ptr = 0; // Check if 1 is present in array or not for(int i = 0; i < n; i++) { if (arr[i] == 1) { ptr = 1; break; } } // If 1 is not present if (ptr == 0) return 1; // Changing values to 1 for(int i = 0; i < n; i++) if (arr[i] <= 0 || arr[i] > n) arr[i] = 1; // Updating indices according to values for(int i = 0; i < n; i++) arr[(arr[i] - 1) % n] += n; // Finding which index has value less than n for(int i = 0; i < n; i++) if (arr[i] <= n) return i + 1; // If array has values from 1 to n return n + 1;} // Driver codepublic static void Main(){ int[] A = { 2, 3, -7, 6, 8, 1, -10, 15 }; int n = A.Length; int ans = firstMissingPositive(A, n); Console.WriteLine(ans);}} // This code is contributed by shailjapriya <script> // Javascript program for the above approach // Function for finding the first// missing positive numberfunction firstMissingPositive(arr, n){ let ptr = 0; // Check if 1 is present in array or not for(let i = 0; i < n; i++) { if (arr[i] == 1) { ptr = 1; break; } } // If 1 is not present if (ptr == 0) return 1; // Changing values to 1 for(let i = 0; i < n; i++) if (arr[i] <= 0 || arr[i] > n) arr[i] = 1; // Updating indices according to values for(let i = 0; i < n; i++) arr[(arr[i] - 1) % n] += n; // Finding which index has value less than n for(let i = 0; i < n; i++) if (arr[i] <= n) return i + 1; // If array has values from 1 to n return n + 1;} // Driver codelet arr = [ 2, 3, -7, 6, 8, 1, -10, 15 ];let n = arr.length;let ans = firstMissingPositive(arr, n); document.write(ans); // This code is contributed by telimayur </script> Output: 4 Time Complexity : O(n)Space Complexity : O(1) Another Approach: Traverse the array, Ignore the elements which are greater than n and less than 1.While traversing check a[i]!=a[a[i]-1] if this condition hold true or not .If the above condition is true then swap a[i], a[a[i] – 1] && swap until a[i] != a[a[i] – 1] condition will fail .Traverse the array and check whether a[i] != i + 1 then return i + 1.If all are equal to its index then return n+1. Traverse the array, Ignore the elements which are greater than n and less than 1. While traversing check a[i]!=a[a[i]-1] if this condition hold true or not . If the above condition is true then swap a[i], a[a[i] – 1] && swap until a[i] != a[a[i] – 1] condition will fail . Traverse the array and check whether a[i] != i + 1 then return i + 1. If all are equal to its index then return n+1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function for finding the first// missing positive numberint firstMissingPositive(int arr[], int n){ // Loop to traverse the whole array for (int i = 0; i < n; i++) { // Loop to check boundary // condition and for swapping while (arr[i] >= 1 && arr[i] <= n && arr[i] != arr[arr[i] - 1]) { swap(arr[i], arr[arr[i] - 1]); } } // Checking any element which // is not equal to i+1 for (int i = 0; i < n; i++) { if (arr[i] != i + 1) { return i + 1; } } // Nothing is present return last index return n + 1;} // Driver codeint main(){ int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); int ans = firstMissingPositive(arr, n); cout << ans; return 0;}// This code is contributed by Harsh kedia // Java program for the above approachimport java.util.Arrays; class GFG{ // Function for finding the first// missing positive numberstatic int firstMissingPositive(int arr[], int n){ // Check if 1 is present in array or not for(int i = 0; i < n; i++) { // Loop to check boundary // condition and for swapping while (arr[i] >= 1 && arr[i] <= n && arr[i] != arr[arr[i] - 1]) { int temp=arr[arr[i]-1]; arr[arr[i]-1]=arr[i]; arr[i]=temp; } } // Finding which index has value less than n for(int i = 0; i < n; i++) if (arr[i] != i + 1) return (i + 1); // If array has values from 1 to n return (n + 1);} // Driver Codepublic static void main(String[] args){ int arr[] = {2, 3, -7, 6, 8, 1, -10, 15 }; int n = arr.length; int ans = firstMissingPositive(arr, n); System.out.println(ans);}} // This code is contributed by mohit kumar 29. # Python program for the above approach# Function for finding the first# missing positive numberdef firstMissingPositive(arr, n): # Loop to traverse the whole array for i in range(n): # Loop to check boundary # condition and for swapping while (arr[i] >= 1 and arr[i] <= n and arr[i] != arr[arr[i] - 1]): temp = arr[i] arr[i] = arr[arr[i] - 1] arr[temp - 1] = temp # Checking any element which # is not equal to i+1 for i in range(n): if (arr[i] != i + 1): return i + 1 # Nothing is present return last index return n + 1 # Driver codearr = [ 2, 3, -7, 6, 8, 1, -10, 15 ];n = len(arr)ans = firstMissingPositive(arr, n)print(ans) # This code is contributed by shivanisinghss2110 // C# program for the above approachusing System;public class GFG{ // Function for finding the first // missing positive number static int firstMissingPositive(int[] arr, int n) { // Check if 1 is present in array or not for(int i = 0; i < n; i++) { // Loop to check boundary // condition and for swapping while (arr[i] >= 1 && arr[i] <= n && arr[i] != arr[arr[i] - 1]) { int temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; } } // Finding which index has value less than n for(int i = 0; i < n; i++) if (arr[i] != i + 1) return (i + 1); // If array has values from 1 to n return (n + 1); } // Driver Code static public void Main () { int[] arr = {2, 3, -7, 6, 8, 1, -10, 15 }; int n = arr.Length; int ans = firstMissingPositive(arr, n); Console.WriteLine(ans); }} // This code is contributed by ab2127 <script>// Javascript program for the above approach // Function for finding the first// missing positive numberfunction firstMissingPositive(arr,n){ // Check if 1 is present in array or not for(let i = 0; i < n; i++) { // Loop to check boundary // condition and for swapping while (arr[i] >= 1 && arr[i] <= n && arr[i] != arr[arr[i] - 1]) { let temp=arr[arr[i]-1]; arr[arr[i]-1]=arr[i]; arr[i]=temp; } } // Finding which index has value less than n for(let i = 0; i < n; i++) if (arr[i] != i + 1) return (i + 1); // If array has values from 1 to n return (n + 1);} // Driver Codelet arr=[2, 3, -7, 6, 8, 1, -10, 15 ];let n = arr.length;let ans = firstMissingPositive(arr, n);document.write(ans); // This code is contributed by patel2127</script> 4 Another simple approach with small and crisp code. Intuition: As we have to calculate the first missing positive integer,and the smallest positive integer is 1. So, take ans=1 and iterate over the array once and check whether nums[i]==ans (means we are checking for value from 1 upto missing number). By iterating if that condition meet where nums[i]==ans then increment ans by 1 and again check for the same condition uptill size of the array. After one scan of array we got the missing number stored in ans variable. Now return that ans to the function as return type in int. Code implementation of above intuition is as below: C++ Java Python3 Javascript #include <bits/stdc++.h>using namespace std;int firstMissingPositive(vector<int>& nums) {sort(nums.begin(),nums.end());int ans=1;for(int i=0;i<nums.size();i++){if(nums[i]==ans)ans++;}return ans;}int main() {vector<int>arr={-1,0,8,1};cout << firstMissingPositive(arr);return 0;} /*package whatever //do not write package name here */import java.io.*;import java.util.Arrays;class GFG {public static int firstMissingPositive(int[] nums,int n){Arrays.sort(nums);int ans = 1;for (int i = 0; i < n; i++) {if (nums[i] == ans)ans++;}return ans;}public static void main(String[] args){int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };int n = arr.length;int ans = firstMissingPositive(arr, n);System.out.println(ans);}} # Python code for the same approachfrom functools import cmp_to_key def cmp(a, b): return (a - b) def firstMissingPositive(nums): nums.sort(key = cmp_to_key(cmp)) ans = 1 for i in range(len(nums)): if(nums[i] == ans): ans += 1 return ans # driver codearr = [-1, 0, 8, 1]print(firstMissingPositive(arr)) # This code is contributed by shinjanpatra <script> function firstMissingPositive(nums){ nums.sort((a,b)=>a-b); let ans = 1; for(let i = 0; i < nums.length; i++) { if(nums[i] == ans) ans++; } return ans;} // driver codelet arr = [-1,0,8,1];document.write(firstMissingPositive(arr)); // This code is contributed by shinjanpatra </script> 2 Time Complexity: O(n*log(n)) Space Complexity: O(1) https://www.youtube.com/watch?v=_OAFHDVihjoPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. pradhanaman2595 ukasp 29AjayKumar princiraj1992 rathbhupendra gp6 SHUBHAMSINGH10 mesaam17 single__loop shailjapriya harsh2608 avanitrachhadiya2155 telimayur mohit kumar 29 sudhanshublaze rag2127 patel2127 ab2127 arorakashish0911 surindertarika1234 shivanisinghss2110 pravinyakumbhare akshitsaxenaa09 rajatsinghk4 shinjanpatra simmytarika5 aravasaiteja nikhatkhan11 sumitgumber28 Accolite Amazon FactSet Samsung Snapdeal Arrays Accolite Amazon Samsung Snapdeal FactSet Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Linear Search Multidimensional Arrays in Java Maximum and minimum of an array using minimum number of comparisons Python | Using 2D arrays/lists the right way Queue | Set 1 (Introduction and Array Implementation) Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
[ { "code": null, "e": 25372, "s": 25344, "text": "\n11 Apr, 2022" }, { "code": null, "e": 25591, "s": 25372, "text": "You are given an unsorted array with both positive and negative elements. You have to find the smallest positive number missing from the array in O(n) time using constant extra space. You can modify the original array." }, { "code": null, "e": 25601, "s": 25591, "text": "Examples " }, { "code": null, "e": 25740, "s": 25601, "text": " Input: {2, 3, 7, 6, 8, -1, -10, 15}\n Output: 1\n\n Input: { 2, 3, -7, 6, 8, 1, -10, 15 }\n Output: 4\n\n Input: {1, 1, 0, -1, -2}\n Output: 2" }, { "code": null, "e": 25956, "s": 25740, "text": "A naive method to solve this problem is to search all positive integers, starting from 1 in the given array. We may have to search at most n+1 numbers in the given array. So this solution takes O(n^2) in worst case." }, { "code": null, "e": 26194, "s": 25956, "text": "We can use sorting to solve it in lesser time complexity. We can sort the array in O(nLogn) time. Once the array is sorted, then all we need to do is a linear scan of the array. So this approach takes O(nLogn + n) time which is O(nLogn)." }, { "code": null, "e": 26549, "s": 26194, "text": "We can also use hashing. We can build a hash table of all positive elements in the given array. Once the hash table is built. We can look in the hash table for all positive integers, starting from 1. As soon as we find a number which is not there in hash table, we return it. This approach may take O(n) time on average, but it requires O(n) extra space." }, { "code": null, "e": 26908, "s": 26549, "text": "A O(n) time and O(1) extra space solution: The idea is similar to this post. We use array elements as index. To mark presence of an element x, we change the value at the index x to negative. But this approach doesn’t work if there are non-positive (-ve and 0) numbers. So we segregate positive from negative numbers as first step and then apply the approach." }, { "code": null, "e": 27610, "s": 26908, "text": "Following is the two step algorithm. 1) Segregate positive numbers from others i.e., move all non-positive numbers to left side. In the following code, segregate() function does this part. 2) Now we can ignore non-positive elements and consider only the part of array which contains all positive elements. We traverse the array containing all positive numbers and to mark presence of an element x, we change the sign of value at index x to negative. We traverse the array again and print the first index which has positive value. In the following code, findMissingPositive() function does this part. Note that in findMissingPositive, we have subtracted 1 from the values as indexes start from 0 in C. " }, { "code": null, "e": 27614, "s": 27610, "text": "C++" }, { "code": null, "e": 27616, "s": 27614, "text": "C" }, { "code": null, "e": 27621, "s": 27616, "text": "Java" }, { "code": null, "e": 27629, "s": 27621, "text": "Python3" }, { "code": null, "e": 27632, "s": 27629, "text": "C#" }, { "code": null, "e": 27643, "s": 27632, "text": "Javascript" }, { "code": "/* C++ program to find the smallest positive missing number */#include <bits/stdc++.h>using namespace std; /* Utility to swap to integers */void swap(int* a, int* b){ int temp; temp = *a; *a = *b; *b = temp;} /* Utility function that puts allnon-positive (0 and negative) numbers on leftside of arr[] and return count of such numbers */int segregate(int arr[], int size){ int j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { swap(&arr[i], &arr[j]); // increment count of // non-positive integers j++; } } return j;} /* Find the smallest positive missing numberin an array that contains all positive integers */int findMissingPositive(int arr[], int size){ int i; // Mark arr[i] as visited by // making arr[arr[i] - 1] negative. // Note that 1 is subtracted // because index start // from 0 and positive numbers start from 1 for (i = 0; i < size; i++) { if (abs(arr[i]) - 1 < size && arr[abs(arr[i]) - 1] > 0) arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]; } // Return the first index // value at which is positive for (i = 0; i < size; i++) if (arr[i] > 0) // 1 is added because // indexes start from 0 return i + 1; return size + 1;} /* Find the smallest positive missingnumber in an array that containsboth positive and negative integers */int findMissing(int arr[], int size){ // First separate positive // and negative numbers int shift = segregate(arr, size); // Shift the array and call // findMissingPositive for // positive part return findMissingPositive(arr + shift, size - shift);} // Driver codeint main(){ int arr[] = { 0, 10, 2, -10, -20 }; int arr_size = sizeof(arr) / sizeof(arr[0]); int missing = findMissing(arr, arr_size); cout << \"The smallest positive missing number is \" << missing; return 0;} // This is code is contributed by rathbhupendra", "e": 29691, "s": 27643, "text": null }, { "code": "/* C program to find the smallest positive missing number */#include <stdio.h>#include <stdlib.h> /* Utility to swap to integers */void swap(int* a, int* b){ int temp; temp = *a; *a = *b; *b = temp;} /* Utility function that puts allnon-positive (0 and negative) numbers on leftside of arr[] and return count of such numbers */int segregate(int arr[], int size){ int j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { swap(&arr[i], &arr[j]); j++; // increment count of non-positive integers } } return j;} /* Find the smallest positive missing numberin an array that contains all positive integers */int findMissingPositive(int arr[], int size){ int i; // Mark arr[i] as visited by // making arr[arr[i] - 1] negative. // Note that 1 is subtracted // because index start // from 0 and positive numbers start from 1 for (i = 0; i < size; i++) { if (abs(arr[i]) - 1 < size && arr[abs(arr[i]) - 1] > 0) arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]; } // Return the first index value at which is positive for (i = 0; i < size; i++) if (arr[i] > 0) // 1 is added because indexes start from 0 return i + 1; return size + 1;} /* Find the smallest positive missingnumber in an array that containsboth positive and negative integers */int findMissing(int arr[], int size){ // First separate positive and negative numbers int shift = segregate(arr, size); // Shift the array and call findMissingPositive for // positive part return findMissingPositive(arr + shift, size - shift);} // Driver codeint main(){ int arr[] = { 0, 10, 2, -10, -20 }; int arr_size = sizeof(arr) / sizeof(arr[0]); int missing = findMissing(arr, arr_size); printf(\"The smallest positive missing number is %d \", missing); getchar(); return 0;}", "e": 31583, "s": 29691, "text": null }, { "code": "// Java program to find the smallest// positive missing numberimport java.util.*; class Main { /* Utility function that puts all non-positive (0 and negative) numbers on left side of arr[] and return count of such numbers */ static int segregate(int arr[], int size) { int j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { int temp; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // increment count of non-positive // integers j++; } } return j; } /* Find the smallest positive missing number in an array that contains all positive integers */ static int findMissingPositive(int arr[], int size) { int i; // Mark arr[i] as visited by making // arr[arr[i] - 1] negative. Note that // 1 is subtracted because index start // from 0 and positive numbers start from 1 for (i = 0; i < size; i++) { int x = Math.abs(arr[i]); if (x - 1 < size && arr[x - 1] > 0) arr[x - 1] = -arr[x - 1]; } // Return the first index value at which // is positive for (i = 0; i < size; i++) if (arr[i] > 0) return i + 1; // 1 is added because indexes // start from 0 return size + 1; } /* Find the smallest positive missing number in an array that contains both positive and negative integers */ static int findMissing(int arr[], int size) { // First separate positive and // negative numbers int shift = segregate(arr, size); int arr2[] = new int[size - shift]; int j = 0; for (int i = shift; i < size; i++) { arr2[j] = arr[i]; j++; } // Shift the array and call // findMissingPositive for // positive part return findMissingPositive(arr2, j); } // Driver code public static void main(String[] args) { int arr[] = { 0, 10, 2, -10, -20 }; int arr_size = arr.length; int missing = findMissing(arr, arr_size); System.out.println(\"The smallest positive missing number is \" + missing); }}", "e": 33875, "s": 31583, "text": null }, { "code": "''' Python3 program to find thesmallest positive missing number ''' ''' Utility function that puts allnon-positive (0 and negative) numbers on leftside of arr[] and return count of such numbers '''def segregate(arr, size): j = 0 for i in range(size): if (arr[i] <= 0): arr[i], arr[j] = arr[j], arr[i] j += 1 # increment count of non-positive integers return j ''' Find the smallest positive missing numberin an array that contains all positive integers '''def findMissingPositive(arr, size): # Mark arr[i] as visited by # making arr[arr[i] - 1] negative. # Note that 1 is subtracted # because index start # from 0 and positive numbers start from 1 for i in range(size): if (abs(arr[i]) - 1 < size and arr[abs(arr[i]) - 1] > 0): arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1] # Return the first index value at which is positive for i in range(size): if (arr[i] > 0): # 1 is added because indexes start from 0 return i + 1 return size + 1 ''' Find the smallest positive missingnumber in an array that containsboth positive and negative integers '''def findMissing(arr, size): # First separate positive and negative numbers shift = segregate(arr, size) # Shift the array and call findMissingPositive for # positive part return findMissingPositive(arr[shift:], size - shift) # Driver codearr = [ 0, 10, 2, -10, -20 ]arr_size = len(arr)missing = findMissing(arr, arr_size)print(\"The smallest positive missing number is \", missing) # This code is contributed by Shubhamsingh10", "e": 35517, "s": 33875, "text": null }, { "code": "// C# program to find the smallest// positive missing numberusing System; class main { // Utility function that puts all // non-positive (0 and negative) // numbers on left side of arr[] // and return count of such numbers static int segregate(int[] arr, int size) { int j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { int temp; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // increment count of non-positive // integers j++; } } return j; } // Find the smallest positive missing // number in an array that contains // all positive integers static int findMissingPositive(int[] arr, int size) { int i; // Mark arr[i] as visited by making // arr[arr[i] - 1] negative. Note that // 1 is subtracted as index start from // 0 and positive numbers start from 1 for (i = 0; i < size; i++) { if (Math.Abs(arr[i]) - 1 < size && arr[ Math.Abs(arr[i]) - 1] > 0) arr[ Math.Abs(arr[i]) - 1] = -arr[ Math.Abs(arr[i]) - 1]; } // Return the first index value at // which is positive for (i = 0; i < size; i++) if (arr[i] > 0) return i + 1; // 1 is added because indexes // start from 0 return size + 1; } // Find the smallest positive // missing number in array that // contains both positive and // negative integers static int findMissing(int[] arr, int size) { // First separate positive and // negative numbers int shift = segregate(arr, size); int[] arr2 = new int[size - shift]; int j = 0; for (int i = shift; i < size; i++) { arr2[j] = arr[i]; j++; } // Shift the array and call // findMissingPositive for // positive part return findMissingPositive(arr2, j); } // Driver code public static void Main() { int[] arr = { 0, 10, 2, -10, -20 }; int arr_size = arr.Length; int missing = findMissing(arr, arr_size); Console.WriteLine(\"The smallest positive missing number is \" + missing); }} // This code is contributed by Anant Agarwal.", "e": 37861, "s": 35517, "text": null }, { "code": "<script>// Javascript program to find the smallest// positive missing number /* Utility function that puts all non-positive (0 and negative) numbers on left side of arr[] and return count of such numbers */function segregate(arr,size){ let j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { let temp; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // increment count of non-positive // integers j++; } } return j;} /* Find the smallest positive missing number in an array that contains all positive integers */function findMissingPositive(arr,size){ let i; // Mark arr[i] as visited by making // arr[arr[i] - 1] negative. Note that // 1 is subtracted because index start // from 0 and positive numbers start from 1 for (i = 0; i < size; i++) { let x = Math.abs(arr[i]); if (x - 1 < size && arr[x - 1] > 0) arr[x - 1] = -arr[x - 1]; } // Return the first index value at which // is positive for (i = 0; i < size; i++) if (arr[i] > 0) return i + 1; // 1 is added because indexes // start from 0 return size + 1;} /* Find the smallest positive missing number in an array that contains both positive and negative integers */function findMissing(arr,size){ // First separate positive and // negative numbers let shift = segregate(arr, size); let arr2 = new Array(size - shift); let j = 0; for (let i = shift; i < size; i++) { arr2[j] = arr[i]; j++; } // Shift the array and call // findMissingPositive for // positive part return findMissingPositive(arr2, j);} // Driver codelet arr = [0, 10, 2, -10, -20];let arr_size = arr.length;let missing = findMissing(arr, arr_size);document.write(\"The smallest positive missing number is \" + missing); // This code is contributed by rag2127</script>", "e": 40001, "s": 37861, "text": null }, { "code": null, "e": 40043, "s": 40001, "text": "The smallest positive missing number is 1" }, { "code": null, "e": 40362, "s": 40043, "text": "Note that this method modifies the original array. We can change the sign of elements in the segregated array to get the same set of elements back. But we still loose the order of elements. If we want to keep the original array as it was, then we can create a copy of the array and run this approach on the temp array." }, { "code": null, "e": 40768, "s": 40362, "text": "Another approach: In this problem, we have created a list full of 0’s with size of the max() value of our given array. Now, whenever we encounter any positive value in our original array, we change the index value of our list to 1. So, after we are done, we simply iterate through our modified list, the first 0 we encounter, its (index value + 1) should be our answer since index in python starts from 0." }, { "code": null, "e": 40816, "s": 40768, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 40820, "s": 40816, "text": "C++" }, { "code": null, "e": 40825, "s": 40820, "text": "Java" }, { "code": null, "e": 40833, "s": 40825, "text": "Python3" }, { "code": null, "e": 40836, "s": 40833, "text": "C#" }, { "code": null, "e": 40840, "s": 40836, "text": "PHP" }, { "code": null, "e": 40851, "s": 40840, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the first missing positive// number from the given unsorted arrayint firstMissingPos(int A[], int n){ // To mark the occurrence of elements bool present[n + 1] = { false }; // Mark the occurrences for (int i = 0; i < n; i++) { // Only mark the required elements // All non-positive elements and // the elements greater n + 1 will never // be the answer // For example, the array will be {1, 2, 3} // in the worst case and the result // will be 4 which is n + 1 if (A[i] > 0 && A[i] <= n) present[A[i]] = true; } // Find the first element which didn't // appear in the original array for (int i = 1; i <= n; i++) if (!present[i]) return i; // If the original array was of the // type {1, 2, 3} in its sorted form return n + 1;} // Driver codeint main(){ int A[] = { 0, 10, 2, -10, -20 }; int size = sizeof(A) / sizeof(A[0]); cout << firstMissingPos(A, size);} // This code is contributed by gp6", "e": 41982, "s": 40851, "text": null }, { "code": "// Java Program to find the smallest// positive missing numberimport java.util.*;public class GFG { static int solution(int[] A) { int n = A.length; //Let this 1e6 be the maximum element provided in the array; int N=1000010; // To mark the occurrence of elements boolean[] present = new boolean[N]; int maxele=Integer.MIN_VALUE; // Mark the occurrences for (int i = 0; i < n; i++) { // Only mark the required elements // All non-positive elements and // the elements greater n + 1 will never // be the answer // For example, the array will be {1, 2, 3} // in the worst case and the result // will be 4 which is n + 1 if (A[i] > 0 && A[i] <= n) present[A[i]] = true; //find the maximum element so that if all the elements are in order can directly return the next number maxele=Math.max(maxele,A[i]); } // Find the first element which didn't // appear in the original array for (int i = 1; i < N; i++) if (!present[i]) return i; // If the original array was of the // type {1, 2, 3} in its sorted form return maxele + 1; } // Driver Code public static void main(String[] args) { int A[] = { 0, 10, 2, -10, -20 }; System.out.println(solution(A)); int arr[]={-2,-1,0,1,2,3,4}; System.out.println(solution(arr)); }}// This code is contributed by Arava Sai Teja", "e": 43568, "s": 41982, "text": null }, { "code": "# Python3 Program to find the smallest# positive missing number def solution(A): # Our original array m = max(A) # Storing maximum value if m < 1: # In case all values in our array are negative return 1 if len(A) == 1: # If it contains only one element return 2 if A[0] == 1 else 1 l = [0] * m for i in range(len(A)): if A[i] > 0: if l[A[i] - 1] != 1: # Changing the value status at the index of our list l[A[i] - 1] = 1 for i in range(len(l)): # Encountering first 0, i.e, the element with least value if l[i] == 0: return i + 1 # In case all values are filled between 1 and m return i + 2 # Driver CodeA = [0, 10, 2, -10, -20]print(solution(A))", "e": 44356, "s": 43568, "text": null }, { "code": "// C# Program to find the smallest// positive missing numberusing System;using System.Linq; class GFG { static int solution(int[] A) { // Our original array int m = A.Max(); // Storing maximum value // In case all values in our array are negative if (m < 1) { return 1; } if (A.Length == 1) { // If it contains only one element if (A[0] == 1) { return 2; } else { return 1; } } int i = 0; int[] l = new int[m]; for (i = 0; i < A.Length; i++) { if (A[i] > 0) { // Changing the value status at the index of // our list if (l[A[i] - 1] != 1) { l[A[i] - 1] = 1; } } } // Encountering first 0, i.e, the element with least // value for (i = 0; i < l.Length; i++) { if (l[i] == 0) { return i + 1; } } // In case all values are filled between 1 and m return i + 2; } // Driver code public static void Main() { int[] A = { 0, 10, 2, -10, -20 }; Console.WriteLine(solution(A)); }} // This code is contributed by PrinciRaj1992", "e": 45666, "s": 44356, "text": null }, { "code": "<?php// PHP Program to find the smallest// positive missing number function solution($A){//Our original array $m = max($A); //Storing maximum value if ($m < 1) { // In case all values in our array are negative return 1; } if (sizeof($A) == 1) { //If it contains only one element if ($A[0] == 1) return 2 ; else return 1 ; } $l = array_fill(0, $m, NULL); for($i = 0; $i < sizeof($A); $i++) { if( $A[$i] > 0) { if ($l[$A[$i] - 1] != 1) { //Changing the value status at the index of our list $l[$A[$i] - 1] = 1; } } } for ($i = 0;$i < sizeof($l); $i++) { //Encountering first 0, i.e, the element with least value if ($l[$i] == 0) return $i+1; } //In case all values are filled between 1 and m return $i+2; } // Driver Code$A = array(0, 10, 2, -10, -20);echo solution($A);return 0;?>", "e": 46723, "s": 45666, "text": null }, { "code": "<script>// Javascript Program to find the smallest// positive missing number function solution(A) { let n = A.length; // To mark the occurrence of elements let present = new Array(n+1); for(let i=0;i<n+1;i++) { present[i]=false; } // Mark the occurrences for (let i = 0; i < n; i++) { // Only mark the required elements // All non-positive elements and // the elements greater n + 1 will never // be the answer // For example, the array will be {1, 2, 3} // in the worst case and the result // will be 4 which is n + 1 if (A[i] > 0 && A[i] <= n) { present[A[i]] = true; } } // Find the first element which didn't // appear in the original array for (let i = 1; i <= n; i++) { if (!present[i]) { return i; } } // If the original array was of the // type {1, 2, 3} in its sorted form return n + 1; } // Driver Code let A=[0, 10, 2, -10, -20] document.write(solution(A)); </script>", "e": 47959, "s": 46723, "text": null }, { "code": null, "e": 47961, "s": 47959, "text": "1" }, { "code": null, "e": 47979, "s": 47961, "text": "Another Approach:" }, { "code": null, "e": 48115, "s": 47979, "text": "The smallest positive integer is 1. First we will check if 1 is present in the array or not. If it is not present then 1 is the answer." }, { "code": null, "e": 48512, "s": 48115, "text": "If present then, again traverse the array. The largest possible answer is N+1 where N is the size of array. This will happen when array have all the elements from 1 to N. When we are traversing the array, if we find any number less than 1 or greater than N, then we will change it to 1. This will not change anything as answer will always between 1 to N+1. Now our array has elements from 1 to N." }, { "code": null, "e": 48749, "s": 48512, "text": "Now, for every ith number, increase arr[ (arr[i]-1) ] by N. But this will increase the value more than N. So, we will access the array by arr[(arr[i]-1)%N]. What we have done is for each value we have increased value at that index by N." }, { "code": null, "e": 48833, "s": 48749, "text": "We will find now which index has value less than N+1. Then i+1 will be our answer. " }, { "code": null, "e": 48884, "s": 48833, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 48888, "s": 48884, "text": "C++" }, { "code": null, "e": 48890, "s": 48888, "text": "C" }, { "code": null, "e": 48895, "s": 48890, "text": "Java" }, { "code": null, "e": 48903, "s": 48895, "text": "Python3" }, { "code": null, "e": 48906, "s": 48903, "text": "C#" }, { "code": null, "e": 48917, "s": 48906, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function for finding the first missing positive number int firstMissingPositive(int arr[], int n){ int ptr = 0; // Check if 1 is present in array or not for (int i = 0; i < n; i++) { if (arr[i] == 1) { ptr = 1; break; } } // If 1 is not present if (ptr == 0) return 1; // Changing values to 1 for (int i = 0; i < n; i++) if (arr[i] <= 0 || arr[i] > n) arr[i] = 1; // Updating indices according to values for (int i = 0; i < n; i++) arr[(arr[i] - 1) % n] += n; // Finding which index has value less than n for (int i = 0; i < n; i++) if (arr[i] <= n) return i + 1; // If array has values from 1 to n return n + 1;} // Driver codeint main(){ int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); int ans = firstMissingPositive(arr, n); cout << ans; return 0;}", "e": 49940, "s": 48917, "text": null }, { "code": "// C program for the above approach#include <stdio.h>#include <stdlib.h> // Function for finding the first// missing positive numberint firstMissingPositive(int arr[], int n){ int ptr = 0; // Check if 1 is present in array or not for(int i = 0; i < n; i++) { if (arr[i] == 1) { ptr = 1; break; } } // If 1 is not present if (ptr == 0) return 1; // Changing values to 1 for(int i = 0; i < n; i++) if (arr[i] <= 0 || arr[i] > n) arr[i] = 1; // Updating indices according to values for(int i = 0; i < n; i++) arr[(arr[i] - 1) % n] += n; // Finding which index has value less than n for(int i = 0; i < n; i++) if (arr[i] <= n) return i + 1; // If array has values from 1 to n return n + 1;} // Driver codeint main(){ int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); int ans = firstMissingPositive(arr, n); printf(\"%d\", ans); return 0;} // This code is contributed by shailjapriya", "e": 51018, "s": 49940, "text": null }, { "code": "// Java program for the above approachimport java.util.Arrays; class GFG{ // Function for finding the first// missing positive numberstatic int firstMissingPositive(int arr[], int n){ int ptr = 0; // Check if 1 is present in array or not for(int i = 0; i < n; i++) { if (arr[i] == 1) { ptr = 1; break; } } // If 1 is not present if (ptr == 0) return (1); // Changing values to 1 for(int i = 0; i < n; i++) if (arr[i] <= 0 || arr[i] > n) arr[i] = 1; // Updating indices according to values for(int i = 0; i < n; i++) arr[(arr[i] - 1) % n] += n; // Finding which index has value less than n for(int i = 0; i < n; i++) if (arr[i] <= n) return (i + 1); // If array has values from 1 to n return (n + 1);} // Driver Codepublic static void main(String[] args){ int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }; int n = arr.length; int ans = firstMissingPositive(arr, n); System.out.println(ans);}} // This code is contributed by shailjapriya", "e": 52109, "s": 51018, "text": null }, { "code": "# Python3 program for the above approach # Function for finding the first missing# positive numberdef firstMissingPositive(arr, n): ptr = 0 # Check if 1 is present in array or not for i in range(n): if arr[i] == 1: ptr = 1 break # If 1 is not present if ptr == 0: return(1) # Changing values to 1 for i in range(n): if arr[i] <= 0 or arr[i] > n: arr[i] = 1 # Updating indices according to values for i in range(n): arr[(arr[i] - 1) % n] += n # Finding which index has value less than n for i in range(n): if arr[i] <= n: return(i + 1) # If array has values from 1 to n return(n + 1) # Driver Code # Given arrayA = [ 2, 3, -7, 6, 8, 1, -10, 15 ] # Size of the arrayN = len(A) # Function callprint(firstMissingPositive(A, N)) # This code is contributed by shailjapriya", "e": 53045, "s": 52109, "text": null }, { "code": "// C# program for the above approachusing System;using System.Linq; class GFG{ // Function for finding the first missing// positive number static int firstMissingPositive(int[] arr, int n){ int ptr = 0; // Check if 1 is present in array or not for(int i = 0; i < n; i++) { if (arr[i] == 1) { ptr = 1; break; } } // If 1 is not present if (ptr == 0) return 1; // Changing values to 1 for(int i = 0; i < n; i++) if (arr[i] <= 0 || arr[i] > n) arr[i] = 1; // Updating indices according to values for(int i = 0; i < n; i++) arr[(arr[i] - 1) % n] += n; // Finding which index has value less than n for(int i = 0; i < n; i++) if (arr[i] <= n) return i + 1; // If array has values from 1 to n return n + 1;} // Driver codepublic static void Main(){ int[] A = { 2, 3, -7, 6, 8, 1, -10, 15 }; int n = A.Length; int ans = firstMissingPositive(A, n); Console.WriteLine(ans);}} // This code is contributed by shailjapriya", "e": 54135, "s": 53045, "text": null }, { "code": "<script> // Javascript program for the above approach // Function for finding the first// missing positive numberfunction firstMissingPositive(arr, n){ let ptr = 0; // Check if 1 is present in array or not for(let i = 0; i < n; i++) { if (arr[i] == 1) { ptr = 1; break; } } // If 1 is not present if (ptr == 0) return 1; // Changing values to 1 for(let i = 0; i < n; i++) if (arr[i] <= 0 || arr[i] > n) arr[i] = 1; // Updating indices according to values for(let i = 0; i < n; i++) arr[(arr[i] - 1) % n] += n; // Finding which index has value less than n for(let i = 0; i < n; i++) if (arr[i] <= n) return i + 1; // If array has values from 1 to n return n + 1;} // Driver codelet arr = [ 2, 3, -7, 6, 8, 1, -10, 15 ];let n = arr.length;let ans = firstMissingPositive(arr, n); document.write(ans); // This code is contributed by telimayur </script>", "e": 55132, "s": 54135, "text": null }, { "code": null, "e": 55140, "s": 55132, "text": "Output:" }, { "code": null, "e": 55142, "s": 55140, "text": "4" }, { "code": null, "e": 55190, "s": 55142, "text": "Time Complexity : O(n)Space Complexity : O(1) " }, { "code": null, "e": 55208, "s": 55190, "text": "Another Approach:" }, { "code": null, "e": 55597, "s": 55208, "text": "Traverse the array, Ignore the elements which are greater than n and less than 1.While traversing check a[i]!=a[a[i]-1] if this condition hold true or not .If the above condition is true then swap a[i], a[a[i] – 1] && swap until a[i] != a[a[i] – 1] condition will fail .Traverse the array and check whether a[i] != i + 1 then return i + 1.If all are equal to its index then return n+1. " }, { "code": null, "e": 55679, "s": 55597, "text": "Traverse the array, Ignore the elements which are greater than n and less than 1." }, { "code": null, "e": 55755, "s": 55679, "text": "While traversing check a[i]!=a[a[i]-1] if this condition hold true or not ." }, { "code": null, "e": 55872, "s": 55755, "text": "If the above condition is true then swap a[i], a[a[i] – 1] && swap until a[i] != a[a[i] – 1] condition will fail ." }, { "code": null, "e": 55942, "s": 55872, "text": "Traverse the array and check whether a[i] != i + 1 then return i + 1." }, { "code": null, "e": 55990, "s": 55942, "text": "If all are equal to its index then return n+1. " }, { "code": null, "e": 56041, "s": 55990, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 56045, "s": 56041, "text": "C++" }, { "code": null, "e": 56050, "s": 56045, "text": "Java" }, { "code": null, "e": 56058, "s": 56050, "text": "Python3" }, { "code": null, "e": 56061, "s": 56058, "text": "C#" }, { "code": null, "e": 56072, "s": 56061, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function for finding the first// missing positive numberint firstMissingPositive(int arr[], int n){ // Loop to traverse the whole array for (int i = 0; i < n; i++) { // Loop to check boundary // condition and for swapping while (arr[i] >= 1 && arr[i] <= n && arr[i] != arr[arr[i] - 1]) { swap(arr[i], arr[arr[i] - 1]); } } // Checking any element which // is not equal to i+1 for (int i = 0; i < n; i++) { if (arr[i] != i + 1) { return i + 1; } } // Nothing is present return last index return n + 1;} // Driver codeint main(){ int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); int ans = firstMissingPositive(arr, n); cout << ans; return 0;}// This code is contributed by Harsh kedia", "e": 57014, "s": 56072, "text": null }, { "code": "// Java program for the above approachimport java.util.Arrays; class GFG{ // Function for finding the first// missing positive numberstatic int firstMissingPositive(int arr[], int n){ // Check if 1 is present in array or not for(int i = 0; i < n; i++) { // Loop to check boundary // condition and for swapping while (arr[i] >= 1 && arr[i] <= n && arr[i] != arr[arr[i] - 1]) { int temp=arr[arr[i]-1]; arr[arr[i]-1]=arr[i]; arr[i]=temp; } } // Finding which index has value less than n for(int i = 0; i < n; i++) if (arr[i] != i + 1) return (i + 1); // If array has values from 1 to n return (n + 1);} // Driver Codepublic static void main(String[] args){ int arr[] = {2, 3, -7, 6, 8, 1, -10, 15 }; int n = arr.length; int ans = firstMissingPositive(arr, n); System.out.println(ans);}} // This code is contributed by mohit kumar 29.", "e": 57984, "s": 57014, "text": null }, { "code": "# Python program for the above approach# Function for finding the first# missing positive numberdef firstMissingPositive(arr, n): # Loop to traverse the whole array for i in range(n): # Loop to check boundary # condition and for swapping while (arr[i] >= 1 and arr[i] <= n and arr[i] != arr[arr[i] - 1]): temp = arr[i] arr[i] = arr[arr[i] - 1] arr[temp - 1] = temp # Checking any element which # is not equal to i+1 for i in range(n): if (arr[i] != i + 1): return i + 1 # Nothing is present return last index return n + 1 # Driver codearr = [ 2, 3, -7, 6, 8, 1, -10, 15 ];n = len(arr)ans = firstMissingPositive(arr, n)print(ans) # This code is contributed by shivanisinghss2110", "e": 58791, "s": 57984, "text": null }, { "code": "// C# program for the above approachusing System;public class GFG{ // Function for finding the first // missing positive number static int firstMissingPositive(int[] arr, int n) { // Check if 1 is present in array or not for(int i = 0; i < n; i++) { // Loop to check boundary // condition and for swapping while (arr[i] >= 1 && arr[i] <= n && arr[i] != arr[arr[i] - 1]) { int temp = arr[arr[i] - 1]; arr[arr[i] - 1] = arr[i]; arr[i] = temp; } } // Finding which index has value less than n for(int i = 0; i < n; i++) if (arr[i] != i + 1) return (i + 1); // If array has values from 1 to n return (n + 1); } // Driver Code static public void Main () { int[] arr = {2, 3, -7, 6, 8, 1, -10, 15 }; int n = arr.Length; int ans = firstMissingPositive(arr, n); Console.WriteLine(ans); }} // This code is contributed by ab2127", "e": 59730, "s": 58791, "text": null }, { "code": "<script>// Javascript program for the above approach // Function for finding the first// missing positive numberfunction firstMissingPositive(arr,n){ // Check if 1 is present in array or not for(let i = 0; i < n; i++) { // Loop to check boundary // condition and for swapping while (arr[i] >= 1 && arr[i] <= n && arr[i] != arr[arr[i] - 1]) { let temp=arr[arr[i]-1]; arr[arr[i]-1]=arr[i]; arr[i]=temp; } } // Finding which index has value less than n for(let i = 0; i < n; i++) if (arr[i] != i + 1) return (i + 1); // If array has values from 1 to n return (n + 1);} // Driver Codelet arr=[2, 3, -7, 6, 8, 1, -10, 15 ];let n = arr.length;let ans = firstMissingPositive(arr, n);document.write(ans); // This code is contributed by patel2127</script>", "e": 60638, "s": 59730, "text": null }, { "code": null, "e": 60640, "s": 60638, "text": "4" }, { "code": null, "e": 60692, "s": 60640, "text": "Another simple approach with small and crisp code. " }, { "code": null, "e": 60802, "s": 60692, "text": "Intuition: As we have to calculate the first missing positive integer,and the smallest positive integer is 1." }, { "code": null, "e": 60942, "s": 60802, "text": "So, take ans=1 and iterate over the array once and check whether nums[i]==ans (means we are checking for value from 1 upto missing number)." }, { "code": null, "e": 61086, "s": 60942, "text": "By iterating if that condition meet where nums[i]==ans then increment ans by 1 and again check for the same condition uptill size of the array." }, { "code": null, "e": 61160, "s": 61086, "text": "After one scan of array we got the missing number stored in ans variable." }, { "code": null, "e": 61219, "s": 61160, "text": "Now return that ans to the function as return type in int." }, { "code": null, "e": 61271, "s": 61219, "text": "Code implementation of above intuition is as below:" }, { "code": null, "e": 61275, "s": 61271, "text": "C++" }, { "code": null, "e": 61280, "s": 61275, "text": "Java" }, { "code": null, "e": 61288, "s": 61280, "text": "Python3" }, { "code": null, "e": 61299, "s": 61288, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std;int firstMissingPositive(vector<int>& nums) {sort(nums.begin(),nums.end());int ans=1;for(int i=0;i<nums.size();i++){if(nums[i]==ans)ans++;}return ans;}int main() {vector<int>arr={-1,0,8,1};cout << firstMissingPositive(arr);return 0;}", "e": 61577, "s": 61299, "text": null }, { "code": "/*package whatever //do not write package name here */import java.io.*;import java.util.Arrays;class GFG {public static int firstMissingPositive(int[] nums,int n){Arrays.sort(nums);int ans = 1;for (int i = 0; i < n; i++) {if (nums[i] == ans)ans++;}return ans;}public static void main(String[] args){int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };int n = arr.length;int ans = firstMissingPositive(arr, n);System.out.println(ans);}}", "e": 62004, "s": 61577, "text": null }, { "code": "# Python code for the same approachfrom functools import cmp_to_key def cmp(a, b): return (a - b) def firstMissingPositive(nums): nums.sort(key = cmp_to_key(cmp)) ans = 1 for i in range(len(nums)): if(nums[i] == ans): ans += 1 return ans # driver codearr = [-1, 0, 8, 1]print(firstMissingPositive(arr)) # This code is contributed by shinjanpatra", "e": 62390, "s": 62004, "text": null }, { "code": "<script> function firstMissingPositive(nums){ nums.sort((a,b)=>a-b); let ans = 1; for(let i = 0; i < nums.length; i++) { if(nums[i] == ans) ans++; } return ans;} // driver codelet arr = [-1,0,8,1];document.write(firstMissingPositive(arr)); // This code is contributed by shinjanpatra </script>", "e": 62720, "s": 62390, "text": null }, { "code": null, "e": 62722, "s": 62720, "text": "2" }, { "code": null, "e": 62751, "s": 62722, "text": "Time Complexity: O(n*log(n))" }, { "code": null, "e": 62775, "s": 62751, "text": "Space Complexity: O(1) " }, { "code": null, "e": 62943, "s": 62775, "text": "https://www.youtube.com/watch?v=_OAFHDVihjoPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 62959, "s": 62943, "text": "pradhanaman2595" }, { "code": null, "e": 62965, "s": 62959, "text": "ukasp" }, { "code": null, "e": 62977, "s": 62965, "text": "29AjayKumar" }, { "code": null, "e": 62991, "s": 62977, "text": "princiraj1992" }, { "code": null, "e": 63005, "s": 62991, "text": "rathbhupendra" }, { "code": null, "e": 63009, "s": 63005, "text": "gp6" }, { "code": null, "e": 63024, "s": 63009, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 63033, "s": 63024, "text": "mesaam17" }, { "code": null, "e": 63046, "s": 63033, "text": "single__loop" }, { "code": null, "e": 63059, "s": 63046, "text": "shailjapriya" }, { "code": null, "e": 63069, "s": 63059, "text": "harsh2608" }, { "code": null, "e": 63090, "s": 63069, "text": "avanitrachhadiya2155" }, { "code": null, "e": 63100, "s": 63090, "text": "telimayur" }, { "code": null, "e": 63115, "s": 63100, "text": "mohit kumar 29" }, { "code": null, "e": 63130, "s": 63115, "text": "sudhanshublaze" }, { "code": null, "e": 63138, "s": 63130, "text": "rag2127" }, { "code": null, "e": 63148, "s": 63138, "text": "patel2127" }, { "code": null, "e": 63155, "s": 63148, "text": "ab2127" }, { "code": null, "e": 63172, "s": 63155, "text": "arorakashish0911" }, { "code": null, "e": 63191, "s": 63172, "text": "surindertarika1234" }, { "code": null, "e": 63210, "s": 63191, "text": "shivanisinghss2110" }, { "code": null, "e": 63227, "s": 63210, "text": "pravinyakumbhare" }, { "code": null, "e": 63243, "s": 63227, "text": "akshitsaxenaa09" }, { "code": null, "e": 63256, "s": 63243, "text": "rajatsinghk4" }, { "code": null, "e": 63269, "s": 63256, "text": "shinjanpatra" }, { "code": null, "e": 63282, "s": 63269, "text": "simmytarika5" }, { "code": null, "e": 63295, "s": 63282, "text": "aravasaiteja" }, { "code": null, "e": 63308, "s": 63295, "text": "nikhatkhan11" }, { "code": null, "e": 63322, "s": 63308, "text": "sumitgumber28" }, { "code": null, "e": 63331, "s": 63322, "text": "Accolite" }, { "code": null, "e": 63338, "s": 63331, "text": "Amazon" }, { "code": null, "e": 63346, "s": 63338, "text": "FactSet" }, { "code": null, "e": 63354, "s": 63346, "text": "Samsung" }, { "code": null, "e": 63363, "s": 63354, "text": "Snapdeal" }, { "code": null, "e": 63370, "s": 63363, "text": "Arrays" }, { "code": null, "e": 63379, "s": 63370, "text": "Accolite" }, { "code": null, "e": 63386, "s": 63379, "text": "Amazon" }, { "code": null, "e": 63394, "s": 63386, "text": "Samsung" }, { "code": null, "e": 63403, "s": 63394, "text": "Snapdeal" }, { "code": null, "e": 63411, "s": 63403, "text": "FactSet" }, { "code": null, "e": 63418, "s": 63411, "text": "Arrays" }, { "code": null, "e": 63516, "s": 63418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 63525, "s": 63516, "text": "Comments" }, { "code": null, "e": 63538, "s": 63525, "text": "Old Comments" }, { "code": null, "e": 63586, "s": 63538, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 63630, "s": 63586, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 63653, "s": 63630, "text": "Introduction to Arrays" }, { "code": null, "e": 63667, "s": 63653, "text": "Linear Search" }, { "code": null, "e": 63699, "s": 63667, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 63767, "s": 63699, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 63812, "s": 63767, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 63866, "s": 63812, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 63887, "s": 63866, "text": "Linked List vs Array" } ]
Ionic - Cards
Since mobile devices have smaller screen size, cards are one of the best elements for displaying information that will feel user friendly. In the previous chapter, we have discussed how to inset lists. Cards are very similar to inset lists, but they offer some additional shadowing that can influence the performance for larger lists. A default card can be created by adding a card class to your element. Cards are usually formed as lists with the item class. One of the most useful class is the item-text-wrap. This will help when you have too much text, so you want to wrap it inside your card. The first card in the following example does not have the item-text-wrap class assigned, but the second one is using it. <div class = "card"> <div class = "item"> This is a Ionic card without item-text-wrap class. </div> <div class = "item item-text-wrap"> This is a Ionic card with item-text-wrap class. </div> </div> The above code will produce the following screen − In the previous chapter, we have already discussed how to use the item-divider class for grouping lists. This class can be very useful when working with cards to create card headers. The same class can be used for footers as shown in the following code − <div class = "card list"> <div class = "item item-divider"> Card header </div> <div class = "item item-text-wrap"> Card text... </div> <div class = "item item-divider"> Card Footer </div> </div> The above code will produce the following screen − You can add any element on top of your card. In following example, we will show you how to use the full-image class together with the item-body to get a good-looking windowed image inside your card. <div class = "card"> <div class = "item item-avatar"> <img src = "my-image.png"> <h2>Card Name</h2> </div> <div class = "item item-body"> <img class = "full-image" src = "my-image.png"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eget pharetra tortor. Proin quis eros imperdiet, facilisis nisi in, tincidunt orci. Nam tristique elit massa, quis faucibus augue finibus ac. </div> </div> The above code will produce the following screen − 16 Lectures 2.5 hours Frahaan Hussain 185 Lectures 46.5 hours Nikhil Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2798, "s": 2463, "text": "Since mobile devices have smaller screen size, cards are one of the best elements for displaying information that will feel user friendly. In the previous chapter, we have discussed how to inset lists. Cards are very similar to inset lists, but they offer some additional shadowing that can influence the performance for larger lists." }, { "code": null, "e": 3181, "s": 2798, "text": "A default card can be created by adding a card class to your element. Cards are usually formed as lists with the item class. One of the most useful class is the item-text-wrap. This will help when you have too much text, so you want to wrap it inside your card. The first card in the following example does not have the item-text-wrap class assigned, but the second one is using it." }, { "code": null, "e": 3407, "s": 3181, "text": "<div class = \"card\">\n <div class = \"item\">\n This is a Ionic card without item-text-wrap class.\n </div>\n \n <div class = \"item item-text-wrap\">\n This is a Ionic card with item-text-wrap class.\n </div>\n</div>" }, { "code": null, "e": 3458, "s": 3407, "text": "The above code will produce the following screen −" }, { "code": null, "e": 3713, "s": 3458, "text": "In the previous chapter, we have already discussed how to use the item-divider class for grouping lists. This class can be very useful when working with cards to create card headers. The same class can be used for footers as shown in the following code −" }, { "code": null, "e": 3952, "s": 3713, "text": "<div class = \"card list\">\n <div class = \"item item-divider\">\n Card header\n </div>\n \n <div class = \"item item-text-wrap\">\n Card text...\n </div>\n \n <div class = \"item item-divider\">\n Card Footer\n </div>\n</div>" }, { "code": null, "e": 4003, "s": 3952, "text": "The above code will produce the following screen −" }, { "code": null, "e": 4202, "s": 4003, "text": "You can add any element on top of your card. In following example, we will show you how to use the full-image class together with the item-body to get a good-looking windowed image inside your card." }, { "code": null, "e": 4665, "s": 4202, "text": "<div class = \"card\">\n <div class = \"item item-avatar\">\n <img src = \"my-image.png\">\n <h2>Card Name</h2>\n </div>\n\n <div class = \"item item-body\">\n <img class = \"full-image\" src = \"my-image.png\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eget \n pharetra tortor. Proin quis eros imperdiet, facilisis nisi in, tincidunt orci. \n Nam tristique elit massa, quis faucibus augue finibus ac.\n </div>\n</div>" }, { "code": null, "e": 4716, "s": 4665, "text": "The above code will produce the following screen −" }, { "code": null, "e": 4751, "s": 4716, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4768, "s": 4751, "text": " Frahaan Hussain" }, { "code": null, "e": 4805, "s": 4768, "text": "\n 185 Lectures \n 46.5 hours \n" }, { "code": null, "e": 4821, "s": 4805, "text": " Nikhil Agarwal" }, { "code": null, "e": 4828, "s": 4821, "text": " Print" }, { "code": null, "e": 4839, "s": 4828, "text": " Add Notes" } ]
Adjusting the spacing between the edge of the plot and the X-axis in Matplotlib
To adjust the spacing between the edge of the plot and the X-axis, we can use tight_layout() method or set the bottom padding of the current figure. Set the figure size and adjust the padding between and around the subplots. Create x and y data points using numpy. Plot x and y data points using plot() method. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-2, 2, 100) y = np.exp(x) plt.plot(x, y, c='red', lw=1) plt.show()
[ { "code": null, "e": 1211, "s": 1062, "text": "To adjust the spacing between the edge of the plot and the X-axis, we can use tight_layout() method or set the bottom padding of the current figure." }, { "code": null, "e": 1287, "s": 1211, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1327, "s": 1287, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1373, "s": 1327, "text": "Plot x and y data points using plot() method." }, { "code": null, "e": 1415, "s": 1373, "text": "To display the figure, use show() method." }, { "code": null, "e": 1638, "s": 1415, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.linspace(-2, 2, 100)\ny = np.exp(x)\nplt.plot(x, y, c='red', lw=1)\nplt.show()" } ]
Firebase - Quick Guide
As per official Firebase documentation − Firebase can power your app's backend, including data storage, user authentication, static hosting, and more. Focus on creating extraordinary user experiences. We will take care of the rest. Build cross-platform native mobile and web apps with our Android, iOS, and JavaScript SDKs. You can also connect Firebase to your existing backend using our server-side libraries or our REST API. Real-time Database − Firebase supports JSON data and all users connected to it receive live updates after every change. Real-time Database − Firebase supports JSON data and all users connected to it receive live updates after every change. Authentication − We can use anonymous, password or different social authentications. Authentication − We can use anonymous, password or different social authentications. Hosting − The applications can be deployed over secured connection to Firebase servers. Hosting − The applications can be deployed over secured connection to Firebase servers. It is simple and user friendly. No need for complicated configuration. It is simple and user friendly. No need for complicated configuration. The data is real-time, which means that every change will automatically update connected clients. The data is real-time, which means that every change will automatically update connected clients. Firebase offers simple control dashboard. Firebase offers simple control dashboard. There are a number of useful services to choose. There are a number of useful services to choose. Firebase free plan is limited to 50 Connections and 100 MB of storage. In the next chapter, we will discuss the environment setup of Firebase. In this chapter, we will show you how to add Firebase to the existing application. We will need NodeJS. Check the link from the following table, if you do not have it already. NodeJS and NPM NodeJS is the platform needed for Firebase development. Checkout our NodeJS Environment Setup. You can create a Firebase account here. You can create new app from the dashboard page. The following image shows the app we created. We can click the Manage App button to enter the app. You just need to create a folder where your app will be placed. Inside that folder, we will need index.html and index.js files. We will add Firebase to the header of our app. <html> <head> <script src = "https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script> <script type = "text/javascript" src = "index.js"></script> </head> <body> </body> </html> If you want to use your existing app, you can use Firebase NPM or Bowers packages. Run one of the following command from your apps root folder. npm install firebase --save bower install firebase The Firebase data is representing JSON objects. If you open your app from Firebase dashboard, you can add data manually by clicking on the + sign. We will create a simple data structure. You can check the image below. In the previous chapter, we connected Firebase to our app. Now, we can log Firebase to the console. console.log(firebase) We can create a reference to our player’s collection. var ref = firebase.database().ref('players'); console.log(ref); We can see the following result in the console. This chapter will explain the Firebase representation of arrays. We will use the same data from the previous chapter. We could create this data by sending the following JSON tree to the player’s collection. ['john', 'amanda'] This is because Firebase does not support Arrays directly, but it creates a list of objects with integers as key names. The reason for not using arrays is because Firebase acts as a real time database and if a couple of users were to manipulate arrays at the same time, the result could be problematic since array indexes are constantly changing. The way Firebase handles it, the keys (indexes) will always stay the same. We could delete john and amanda would still have the key (index) 1. In this chapter, we will show you how to save your data to Firebase. The set method will write or replace data on a specified path. Let us create a reference to the player’s collection and set two players. var playersRef = firebase.database().ref("players/"); playersRef.set ({ John: { number: 1, age: 30 }, Amanda: { number: 2, age: 20 } }); We will see the following result. We can update the Firebase data in a similar fashion. Notice how we are using the players/john path. var johnRef = firebase.database().ref("players/John"); johnRef.update ({ "number": 10 }); When we refresh our app, we can see that the Firebase data is updating. In our last chapter, we showed you how to write data in Firebase. Sometimes you need to have a unique identifier for your data. When you want to create unique identifiers for your data, you need to use the push method instead of the set method. The push() method will create a unique id when the data is pushed. If we want to create our players from the previous chapters with a unique id, we could use the code snippet given below. var ref = new Firebase('https://tutorialsfirebase.firebaseio.com'); var playersRef = ref.child("players"); playersRef.push ({ name: "John", number: 1, age: 30 }); playersRef.push ({ name: "Amanda", number: 2, age: 20 }); Now our data will look differently. The name will just be a name/value pair like the rest of the properties. We can get any key from Firebase by using the key() method. For example, if we want to get our collection name, we could use the following snippet. var ref = new Firebase('https://tutorialsfirebase.firebaseio.com'); var playersRef = ref.child("players"); var playersKey = playersRef.key(); console.log(playersKey); The console will log our collection name (players). More on this in our next chapters. Transactional data is used when you need to return some data from the database then make some calculation with it and store it back. Let us say we have one player inside our player list. We want to retrieve property, add one year of age and return it back to Firebase. The amandaRef is retrieving the age from the collection and then we can use the transaction method. We will get the current age, add one year and update the collection. var ref = new Firebase('https://tutorialsfirebase.firebaseio.com'); var amandaAgeRef = ref.child("players").child("-KGb1Ls-gEErWbAMMnZC").child('age'); amandaAgeRef.transaction(function(currentAge) { return currentAge + 1; }); If we run this code, we can see that the age value is updated to 21. In this chapter, we will show you how to read Firebase data. The following image shows the data we want to read. We can use the on() method to retrieve data. This method is taking the event type as "value" and then retrieves the snapshot of the data. When we add val() method to the snapshot, we will get the JavaScript representation of the data. Let us consider the following example. var ref = firebase.database().ref(); ref.on("value", function(snapshot) { console.log(snapshot.val()); }, function (error) { console.log("Error: " + error.code); }); If we run the following code, our console will show the data. In our next chapter, we will explain other event types that you can use for reading data. Firebase offers several different event types for reading data. Some of the most commonly used ones are described below. The first event type is value. We showed you how to use value in our last chapter. This event type will be triggered every time the data changes and it will retrieve all the data including children. This event type will be triggered once for every player and every time a new player is added to our data. It is useful for reading list data because we get access of the added player and previous player from the list. Let us consider the following example. var playersRef = firebase.database().ref("players/"); playersRef.on("child_added", function(data, prevChildKey) { var newPlayer = data.val(); console.log("name: " + newPlayer.name); console.log("age: " + newPlayer.age); console.log("number: " + newPlayer.number); console.log("Previous Player: " + prevChildKey); }); We will get the following result. If we add a new player named Bob, we will get the updated data. This event type is triggered when the data has changed. Let us consider the following example. var playersRef = firebase.database().ref("players/"); playersRef.on("child_changed", function(data) { var player = data.val(); console.log("The updated player name is " + player.name); }); We can change Bob to Maria in Firebase to get the update. If we want to get access of deleted data, we can use child_removed event type. var playersRef = firebase.database().ref("players/"); playersRef.on("child_removed", function(data) { var deletedPlayer = data.val(); console.log(deletedPlayer.name + " has been deleted"); }); Now, we can delete Maria from Firebase to get notifications. This chapter will show you how to detach callbacks in Firebase. Let us say we want to detach a callback for a function with value event type. var playersRef = firebase.database().ref("players/"); ref.on("value", function(data) { console.log(data.val()); }, function (error) { console.log("Error: " + error.code); }); We need to use off() method. This will remove all callbacks with value event type. playersRef.off("value"); When we want to detach all callbacks, we can use − playersRef.off(); Firebase offers various ways of ordering data. In this chapter, we will show simple query examples. We will use the same data from our previous chapters. To order data by name, we can use the following code. Let us consider the following example. var playersRef = firebase.database().ref("players/"); playersRef.orderByChild("name").on("child_added", function(data) { console.log(data.val().name); }); We will see names in the alphabetic order. We can order data by key in a similar fashion. Let us consider the following example. var playersRef = firebase.database().ref("players/"); playersRef.orderByKey().on("child_added", function(data) { console.log(data.key); }); The output will be as shown below. We can also order data by value. Let us add the ratings collection in Firebase. Now we can order data by value for each player. Let us consider the following example. var ratingRef = firebase.database().ref("ratings/"); ratingRef.orderByValue().on("value", function(data) { data.forEach(function(data) { console.log("The " + data.key + " rating is " + data.val()); }); }); The output will be as shown below. Firebase offers several ways to filter data. Let us understand what limit to first and last is. limitToFirst method returns the specified number of items beginning from the first one. limitToFirst method returns the specified number of items beginning from the first one. limitToLast method returns a specified number of items beginning from the last one. limitToLast method returns a specified number of items beginning from the last one. Our example is showing how this works. Since we only have two players in database, we will limit queries to one player. Let us consider the following example. var firstPlayerRef = firebase.database().ref("players/").limitToFirst(1); var lastPlayerRef = firebase.database().ref('players/').limitToLast(1); firstPlayerRef.on("value", function(data) { console.log(data.val()); }, function (error) { console.log("Error: " + error.code); }); lastPlayerRef.on("value", function(data) { console.log(data.val()); }, function (error) { console.log("Error: " + error.code); }); Our console will log the first player from the first query, and the last player from the second query. We can also use other Firebase filtering methods. The startAt(), endAt() and the equalTo() can be combined with ordering methods. In our example, we will combine it with the orderByChild() method. Let us consider the following example. var playersRef = firebase.database().ref("players/"); playersRef.orderByChild("name").startAt("Amanda").on("child_added", function(data) { console.log("Start at filter: " + data.val().name); }); playersRef.orderByChild("name").endAt("Amanda").on("child_added", function(data) { console.log("End at filter: " + data.val().name); }); playersRef.orderByChild("name").equalTo("John").on("child_added", function(data) { console.log("Equal to filter: " + data.val().name); }); playersRef.orderByChild("age").startAt(20).on("child_added", function(data) { console.log("Age filter: " + data.val().name); }); The first query will order elements by name and filter from the player with the name Amanda. The console will log both players. The second query will log "Amanda" since we are ending query with this name. The third one will log "John" since we are searching for a player with that name. The fourth example is showing how we can combine filters with "age" value. Instead of string, we are passing the number inside the startAt() method since age is represented by a number value. In this chapter, we will go through the best practices of Firebase. When you fetch the data from Firebase, you will get all of the child nodes. This is why deep nesting is not said to be the best practice. When you need deep nesting functionality, consider adding couple of different collections; even when you need to add some data duplication and use more than one request to retrieve what you need. In this chapter, we will show you how to use Firebase Email/Password authentication. To authenticate a user, we can use the createUserWithEmailAndPassword(email, password) method. Let us consider the following example. var email = "myemail@email.com"; var password = "mypassword"; firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) { console.log(error.code); console.log(error.message); }); We can check the Firebase dashboard and see that the user is created. The Sign-in process is almost the same. We are using the signInWithEmailAndPassword(email, password) to sign in the user. Let us consider the following example. var email = "myemail@email.com"; var password = "mypassword"; firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) { console.log(error.code); console.log(error.message); }); And finally we can logout the user with the signOut() method. Let us consider the following example. firebase.auth().signOut().then(function() { console.log("Logged out!") }, function(error) { console.log(error.code); console.log(error.message); }); In this chapter, we will show you how to set up Google authentication in Firebase. Open Firebase dashboard and click Auth on the left side menu. To open the list of available methods, you need to click on SIGN_IN_METHODS in the tab menu. Now you can choose Google from the list, enable it and save it. Inside our index.html, we will add two buttons. <button onclick = "googleSignin()">Google Signin</button> <button onclick = "googleSignout()">Google Signout</button> In this step, we will create Signin and Signout functions. We will use signInWithPopup() and signOut() methods. Let us consider the following example. var provider = new firebase.auth.GoogleAuthProvider(); function googleSignin() { firebase.auth() .signInWithPopup(provider).then(function(result) { var token = result.credential.accessToken; var user = result.user; console.log(token) console.log(user) }).catch(function(error) { var errorCode = error.code; var errorMessage = error.message; console.log(error.code) console.log(error.message) }); } function googleSignout() { firebase.auth().signOut() .then(function() { console.log('Signout Succesfull') }, function(error) { console.log('Signout Failed') }); } After we refresh the page, we can click on the Google Signin button to trigger the Google popup. If signing in is successful, the developer console will log in our user. We can also click on the Google Signout button to logout from the app. The console will confirm that the logout was successful. In this chapter, we will authenticate users with Firebase Facebook authentication. We need to open Firebase dashboard and click Auth in side menu. Next, we need to choose SIGN-IN-METHOD in tab bar. We will enable Facebook auth and leave this open since we need to add App ID and App Secret when we finish step 2. To enable Facebook authentication, we need to create the Facebook app. Click on this link to start. Once the app is created, we need to copy App ID and App Secret to the Firebase page, which we left open in step 1. We also need to copy OAuth Redirect URI from this window into the Facebook app. You can find + Add Product inside side menu of the Facebook app dashboard. Choose Facebook Login and it will appear in the side menu. You will find input field Valid OAuth redirect URIs where you need to copy the OAuth Redirect URI from Firebase. Copy the following code at the beginning of the body tag in index.html. Be sure to replace the 'APP_ID' to your app id from Facebook dashboard. Let us consider the following example. <script> window.fbAsyncInit = function() { FB.init ({ appId : 'APP_ID', xfbml : true, version : 'v2.6' }); }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); } (document, 'script', 'facebook-jssdk')); </script> We set everything in first three steps, now we can create two buttons for login and logout. <button onclick = "facebookSignin()">Facebook Signin</button> <button onclick = "facebookSignout()">Facebook Signout</button> This is the last step. Open index.js and copy the following code. var provider = new firebase.auth.FacebookAuthProvider(); function facebookSignin() { firebase.auth().signInWithPopup(provider) .then(function(result) { var token = result.credential.accessToken; var user = result.user; console.log(token) console.log(user) }).catch(function(error) { console.log(error.code); console.log(error.message); }); } function facebookSignout() { firebase.auth().signOut() .then(function() { console.log('Signout successful!') }, function(error) { console.log('Signout failed') }); } In this chapter, we will explain how to use Twitter authentication. You can create Twitter app on this link. Once your app is created click on Keys and Access Tokens where you can find API Key and API Secret. You will need this in step 2. In your Firebase dashboard side menu, you need to click Auth. Then open SIGN-IN-METHOD tab. Click on Twitter to enable it. You need to add API Key and API Secret from the step 1. Then you would need to copy the callback URL and paste it in your Twitter app. You can find the Callback URL of your Twitter app when you click on the Settings tab. In this step, we will add two buttons inside the body tag of index.html. <button onclick = "twitterSignin()">Twitter Signin</button> <button onclick = "twitterSignout()">Twitter Signout</button> Now we can create functions for Twitter authentication. var provider = new firebase.auth.TwitterAuthProvider(); function twitterSignin() { firebase.auth().signInWithPopup(provider) .then(function(result) { var token = result.credential.accessToken; var user = result.user; console.log(token) console.log(user) }).catch(function(error) { console.log(error.code) console.log(error.message) }); } function twitterSignout() { firebase.auth().signOut() .then(function() { console.log('Signout successful!') }, function(error) { console.log('Signout failed!') }); } When we start our app, we can sigin or signout by clicking the two buttons. The console will confirm that the authentication is successful. In this chapter, we will show you how to authenticate users using the GitHub API. Open Firebase dashboard and click Auth from the side menu and then SIGN-IN-METHOD in tab bar. You need enable GitHub authentication and copy the Callback URL. You will need this in step 2. You can leave this tab open since you will need to add Client ID and Client Secret once you finish step 2. Follow this link to create the GitHub app. You need to copy the Callback URL from Firebase into the Authorization callback URL field. Once your app is created, you need to copy the Client Key and the Client Secret from the GitHub app to Firebase. We will add two buttons in the body tag. <button onclick = "githubSignin()">Github Signin</button> <button onclick = "githubSignout()">Github Signout</button> We will create functions for signin and signout inside the index.js file. var provider = new firebase.auth.GithubAuthProvider(); function githubSignin() { firebase.auth().signInWithPopup(provider) .then(function(result) { var token = result.credential.accessToken; var user = result.user; console.log(token) console.log(user) }).catch(function(error) { var errorCode = error.code; var errorMessage = error.message; console.log(error.code) console.log(error.message) }); } function githubSignout(){ firebase.auth().signOut() .then(function() { console.log('Signout successful!') }, function(error) { console.log('Signout failed') }); } Now we can click on buttons to trigger authentication. Console will show that the authentication is successful. In this chapter, we will authenticate users anonymously. This is the same process as in our earlier chapters. You need to open the Firebase dashboard, click on Auth from the side menu and SIGN-IN-METHOD inside the tab bar. You need to enable anonymous authentication. We can use signInAnonymously() method for this authentication. Let us consider the following example. firebase.auth().signInAnonymously() .then(function() { console.log('Logged in as Anonymous!') }).catch(function(error) { var errorCode = error.code; var errorMessage = error.message; console.log(errorCode); console.log(errorMessage); }); In this chapter, we will show you how to handle the Firebase connection state. We can check for connection value using the following code. var connectedRef = firebase.database().ref(".info/connected"); connectedRef.on("value", function(snap) { if (snap.val() === true) { alert("connected"); } else { alert("not connected"); } }); When we run the app, the pop up will inform us about the connection. By using the above given function, you can keep a track of the connection state and update your app accordingly. Security in Firebase is handled by setting the JSON like object inside the security rules. Security rules can be found when we click on Database inside the side menu and then RULES in tab bar. In this chapter, we will go through a couple of simple examples to show you how to secure the Firebase data. The following code snippet defined inside the Firebase security rules will allow writing access to /users/'$uid'/ for the authenticated user with the same uid, but everyone could read it. Let us consider the following example. { "rules": { "users": { "$uid": { ".write": "$uid === auth.uid", ".read": true } } } } We can enforce data to string by using the following example. { "rules": { "foo": { ".validate": "newData.isString()" } } } This chapter only grabbed the surface of Firebase security rules. The important thing is to understand how these rules work, so you can combine it inside the app. In this chapter, we will show you how to host your app on the Firebase server. Before we begin, let us just add some text to index.html body tag. In this example, we will add the following text. <h1>WELCOME TO FIREBASE TUTORIALS APP</h1> We need to install firebase tools globally in the command prompt window. npm install -g firebase-tools First we need to login to Firebase in the command prompt. firebase login Open the root folder of your app in the command prompt and run the following command. firebase init This command will initialize your app. NOTE − If you have used a default configuration, the public folder will be created and the index.html inside this folder will be the starting point of your app. You can copy your app file inside the public folder as a workaround. This is the last step in this chapter. Run the following command from the command prompt to deploy your app. firebase deploy After this step, the console will log your apps Firebase URL. In our case, it is called https://tutorialsfirebase.firebaseapp.com. We can run this link in the browser to see our app. 60 Lectures 5 hours University Code 28 Lectures 2.5 hours Appeteria 85 Lectures 14.5 hours Appeteria 46 Lectures 2.5 hours Gautham Vijayan 13 Lectures 1.5 hours Nishant Kumar 85 Lectures 16.5 hours Rahul Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2207, "s": 2166, "text": "As per official Firebase documentation −" }, { "code": null, "e": 2594, "s": 2207, "text": "Firebase can power your app's backend, including data storage, user authentication, static hosting, and more. Focus on creating extraordinary user experiences. We will take care of the rest. Build cross-platform native mobile and web apps with our Android, iOS, and JavaScript SDKs. You can also connect Firebase to your existing backend using our server-side libraries or our REST API." }, { "code": null, "e": 2714, "s": 2594, "text": "Real-time Database − Firebase supports JSON data and all users connected to it receive live updates after every change." }, { "code": null, "e": 2834, "s": 2714, "text": "Real-time Database − Firebase supports JSON data and all users connected to it receive live updates after every change." }, { "code": null, "e": 2919, "s": 2834, "text": "Authentication − We can use anonymous, password or different social authentications." }, { "code": null, "e": 3004, "s": 2919, "text": "Authentication − We can use anonymous, password or different social authentications." }, { "code": null, "e": 3092, "s": 3004, "text": "Hosting − The applications can be deployed over secured connection to Firebase servers." }, { "code": null, "e": 3180, "s": 3092, "text": "Hosting − The applications can be deployed over secured connection to Firebase servers." }, { "code": null, "e": 3251, "s": 3180, "text": "It is simple and user friendly. No need for complicated configuration." }, { "code": null, "e": 3322, "s": 3251, "text": "It is simple and user friendly. No need for complicated configuration." }, { "code": null, "e": 3420, "s": 3322, "text": "The data is real-time, which means that every change will automatically update connected clients." }, { "code": null, "e": 3518, "s": 3420, "text": "The data is real-time, which means that every change will automatically update connected clients." }, { "code": null, "e": 3560, "s": 3518, "text": "Firebase offers simple control dashboard." }, { "code": null, "e": 3602, "s": 3560, "text": "Firebase offers simple control dashboard." }, { "code": null, "e": 3651, "s": 3602, "text": "There are a number of useful services to choose." }, { "code": null, "e": 3700, "s": 3651, "text": "There are a number of useful services to choose." }, { "code": null, "e": 3771, "s": 3700, "text": "Firebase free plan is limited to 50 Connections and 100 MB of storage." }, { "code": null, "e": 3843, "s": 3771, "text": "In the next chapter, we will discuss the environment setup of Firebase." }, { "code": null, "e": 4019, "s": 3843, "text": "In this chapter, we will show you how to add Firebase to the existing application. We will need NodeJS. Check the link from the following table, if you do not have it already." }, { "code": null, "e": 4034, "s": 4019, "text": "NodeJS and NPM" }, { "code": null, "e": 4129, "s": 4034, "text": "NodeJS is the platform needed for Firebase development. Checkout our NodeJS Environment Setup." }, { "code": null, "e": 4169, "s": 4129, "text": "You can create a Firebase account here." }, { "code": null, "e": 4316, "s": 4169, "text": "You can create new app from the dashboard page. The following image shows the app we created. We can click the Manage App button to enter the app." }, { "code": null, "e": 4491, "s": 4316, "text": "You just need to create a folder where your app will be placed. Inside that folder, we will need index.html and index.js files. We will add Firebase to the header of our app." }, { "code": null, "e": 4702, "s": 4491, "text": "<html>\n <head>\n <script src = \"https://cdn.firebase.com/js/client/2.4.2/firebase.js\"></script>\n <script type = \"text/javascript\" src = \"index.js\"></script>\n </head>\n\t\n <body>\n\n </body>\n</html>" }, { "code": null, "e": 4846, "s": 4702, "text": "If you want to use your existing app, you can use Firebase NPM or Bowers packages. Run one of the following command from your apps root folder." }, { "code": null, "e": 4875, "s": 4846, "text": "npm install firebase --save\n" }, { "code": null, "e": 4899, "s": 4875, "text": "bower install firebase\n" }, { "code": null, "e": 5046, "s": 4899, "text": "The Firebase data is representing JSON objects. If you open your app from Firebase dashboard, you can add data manually by clicking on the + sign." }, { "code": null, "e": 5117, "s": 5046, "text": "We will create a simple data structure. You can check the image below." }, { "code": null, "e": 5217, "s": 5117, "text": "In the previous chapter, we connected Firebase to our app. Now, we can log Firebase to the console." }, { "code": null, "e": 5239, "s": 5217, "text": "console.log(firebase)" }, { "code": null, "e": 5293, "s": 5239, "text": "We can create a reference to our player’s collection." }, { "code": null, "e": 5361, "s": 5293, "text": " \nvar ref = firebase.database().ref('players');\n\nconsole.log(ref);" }, { "code": null, "e": 5409, "s": 5361, "text": "We can see the following result in the console." }, { "code": null, "e": 5527, "s": 5409, "text": "This chapter will explain the Firebase representation of arrays. We will use the same data from the previous chapter." }, { "code": null, "e": 5616, "s": 5527, "text": "We could create this data by sending the following JSON tree to the player’s collection." }, { "code": null, "e": 5636, "s": 5616, "text": "['john', 'amanda']\n" }, { "code": null, "e": 5756, "s": 5636, "text": "This is because Firebase does not support Arrays directly, but it creates a list of objects with integers as key names." }, { "code": null, "e": 5983, "s": 5756, "text": "The reason for not using arrays is because Firebase acts as a real time database and if a couple of users were to manipulate arrays at the same time, the result could be problematic since array indexes are constantly changing." }, { "code": null, "e": 6126, "s": 5983, "text": "The way Firebase handles it, the keys (indexes) will always stay the same. We could delete john and amanda would still have the key (index) 1." }, { "code": null, "e": 6195, "s": 6126, "text": "In this chapter, we will show you how to save your data to Firebase." }, { "code": null, "e": 6332, "s": 6195, "text": "The set method will write or replace data on a specified path. Let us create a reference to the player’s collection and set two players." }, { "code": null, "e": 6508, "s": 6332, "text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.set ({\n John: {\n number: 1,\n age: 30\n },\n\t\n Amanda: {\n number: 2,\n age: 20\n }\n});" }, { "code": null, "e": 6542, "s": 6508, "text": "We will see the following result." }, { "code": null, "e": 6643, "s": 6542, "text": "We can update the Firebase data in a similar fashion. Notice how we are using the players/john path." }, { "code": null, "e": 6737, "s": 6643, "text": "var johnRef = firebase.database().ref(\"players/John\");\n\njohnRef.update ({\n \"number\": 10\n});" }, { "code": null, "e": 6809, "s": 6737, "text": "When we refresh our app, we can see that the Firebase data is updating." }, { "code": null, "e": 7054, "s": 6809, "text": "In our last chapter, we showed you how to write data in Firebase. Sometimes you need to have a unique identifier for your data. When you want to create unique identifiers for your data, you need to use the push method instead of the set method." }, { "code": null, "e": 7242, "s": 7054, "text": "The push() method will create a unique id when the data is pushed. If we want to create our players from the previous chapters with a unique id, we could use the code snippet given below." }, { "code": null, "e": 7483, "s": 7242, "text": "var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');\n\nvar playersRef = ref.child(\"players\");\nplayersRef.push ({\n name: \"John\",\n number: 1,\n age: 30\n});\n\nplayersRef.push ({\n name: \"Amanda\",\n number: 2,\n age: 20\n});" }, { "code": null, "e": 7592, "s": 7483, "text": "Now our data will look differently. The name will just be a name/value pair like the rest of the properties." }, { "code": null, "e": 7740, "s": 7592, "text": "We can get any key from Firebase by using the key() method. For example, if we want to get our collection name, we could use the following snippet." }, { "code": null, "e": 7909, "s": 7740, "text": "var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');\n\nvar playersRef = ref.child(\"players\");\n\nvar playersKey = playersRef.key();\nconsole.log(playersKey);" }, { "code": null, "e": 7961, "s": 7909, "text": "The console will log our collection name (players)." }, { "code": null, "e": 7996, "s": 7961, "text": "More on this in our next chapters." }, { "code": null, "e": 8129, "s": 7996, "text": "Transactional data is used when you need to return some data from the database then make some calculation with it and store it back." }, { "code": null, "e": 8183, "s": 8129, "text": "Let us say we have one player inside our player list." }, { "code": null, "e": 8265, "s": 8183, "text": "We want to retrieve property, add one year of age and return it back to Firebase." }, { "code": null, "e": 8434, "s": 8265, "text": "The amandaRef is retrieving the age from the collection and then we can use the transaction method. We will get the current age, add one year and update the collection." }, { "code": null, "e": 8666, "s": 8434, "text": "var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');\n\nvar amandaAgeRef = ref.child(\"players\").child(\"-KGb1Ls-gEErWbAMMnZC\").child('age');\n\namandaAgeRef.transaction(function(currentAge) {\n return currentAge + 1;\n});" }, { "code": null, "e": 8735, "s": 8666, "text": "If we run this code, we can see that the age value is updated to 21." }, { "code": null, "e": 8848, "s": 8735, "text": "In this chapter, we will show you how to read Firebase data. The following image shows the data we want to read." }, { "code": null, "e": 9083, "s": 8848, "text": "We can use the on() method to retrieve data. This method is taking the event type as \"value\" and then retrieves the snapshot of the data. When we add val() method to the snapshot, we will get the JavaScript representation of the data." }, { "code": null, "e": 9122, "s": 9083, "text": "Let us consider the following example." }, { "code": null, "e": 9295, "s": 9122, "text": "var ref = firebase.database().ref();\n\nref.on(\"value\", function(snapshot) {\n console.log(snapshot.val());\n}, function (error) {\n console.log(\"Error: \" + error.code);\n});" }, { "code": null, "e": 9357, "s": 9295, "text": "If we run the following code, our console will show the data." }, { "code": null, "e": 9447, "s": 9357, "text": "In our next chapter, we will explain other event types that you can use for reading data." }, { "code": null, "e": 9568, "s": 9447, "text": "Firebase offers several different event types for reading data. Some of the most commonly used ones are described below." }, { "code": null, "e": 9767, "s": 9568, "text": "The first event type is value. We showed you how to use value in our last chapter. This event type will be triggered every time the data changes and it will retrieve all the data including children." }, { "code": null, "e": 9985, "s": 9767, "text": "This event type will be triggered once for every player and every time a new player is added to our data. It is useful for reading list data because we get access of the added player and previous player from the list." }, { "code": null, "e": 10024, "s": 9985, "text": "Let us consider the following example." }, { "code": null, "e": 10357, "s": 10024, "text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.on(\"child_added\", function(data, prevChildKey) {\n var newPlayer = data.val();\n console.log(\"name: \" + newPlayer.name);\n console.log(\"age: \" + newPlayer.age);\n console.log(\"number: \" + newPlayer.number);\n console.log(\"Previous Player: \" + prevChildKey);\n});" }, { "code": null, "e": 10391, "s": 10357, "text": "We will get the following result." }, { "code": null, "e": 10455, "s": 10391, "text": "If we add a new player named Bob, we will get the updated data." }, { "code": null, "e": 10511, "s": 10455, "text": "This event type is triggered when the data has changed." }, { "code": null, "e": 10550, "s": 10511, "text": "Let us consider the following example." }, { "code": null, "e": 10746, "s": 10550, "text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.on(\"child_changed\", function(data) {\n var player = data.val();\n console.log(\"The updated player name is \" + player.name);\n});" }, { "code": null, "e": 10804, "s": 10746, "text": "We can change Bob to Maria in Firebase to get the update." }, { "code": null, "e": 10883, "s": 10804, "text": "If we want to get access of deleted data, we can use child_removed event type." }, { "code": null, "e": 11083, "s": 10883, "text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.on(\"child_removed\", function(data) {\n var deletedPlayer = data.val();\n console.log(deletedPlayer.name + \" has been deleted\");\n});" }, { "code": null, "e": 11144, "s": 11083, "text": "Now, we can delete Maria from Firebase to get notifications." }, { "code": null, "e": 11208, "s": 11144, "text": "This chapter will show you how to detach callbacks in Firebase." }, { "code": null, "e": 11286, "s": 11208, "text": "Let us say we want to detach a callback for a function with value event type." }, { "code": null, "e": 11468, "s": 11286, "text": "var playersRef = firebase.database().ref(\"players/\");\n\nref.on(\"value\", function(data) {\n console.log(data.val());\n}, function (error) {\n console.log(\"Error: \" + error.code);\n});" }, { "code": null, "e": 11551, "s": 11468, "text": "We need to use off() method. This will remove all callbacks with value event type." }, { "code": null, "e": 11577, "s": 11551, "text": "playersRef.off(\"value\");\n" }, { "code": null, "e": 11628, "s": 11577, "text": "When we want to detach all callbacks, we can use −" }, { "code": null, "e": 11647, "s": 11628, "text": "playersRef.off();\n" }, { "code": null, "e": 11801, "s": 11647, "text": "Firebase offers various ways of ordering data. In this chapter, we will show simple query examples. We will use the same data from our previous chapters." }, { "code": null, "e": 11855, "s": 11801, "text": "To order data by name, we can use the following code." }, { "code": null, "e": 11894, "s": 11855, "text": "Let us consider the following example." }, { "code": null, "e": 12053, "s": 11894, "text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.orderByChild(\"name\").on(\"child_added\", function(data) {\n console.log(data.val().name);\n});" }, { "code": null, "e": 12096, "s": 12053, "text": "We will see names in the alphabetic order." }, { "code": null, "e": 12143, "s": 12096, "text": "We can order data by key in a similar fashion." }, { "code": null, "e": 12182, "s": 12143, "text": "Let us consider the following example." }, { "code": null, "e": 12326, "s": 12182, "text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.orderByKey().on(\"child_added\", function(data) {\n console.log(data.key);\n});" }, { "code": null, "e": 12361, "s": 12326, "text": "The output will be as shown below." }, { "code": null, "e": 12441, "s": 12361, "text": "We can also order data by value. Let us add the ratings collection in Firebase." }, { "code": null, "e": 12489, "s": 12441, "text": "Now we can order data by value for each player." }, { "code": null, "e": 12528, "s": 12489, "text": "Let us consider the following example." }, { "code": null, "e": 12755, "s": 12528, "text": "var ratingRef = firebase.database().ref(\"ratings/\");\n\nratingRef.orderByValue().on(\"value\", function(data) {\n \n data.forEach(function(data) {\n console.log(\"The \" + data.key + \" rating is \" + data.val());\n });\n \n});" }, { "code": null, "e": 12790, "s": 12755, "text": "The output will be as shown below." }, { "code": null, "e": 12835, "s": 12790, "text": "Firebase offers several ways to filter data." }, { "code": null, "e": 12886, "s": 12835, "text": "Let us understand what limit to first and last is." }, { "code": null, "e": 12974, "s": 12886, "text": "limitToFirst method returns the specified number of items beginning from the first one." }, { "code": null, "e": 13062, "s": 12974, "text": "limitToFirst method returns the specified number of items beginning from the first one." }, { "code": null, "e": 13146, "s": 13062, "text": "limitToLast method returns a specified number of items beginning from the last one." }, { "code": null, "e": 13230, "s": 13146, "text": "limitToLast method returns a specified number of items beginning from the last one." }, { "code": null, "e": 13350, "s": 13230, "text": "Our example is showing how this works. Since we only have two players in database, we will limit queries to one player." }, { "code": null, "e": 13389, "s": 13350, "text": "Let us consider the following example." }, { "code": null, "e": 13813, "s": 13389, "text": "var firstPlayerRef = firebase.database().ref(\"players/\").limitToFirst(1);\n\nvar lastPlayerRef = firebase.database().ref('players/').limitToLast(1);\n\nfirstPlayerRef.on(\"value\", function(data) {\n console.log(data.val());\n}, function (error) {\n console.log(\"Error: \" + error.code);\n});\n\nlastPlayerRef.on(\"value\", function(data) {\n console.log(data.val());\n}, function (error) {\n console.log(\"Error: \" + error.code);\n});" }, { "code": null, "e": 13916, "s": 13813, "text": "Our console will log the first player from the first query, and the last player from the second query." }, { "code": null, "e": 14113, "s": 13916, "text": "We can also use other Firebase filtering methods. The startAt(), endAt() and the equalTo() can be combined with ordering methods. In our example, we will combine it with the orderByChild() method." }, { "code": null, "e": 14152, "s": 14113, "text": "Let us consider the following example." }, { "code": null, "e": 14768, "s": 14152, "text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.orderByChild(\"name\").startAt(\"Amanda\").on(\"child_added\", function(data) {\n console.log(\"Start at filter: \" + data.val().name);\n});\n\nplayersRef.orderByChild(\"name\").endAt(\"Amanda\").on(\"child_added\", function(data) {\n console.log(\"End at filter: \" + data.val().name);\n});\n\nplayersRef.orderByChild(\"name\").equalTo(\"John\").on(\"child_added\", function(data) {\n console.log(\"Equal to filter: \" + data.val().name);\n});\n\nplayersRef.orderByChild(\"age\").startAt(20).on(\"child_added\", function(data) {\n console.log(\"Age filter: \" + data.val().name);\n});" }, { "code": null, "e": 15055, "s": 14768, "text": "The first query will order elements by name and filter from the player with the name Amanda. The console will log both players. The second query will log \"Amanda\" since we are ending query with this name. The third one will log \"John\" since we are searching for a player with that name." }, { "code": null, "e": 15247, "s": 15055, "text": "The fourth example is showing how we can combine filters with \"age\" value. Instead of string, we are passing the number inside the startAt() method since age is represented by a number value." }, { "code": null, "e": 15315, "s": 15247, "text": "In this chapter, we will go through the best practices of Firebase." }, { "code": null, "e": 15453, "s": 15315, "text": "When you fetch the data from Firebase, you will get all of the child nodes. This is why deep nesting is not said to be the best practice." }, { "code": null, "e": 15649, "s": 15453, "text": "When you need deep nesting functionality, consider adding couple of different collections; even when you need to add some data duplication and use more than one request to retrieve what you need." }, { "code": null, "e": 15734, "s": 15649, "text": "In this chapter, we will show you how to use Firebase Email/Password authentication." }, { "code": null, "e": 15829, "s": 15734, "text": "To authenticate a user, we can use the createUserWithEmailAndPassword(email, password) method." }, { "code": null, "e": 15868, "s": 15829, "text": "Let us consider the following example." }, { "code": null, "e": 16082, "s": 15868, "text": "var email = \"myemail@email.com\";\nvar password = \"mypassword\";\n\nfirebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {\n console.log(error.code);\n console.log(error.message);\n});" }, { "code": null, "e": 16152, "s": 16082, "text": "We can check the Firebase dashboard and see that the user is created." }, { "code": null, "e": 16274, "s": 16152, "text": "The Sign-in process is almost the same. We are using the signInWithEmailAndPassword(email, password) to sign in the user." }, { "code": null, "e": 16313, "s": 16274, "text": "Let us consider the following example." }, { "code": null, "e": 16523, "s": 16313, "text": "var email = \"myemail@email.com\";\nvar password = \"mypassword\";\n\nfirebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {\n console.log(error.code);\n console.log(error.message);\n});" }, { "code": null, "e": 16585, "s": 16523, "text": "And finally we can logout the user with the signOut() method." }, { "code": null, "e": 16624, "s": 16585, "text": "Let us consider the following example." }, { "code": null, "e": 16782, "s": 16624, "text": "firebase.auth().signOut().then(function() {\n console.log(\"Logged out!\")\n}, function(error) {\n console.log(error.code);\n console.log(error.message);\n});" }, { "code": null, "e": 16865, "s": 16782, "text": "In this chapter, we will show you how to set up Google authentication in Firebase." }, { "code": null, "e": 17020, "s": 16865, "text": "Open Firebase dashboard and click Auth on the left side menu. To open the list of available methods, you need to click on SIGN_IN_METHODS in the tab menu." }, { "code": null, "e": 17084, "s": 17020, "text": "Now you can choose Google from the list, enable it and save it." }, { "code": null, "e": 17132, "s": 17084, "text": "Inside our index.html, we will add two buttons." }, { "code": null, "e": 17250, "s": 17132, "text": "<button onclick = \"googleSignin()\">Google Signin</button>\n<button onclick = \"googleSignout()\">Google Signout</button>" }, { "code": null, "e": 17362, "s": 17250, "text": "In this step, we will create Signin and Signout functions. We will use signInWithPopup() and signOut() methods." }, { "code": null, "e": 17401, "s": 17362, "text": "Let us consider the following example." }, { "code": null, "e": 18062, "s": 17401, "text": "var provider = new firebase.auth.GoogleAuthProvider();\n\nfunction googleSignin() {\n firebase.auth()\n \n .signInWithPopup(provider).then(function(result) {\n var token = result.credential.accessToken;\n var user = result.user;\n\t\t\n console.log(token)\n console.log(user)\n }).catch(function(error) {\n var errorCode = error.code;\n var errorMessage = error.message;\n\t\t\n console.log(error.code)\n console.log(error.message)\n });\n}\n\nfunction googleSignout() {\n firebase.auth().signOut()\n\t\n .then(function() {\n console.log('Signout Succesfull')\n }, function(error) {\n console.log('Signout Failed') \n });\n}" }, { "code": null, "e": 18232, "s": 18062, "text": "After we refresh the page, we can click on the Google Signin button to trigger the Google popup. If signing in is successful, the developer console will log in our user." }, { "code": null, "e": 18360, "s": 18232, "text": "We can also click on the Google Signout button to logout from the app. The console will confirm that the logout was successful." }, { "code": null, "e": 18443, "s": 18360, "text": "In this chapter, we will authenticate users with Firebase Facebook authentication." }, { "code": null, "e": 18673, "s": 18443, "text": "We need to open Firebase dashboard and click Auth in side menu. Next, we need to choose SIGN-IN-METHOD in tab bar. We will enable Facebook auth and leave this open since we need to add App ID and App Secret when we finish step 2." }, { "code": null, "e": 19043, "s": 18673, "text": "To enable Facebook authentication, we need to create the Facebook app. Click on this link to start. Once the app is created, we need to copy App ID and App Secret to the Firebase page, which we left open in step 1. We also need to copy OAuth Redirect URI from this window into the Facebook app. You can find + Add Product inside side menu of the Facebook app dashboard." }, { "code": null, "e": 19215, "s": 19043, "text": "Choose Facebook Login and it will appear in the side menu. You will find input field Valid OAuth redirect URIs where you need to copy the OAuth Redirect URI from Firebase." }, { "code": null, "e": 19359, "s": 19215, "text": "Copy the following code at the beginning of the body tag in index.html. Be sure to replace the 'APP_ID' to your app id from Facebook dashboard." }, { "code": null, "e": 19398, "s": 19359, "text": "Let us consider the following example." }, { "code": null, "e": 19883, "s": 19398, "text": "<script>\n window.fbAsyncInit = function() {\n FB.init ({\n appId : 'APP_ID',\n xfbml : true,\n version : 'v2.6'\n });\n };\n\n (function(d, s, id) {\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) {return;}\n js = d.createElement(s); js.id = id;\n js.src = \"//connect.facebook.net/en_US/sdk.js\";\n fjs.parentNode.insertBefore(js, fjs);\n } (document, 'script', 'facebook-jssdk'));\n\t\n</script>" }, { "code": null, "e": 19975, "s": 19883, "text": "We set everything in first three steps, now we can create two buttons for login and logout." }, { "code": null, "e": 20101, "s": 19975, "text": "<button onclick = \"facebookSignin()\">Facebook Signin</button>\n<button onclick = \"facebookSignout()\">Facebook Signout</button>" }, { "code": null, "e": 20167, "s": 20101, "text": "This is the last step. Open index.js and copy the following code." }, { "code": null, "e": 20760, "s": 20167, "text": "var provider = new firebase.auth.FacebookAuthProvider();\n\nfunction facebookSignin() {\n firebase.auth().signInWithPopup(provider)\n \n .then(function(result) {\n var token = result.credential.accessToken;\n var user = result.user;\n\t\t\n console.log(token)\n console.log(user)\n }).catch(function(error) {\n console.log(error.code);\n console.log(error.message);\n });\n}\n\nfunction facebookSignout() {\n firebase.auth().signOut()\n \n .then(function() {\n console.log('Signout successful!')\n }, function(error) {\n console.log('Signout failed')\n });\n}" }, { "code": null, "e": 20828, "s": 20760, "text": "In this chapter, we will explain how to use Twitter authentication." }, { "code": null, "e": 20999, "s": 20828, "text": "You can create Twitter app on this link. Once your app is created click on Keys and Access Tokens where you can find API Key and API Secret. You will need this in step 2." }, { "code": null, "e": 21178, "s": 20999, "text": "In your Firebase dashboard side menu, you need to click Auth. Then open SIGN-IN-METHOD tab. Click on Twitter to enable it. You need to add API Key and API Secret from the step 1." }, { "code": null, "e": 21343, "s": 21178, "text": "Then you would need to copy the callback URL and paste it in your Twitter app. You can find the Callback URL of your Twitter app when you click on the Settings tab." }, { "code": null, "e": 21416, "s": 21343, "text": "In this step, we will add two buttons inside the body tag of index.html." }, { "code": null, "e": 21538, "s": 21416, "text": "<button onclick = \"twitterSignin()\">Twitter Signin</button>\n<button onclick = \"twitterSignout()\">Twitter Signout</button>" }, { "code": null, "e": 21594, "s": 21538, "text": "Now we can create functions for Twitter authentication." }, { "code": null, "e": 22183, "s": 21594, "text": "var provider = new firebase.auth.TwitterAuthProvider();\n\nfunction twitterSignin() {\n firebase.auth().signInWithPopup(provider)\n \n .then(function(result) {\n var token = result.credential.accessToken;\n var user = result.user;\n\t\t\n console.log(token)\n console.log(user)\n }).catch(function(error) {\n console.log(error.code)\n console.log(error.message)\n });\n}\n\nfunction twitterSignout() {\n firebase.auth().signOut()\n \n .then(function() {\n console.log('Signout successful!')\n }, function(error) {\n console.log('Signout failed!')\n });\n}" }, { "code": null, "e": 22323, "s": 22183, "text": "When we start our app, we can sigin or signout by clicking the two buttons. The console will confirm that the authentication is successful." }, { "code": null, "e": 22405, "s": 22323, "text": "In this chapter, we will show you how to authenticate users using the GitHub API." }, { "code": null, "e": 22701, "s": 22405, "text": "Open Firebase dashboard and click Auth from the side menu and then SIGN-IN-METHOD in tab bar. You need enable GitHub authentication and copy the Callback URL. You will need this in step 2. You can leave this tab open since you will need to add Client ID and Client Secret once you finish step 2." }, { "code": null, "e": 22948, "s": 22701, "text": "Follow this link to create the GitHub app. You need to copy the Callback URL from Firebase into the Authorization callback URL field. Once your app is created, you need to copy the Client Key and the Client Secret from the GitHub app to Firebase." }, { "code": null, "e": 22989, "s": 22948, "text": "We will add two buttons in the body tag." }, { "code": null, "e": 23107, "s": 22989, "text": "<button onclick = \"githubSignin()\">Github Signin</button>\n<button onclick = \"githubSignout()\">Github Signout</button>" }, { "code": null, "e": 23181, "s": 23107, "text": "We will create functions for signin and signout inside the index.js file." }, { "code": null, "e": 23842, "s": 23181, "text": "var provider = new firebase.auth.GithubAuthProvider();\n\nfunction githubSignin() {\n firebase.auth().signInWithPopup(provider)\n \n .then(function(result) {\n var token = result.credential.accessToken;\n var user = result.user;\n\t\t\n console.log(token)\n console.log(user)\n }).catch(function(error) {\n var errorCode = error.code;\n var errorMessage = error.message;\n\t\t\n console.log(error.code)\n console.log(error.message)\n });\n}\n\nfunction githubSignout(){\n firebase.auth().signOut()\n \n .then(function() {\n console.log('Signout successful!')\n }, function(error) {\n console.log('Signout failed')\n });\n}" }, { "code": null, "e": 23954, "s": 23842, "text": "Now we can click on buttons to trigger authentication. Console will show that the authentication is successful." }, { "code": null, "e": 24011, "s": 23954, "text": "In this chapter, we will authenticate users anonymously." }, { "code": null, "e": 24222, "s": 24011, "text": "This is the same process as in our earlier chapters. You need to open the Firebase dashboard, click on Auth from the side menu and SIGN-IN-METHOD inside the tab bar. You need to enable anonymous authentication." }, { "code": null, "e": 24285, "s": 24222, "text": "We can use signInAnonymously() method for this authentication." }, { "code": null, "e": 24324, "s": 24285, "text": "Let us consider the following example." }, { "code": null, "e": 24584, "s": 24324, "text": "firebase.auth().signInAnonymously()\n.then(function() {\n console.log('Logged in as Anonymous!')\n \n }).catch(function(error) {\n var errorCode = error.code;\n var errorMessage = error.message;\n console.log(errorCode);\n console.log(errorMessage);\n});" }, { "code": null, "e": 24663, "s": 24584, "text": "In this chapter, we will show you how to handle the Firebase connection state." }, { "code": null, "e": 24723, "s": 24663, "text": "We can check for connection value using the following code." }, { "code": null, "e": 24936, "s": 24723, "text": "var connectedRef = firebase.database().ref(\".info/connected\");\n\nconnectedRef.on(\"value\", function(snap) {\n if (snap.val() === true) {\n alert(\"connected\");\n } else {\n alert(\"not connected\");\n }\n});" }, { "code": null, "e": 25005, "s": 24936, "text": "When we run the app, the pop up will inform us about the connection." }, { "code": null, "e": 25118, "s": 25005, "text": "By using the above given function, you can keep a track of the connection state and update your app accordingly." }, { "code": null, "e": 25311, "s": 25118, "text": "Security in Firebase is handled by setting the JSON like object inside the security rules. Security rules can be found when we click on Database inside the side menu and then RULES in tab bar." }, { "code": null, "e": 25420, "s": 25311, "text": "In this chapter, we will go through a couple of simple examples to show you how to secure the Firebase data." }, { "code": null, "e": 25608, "s": 25420, "text": "The following code snippet defined inside the Firebase security rules will allow writing access to /users/'$uid'/ for the authenticated user with the same uid, but everyone could read it." }, { "code": null, "e": 25647, "s": 25608, "text": "Let us consider the following example." }, { "code": null, "e": 25814, "s": 25647, "text": "{\n \"rules\": {\n \"users\": {\n \n \"$uid\": {\n \".write\": \"$uid === auth.uid\",\n \".read\": true\n }\n \n }\n }\n}" }, { "code": null, "e": 25876, "s": 25814, "text": "We can enforce data to string by using the following example." }, { "code": null, "e": 25979, "s": 25876, "text": "{\n \"rules\": {\n \n \"foo\": {\n \".validate\": \"newData.isString()\"\n }\n \n }\n}" }, { "code": null, "e": 26142, "s": 25979, "text": "This chapter only grabbed the surface of Firebase security rules. The important thing is to understand how these rules work, so you can combine it inside the app." }, { "code": null, "e": 26221, "s": 26142, "text": "In this chapter, we will show you how to host your app on the Firebase server." }, { "code": null, "e": 26337, "s": 26221, "text": "Before we begin, let us just add some text to index.html body tag. In this example, we will add the following text." }, { "code": null, "e": 26380, "s": 26337, "text": "<h1>WELCOME TO FIREBASE TUTORIALS APP</h1>" }, { "code": null, "e": 26453, "s": 26380, "text": "We need to install firebase tools globally in the command prompt window." }, { "code": null, "e": 26484, "s": 26453, "text": "npm install -g firebase-tools\n" }, { "code": null, "e": 26542, "s": 26484, "text": "First we need to login to Firebase in the command prompt." }, { "code": null, "e": 26558, "s": 26542, "text": "firebase login\n" }, { "code": null, "e": 26644, "s": 26558, "text": "Open the root folder of your app in the command prompt and run the following command." }, { "code": null, "e": 26659, "s": 26644, "text": "firebase init\n" }, { "code": null, "e": 26698, "s": 26659, "text": "This command will initialize your app." }, { "code": null, "e": 26928, "s": 26698, "text": "NOTE − If you have used a default configuration, the public folder will be created and the index.html inside this folder will be the starting point of your app. You can copy your app file inside the public folder as a workaround." }, { "code": null, "e": 27037, "s": 26928, "text": "This is the last step in this chapter. Run the following command from the command prompt to deploy your app." }, { "code": null, "e": 27054, "s": 27037, "text": "firebase deploy\n" }, { "code": null, "e": 27237, "s": 27054, "text": "After this step, the console will log your apps Firebase URL. In our case, it is called https://tutorialsfirebase.firebaseapp.com. We can run this link in the browser to see our app." }, { "code": null, "e": 27270, "s": 27237, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 27287, "s": 27270, "text": " University Code" }, { "code": null, "e": 27322, "s": 27287, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 27333, "s": 27322, "text": " Appeteria" }, { "code": null, "e": 27369, "s": 27333, "text": "\n 85 Lectures \n 14.5 hours \n" }, { "code": null, "e": 27380, "s": 27369, "text": " Appeteria" }, { "code": null, "e": 27415, "s": 27380, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 27432, "s": 27415, "text": " Gautham Vijayan" }, { "code": null, "e": 27467, "s": 27432, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 27482, "s": 27467, "text": " Nishant Kumar" }, { "code": null, "e": 27518, "s": 27482, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 27533, "s": 27518, "text": " Rahul Agarwal" }, { "code": null, "e": 27540, "s": 27533, "text": " Print" }, { "code": null, "e": 27551, "s": 27540, "text": " Add Notes" } ]
Java program to find common elements in three sorted arrays
The common elements in three sorted arrays are the elements that occur in all three of them. An example of this is given as follows − Array1 = 1 3 5 7 9 Array2 = 2 3 6 7 9 Array3 = 1 2 3 4 5 6 7 8 9 Common elements = 3 7 9 A program that demonstrates this is given as follows − public class Example { public static void main(String args[]) { int arr1[] = {1, 4, 25, 55, 78, 99}; int arr2[] = {2, 3, 4, 34, 55, 68, 75, 78, 100}; int arr3[] = {4, 55, 62, 78, 88, 98}; int i = 0, j = 0, k = 0, x = 0; System.out.print("Array1: "); for(x = 0; x < arr1.length; x++) { System.out.print(arr1[x] + " "); } System.out.print("\nArray2: "); for(x = 0; x < arr2.length; x++) { System.out.print(arr2[x] + " "); } System.out.print("\nArray3: "); for(x = 0; x < arr3.length; x++) { System.out.print(arr3[x] + " "); } System.out.print("\nThe common elements in the 3 sorted arrays are: "); while (i < arr1.length && j < arr2.length && k < arr3.length) { if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) { System.out.print(arr1[i] + " "); i++; j++; k++; }else if (arr1[i] < arr2[j]) { i++; }else if (arr2[j] < arr3[k]) { j++; }else { k++; } } } } Array1: 1 4 25 55 78 99 Array2: 2 3 4 34 55 68 75 78 100 Array3: 4 55 62 78 88 98 The common elements in the 3 sorted arrays are: 4 55 78
[ { "code": null, "e": 1196, "s": 1062, "text": "The common elements in three sorted arrays are the elements that occur in all three of them. An example of this is given as follows −" }, { "code": null, "e": 1285, "s": 1196, "text": "Array1 = 1 3 5 7 9\nArray2 = 2 3 6 7 9\nArray3 = 1 2 3 4 5 6 7 8 9\nCommon elements = 3 7 9" }, { "code": null, "e": 1340, "s": 1285, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 2189, "s": 1340, "text": "public class Example {\npublic static void main(String args[]) {\nint arr1[] = {1, 4, 25, 55, 78, 99};\nint arr2[] = {2, 3, 4, 34, 55, 68, 75, 78, 100};\nint arr3[] = {4, 55, 62, 78, 88, 98};\nint i = 0, j = 0, k = 0, x = 0;\nSystem.out.print(\"Array1: \");\nfor(x = 0; x < arr1.length; x++) {\nSystem.out.print(arr1[x] + \" \");\n}\nSystem.out.print(\"\\nArray2: \");\nfor(x = 0; x < arr2.length; x++) {\nSystem.out.print(arr2[x] + \" \");\n}\nSystem.out.print(\"\\nArray3: \");\nfor(x = 0; x < arr3.length; x++) {\nSystem.out.print(arr3[x] + \" \");\n}\nSystem.out.print(\"\\nThe common elements in the 3 sorted arrays are: \");\nwhile (i < arr1.length && j < arr2.length && k < arr3.length) {\nif (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {\nSystem.out.print(arr1[i] + \" \");\ni++;\nj++;\nk++;\n}else if (arr1[i] < arr2[j]) {\ni++;\n}else if (arr2[j] < arr3[k]) {\nj++;\n}else {\nk++;\n}\n}\n}\n}" }, { "code": null, "e": 2327, "s": 2189, "text": "Array1: 1 4 25 55 78 99\nArray2: 2 3 4 34 55 68 75 78 100\nArray3: 4 55 62 78 88 98\nThe common elements in the 3 sorted arrays are: 4 55 78" } ]
Get Started with C#
The easiest way to get started with C#, is to use an IDE. An IDE (Integrated Development Environment) is used to edit and compile code. In our tutorial, we will use Visual Studio Community, which is free to download from https://visualstudio.microsoft.com/vs/community/. Applications written in C# use the .NET Framework, so it makes sense to use Visual Studio, as the program, the framework, and the language, are all created by Microsoft. Once the Visual Studio Installer is downloaded and installed, choose the .NET workload and click on the Modify/Install button: After the installation is complete, click on the Launch button to get started with Visual Studio. On the start window, choose Create a new project: Then click on the "Install more tools and features" button: Choose "Console App (.NET Core)" from the list and click on the Next button: Enter a name for your project, and click on the Create button: Visual Studio will automatically generate some code for your project: The code should look something like this: using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } Try it Yourself » Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on how to run the code. Run the program by pressing the F5 button on your keyboard (or click on "Debug" -> "Start Debugging"). This will compile and execute your code. The result will look something to this: Congratulations! You have now written and executed your first C# program. When learning C# at W3Schools.com, you can use our "Try it Yourself" tool, which shows both the code and the result. This will make it easier for you to understand every part as we move forward: using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } Result: Try it Yourself » We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 58, "s": 0, "text": "The easiest way to get started with C#, is to use an IDE." }, { "code": null, "e": 136, "s": 58, "text": "An IDE (Integrated Development Environment) is used to edit and compile code." }, { "code": null, "e": 271, "s": 136, "text": "In our tutorial, we will use Visual Studio Community, which is free to download from https://visualstudio.microsoft.com/vs/community/." }, { "code": null, "e": 443, "s": 271, "text": "Applications written in C# use the .NET Framework, so it makes sense to use \nVisual Studio, as the program, the framework, and the language, are all created by \nMicrosoft." }, { "code": null, "e": 571, "s": 443, "text": "Once the Visual Studio Installer is downloaded and installed, choose the .NET workload and click on the \nModify/Install button:" }, { "code": null, "e": 669, "s": 571, "text": "After the installation is complete, click on the Launch button to get started with Visual Studio." }, { "code": null, "e": 719, "s": 669, "text": "On the start window, choose Create a new project:" }, { "code": null, "e": 779, "s": 719, "text": "Then click on the \"Install more tools and features\" button:" }, { "code": null, "e": 856, "s": 779, "text": "Choose \"Console App (.NET Core)\" from the list and click on the Next button:" }, { "code": null, "e": 919, "s": 856, "text": "Enter a name for your project, and click on the Create button:" }, { "code": null, "e": 989, "s": 919, "text": "Visual Studio will automatically generate some code for your project:" }, { "code": null, "e": 1031, "s": 989, "text": "The code should look something like this:" }, { "code": null, "e": 1188, "s": 1031, "text": "using System;\n\nnamespace HelloWorld\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(\"Hello World!\"); \n }\n }\n}" }, { "code": null, "e": 1208, "s": 1188, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1348, "s": 1208, "text": "Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on how to run the code." }, { "code": null, "e": 1532, "s": 1348, "text": "Run the program by pressing the F5 button on your keyboard (or click on \"Debug\" -> \"Start Debugging\"). This will compile and execute your code. The result will look something to this:" }, { "code": null, "e": 1606, "s": 1532, "text": "Congratulations! You have now written and executed your first C# program." }, { "code": null, "e": 1802, "s": 1606, "text": "When learning C# at W3Schools.com, you can use our \"Try it Yourself\" tool, which shows both the code and the result. This will make it easier for \nyou to understand every part as we move forward:" }, { "code": null, "e": 1959, "s": 1802, "text": "using System;\n\nnamespace HelloWorld\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(\"Hello World!\"); \n }\n }\n}" }, { "code": null, "e": 1967, "s": 1959, "text": "Result:" }, { "code": null, "e": 1987, "s": 1967, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2020, "s": 1987, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2062, "s": 2020, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2169, "s": 2062, "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": 2188, "s": 2169, "text": "help@w3schools.com" } ]
What does the two question marks together (??) mean in C#?
It is the null-coalescing operator. The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the lefthand operand evaluates to non-null. A nullable type can represent a value that can be undefined or from the type's domain. We can use the ?? operator to return an appropriate value when the left operand has a nullable type. If we try to assign a nullable value type to a non-nullable value type without using the ?? operator, we will get a compile-time error and if we forcefully cast it, an InvalidOperationException exception will be thrown. The following are the advantages of the Null-Coalescing Operator (??) operator − It is used to define a default value for a nullable item (for both value types and reference types). It is used to define a default value for a nullable item (for both value types and reference types). It prevents the runtime InvalidOperationException exception. It prevents the runtime InvalidOperationException exception. It helps us to remove many redundant "if" conditions. It helps us to remove many redundant "if" conditions. It works for both reference types and value types. It works for both reference types and value types. The code becomes well-organized and readable. The code becomes well-organized and readable. Live Demo using System; namespace MyApplication{ class Program{ static void Main(string[] args){ int? value1 = null; int value2 = value1 ?? 99; Console.WriteLine("Value2: " + value2); string testString = "Null Coalescing"; string resultString = testString ?? "Original string is null"; Console.WriteLine("The value of result message is: " + resultString); } } } The output of the above example is as follows. Value2: 99 The value of result message is: Null Coalescing
[ { "code": null, "e": 1365, "s": 1062, "text": "It is the null-coalescing operator. The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the lefthand operand evaluates to non-null." }, { "code": null, "e": 1773, "s": 1365, "text": "A nullable type can represent a value that can be undefined or from the type's domain. We can use the ?? operator to return an appropriate value when the left operand has a nullable type. If we try to assign a nullable value type to a non-nullable value type without using the ?? operator, we will get a compile-time error and if we forcefully cast it, an InvalidOperationException exception will be thrown." }, { "code": null, "e": 1854, "s": 1773, "text": "The following are the advantages of the Null-Coalescing Operator (??) operator −" }, { "code": null, "e": 1955, "s": 1854, "text": "It is used to define a default value for a nullable item (for both value types and reference types)." }, { "code": null, "e": 2056, "s": 1955, "text": "It is used to define a default value for a nullable item (for both value types and reference types)." }, { "code": null, "e": 2117, "s": 2056, "text": "It prevents the runtime InvalidOperationException exception." }, { "code": null, "e": 2178, "s": 2117, "text": "It prevents the runtime InvalidOperationException exception." }, { "code": null, "e": 2232, "s": 2178, "text": "It helps us to remove many redundant \"if\" conditions." }, { "code": null, "e": 2286, "s": 2232, "text": "It helps us to remove many redundant \"if\" conditions." }, { "code": null, "e": 2337, "s": 2286, "text": "It works for both reference types and value types." }, { "code": null, "e": 2388, "s": 2337, "text": "It works for both reference types and value types." }, { "code": null, "e": 2434, "s": 2388, "text": "The code becomes well-organized and readable." }, { "code": null, "e": 2480, "s": 2434, "text": "The code becomes well-organized and readable." }, { "code": null, "e": 2491, "s": 2480, "text": " Live Demo" }, { "code": null, "e": 2915, "s": 2491, "text": "using System;\nnamespace MyApplication{\n class Program{\n static void Main(string[] args){\n int? value1 = null;\n int value2 = value1 ?? 99;\n Console.WriteLine(\"Value2: \" + value2);\n string testString = \"Null Coalescing\";\n string resultString = testString ?? \"Original string is null\";\n Console.WriteLine(\"The value of result message is: \" + resultString);\n }\n }\n}" }, { "code": null, "e": 2962, "s": 2915, "text": "The output of the above example is as follows." }, { "code": null, "e": 3021, "s": 2962, "text": "Value2: 99\nThe value of result message is: Null Coalescing" } ]
Method and Block Synchronization in Java
When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file. So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Following is the general form of the synchronized statement. synchronized(objectidentifier) { // Access shared variables and other shared resources } Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples, where we will print a counter using two different threads. When threads are not synchronized, they print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads. Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces a different result based on CPU availability to a thread. Live Demo class PrintDemo extends Thread { public void printCount() { try { for(int i = 5; i > 0; i--) { System.out.println("Counter --- " + i ); } } catch (Exception e) { System.out.println("Thread " + Thread.currentThread().getName()+" interrupted."); } } public void run() { printCount(); System.out.println("Thread " + Thread.currentThread().getName() + " exiting."); } } public class TestThread { public static void main(String args[]) { PrintDemo PD = new PrintDemo(); Thread t1 = new Thread(PD ); Thread t2 = new Thread(PD ); t1.start(); t2.start(); // wait for threads to end try { t1.join(); t2.join(); } catch ( Exception e) { System.out.println("Interrupted"); } } } This produces a different result every time you run this program. Counter --- 5 Counter --- 5 Counter --- 4 Counter --- 4 Counter --- 3 Counter --- 3 Counter --- 2 Counter --- 2 Counter --- 1 Counter --- 1 Thread Thread-1 exiting. Thread Thread-2 exiting. Here is the same example which prints counter value in sequence and every time we run it, it produces the same result. W've put synchronized keyword over a block so that counter increment code is now locked as per the object during method execution. We're using current object as lock which we're passing in the synchronized block as parameter. Live Demo class PrintDemo extends Thread { public void printCount() { try { for(int i = 5; i > 0; i--) { System.out.println("Counter --- " + i ); } } catch (Exception e) { System.out.println("Thread " + Thread.currentThread().getName()+" interrupted."); } } public void run() { synchronized(this) { printCount(); } System.out.println("Thread " + Thread.currentThread().getName() + " exiting."); } } public class TestThread { public static void main(String args[]) { PrintDemo PD = new PrintDemo(); Thread t1 = new Thread(PD ); Thread t2 = new Thread(PD ); t1.start(); t2.start(); // wait for threads to end try { t1.join(); t2.join(); } catch ( Exception e) { System.out.println("Interrupted"); } } } This produces the same result every time you run this program. Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread-2 exiting. Thread Thread-1 exiting. Here is the same example which prints counter value in sequence and every time we run it, it produces the same result. W've put synchronized keyword over a method this time so that complete method is locked as per the object during method execution. Live Demo class PrintDemo extends Thread { public void printCount() { try { for(int i = 5; i > 0; i--) { System.out.println("Counter --- " + i ); } } catch (Exception e) { System.out.println("Thread " + Thread.currentThread().getName()+" interrupted."); } } public synchronized void run() { printCount(); System.out.println("Thread " + Thread.currentThread().getName() + " exiting."); } } public class TestThread { public static void main(String args[]) { PrintDemo PD = new PrintDemo(); Thread t1 = new Thread(PD ); Thread t2 = new Thread(PD ); t1.start(); t2.start(); // wait for threads to end try { t1.join(); t2.join(); } catch ( Exception e) { System.out.println("Interrupted"); } } } This produces the same result every time you run this program. Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread-1 exiting. Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread-2 exiting.
[ { "code": null, "e": 1517, "s": 1062, "text": "When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file." }, { "code": null, "e": 1861, "s": 1517, "text": "So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor." }, { "code": null, "e": 2098, "s": 1861, "text": "Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Following is the general form of the synchronized statement." }, { "code": null, "e": 2190, "s": 2098, "text": "synchronized(objectidentifier) {\n // Access shared variables and other shared resources\n}" }, { "code": null, "e": 2644, "s": 2190, "text": "Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples, where we will print a counter using two different threads. When threads are not synchronized, they print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads." }, { "code": null, "e": 2818, "s": 2644, "text": "Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces a different result based on CPU availability to a thread." }, { "code": null, "e": 2829, "s": 2818, "text": " Live Demo" }, { "code": null, "e": 3665, "s": 2829, "text": "class PrintDemo extends Thread {\n public void printCount() {\n try {\n for(int i = 5; i > 0; i--) {\n System.out.println(\"Counter --- \" + i );\n }\n } catch (Exception e) {\n System.out.println(\"Thread \" + Thread.currentThread().getName()+\" interrupted.\");\n }\n }\n public void run() {\n printCount();\n System.out.println(\"Thread \" + Thread.currentThread().getName() + \" exiting.\");\n }\n}\npublic class TestThread {\n public static void main(String args[]) {\n PrintDemo PD = new PrintDemo();\n Thread t1 = new Thread(PD );\n Thread t2 = new Thread(PD );\n t1.start();\n t2.start();\n // wait for threads to end\n try {\n t1.join();\n t2.join();\n } catch ( Exception e) {\n System.out.println(\"Interrupted\");\n }\n }\n}" }, { "code": null, "e": 3731, "s": 3665, "text": "This produces a different result every time you run this program." }, { "code": null, "e": 3921, "s": 3731, "text": "Counter --- 5\nCounter --- 5\nCounter --- 4\nCounter --- 4\nCounter --- 3\nCounter --- 3\nCounter --- 2\nCounter --- 2\nCounter --- 1\nCounter --- 1\nThread Thread-1 exiting.\nThread Thread-2 exiting." }, { "code": null, "e": 4266, "s": 3921, "text": "Here is the same example which prints counter value in sequence and every time we run it, it produces the same result. W've put synchronized keyword over a block so that counter increment code is now locked as per the object during method execution. We're using current object as lock which we're passing in the synchronized block as parameter." }, { "code": null, "e": 4277, "s": 4266, "text": " Live Demo" }, { "code": null, "e": 5151, "s": 4277, "text": "class PrintDemo extends Thread {\n public void printCount() {\n try {\n for(int i = 5; i > 0; i--) {\n System.out.println(\"Counter --- \" + i );\n }\n } catch (Exception e) {\n System.out.println(\"Thread \" + Thread.currentThread().getName()+\" interrupted.\");\n }\n }\n public void run() {\n synchronized(this) {\n printCount();\n }\n System.out.println(\"Thread \" + Thread.currentThread().getName() + \" exiting.\");\n }\n}\npublic class TestThread {\n public static void main(String args[]) {\n PrintDemo PD = new PrintDemo();\n Thread t1 = new Thread(PD );\n Thread t2 = new Thread(PD );\n t1.start();\n t2.start();\n // wait for threads to end\n try {\n t1.join();\n t2.join();\n } catch ( Exception e) {\n System.out.println(\"Interrupted\");\n }\n }\n}" }, { "code": null, "e": 5214, "s": 5151, "text": "This produces the same result every time you run this program." }, { "code": null, "e": 5404, "s": 5214, "text": "Counter --- 5\nCounter --- 4\nCounter --- 3\nCounter --- 2\nCounter --- 1\nCounter --- 5\nCounter --- 4\nCounter --- 3\nCounter --- 2\nCounter --- 1\nThread Thread-2 exiting.\nThread Thread-1 exiting." }, { "code": null, "e": 5654, "s": 5404, "text": "Here is the same example which prints counter value in sequence and every time we run it, it produces the same result. W've put synchronized keyword over a method this time so that complete method is locked as per the object during method execution." }, { "code": null, "e": 5665, "s": 5654, "text": " Live Demo" }, { "code": null, "e": 6514, "s": 5665, "text": "class PrintDemo extends Thread {\n public void printCount() {\n try {\n for(int i = 5; i > 0; i--) {\n System.out.println(\"Counter --- \" + i );\n }\n } catch (Exception e) {\n System.out.println(\"Thread \" + Thread.currentThread().getName()+\" interrupted.\");\n }\n }\n public synchronized void run() {\n printCount();\n System.out.println(\"Thread \" + Thread.currentThread().getName() + \" exiting.\");\n }\n}\npublic class TestThread {\n public static void main(String args[]) {\n PrintDemo PD = new PrintDemo();\n Thread t1 = new Thread(PD );\n Thread t2 = new Thread(PD );\n t1.start();\n t2.start();\n // wait for threads to end\n try {\n t1.join();\n t2.join();\n } catch ( Exception e) {\n System.out.println(\"Interrupted\");\n }\n }\n}" }, { "code": null, "e": 6577, "s": 6514, "text": "This produces the same result every time you run this program." }, { "code": null, "e": 6767, "s": 6577, "text": "Counter --- 5\nCounter --- 4\nCounter --- 3\nCounter --- 2\nCounter --- 1\nThread Thread-1 exiting.\nCounter --- 5\nCounter --- 4\nCounter --- 3\nCounter --- 2\nCounter --- 1\nThread Thread-2 exiting." } ]
Using Non-negative matrix factorization to classify companies. | by Christophe GEISSLER | Towards Data Science
Companies are complex entities that evolve over time. As a data-scientist involved in investment, I have long been asking myself the question of evaluating the most appropriate dimension for modeling enterprise data: in what space do these things live? No better answer could be found than this one: “Far too many!”. Another formulation of the question is to ask how many independent criteria are sufficient to characterize a company. As an example of criteria, we can think of market capitalization, industrial sector, number of employees, level of current earnings, carbon footprint, opinion of financial analysts, and much more: the number of available criteria easily exceeds one hundred. These criteria are not independent but, on the contrary, linked by a whole network of implicit correlations. This makes the choice of relevant subsets of variables a very hard task. Investment practitioners apply machine learning to these data in two main ways: To predict, by means of more or less complex regressions, the future behavior of a company — generally the evolution of its stock market value — from historical data on its different criteria. This is supervised learning. To automatically group companies into homogeneous aggregates, and thus be able to compare these companies with their neighbors, without proper labels: this exercise is called unsupervised learning. An example of an aggregate very frequently used by the financial industry is the notion of industrial sector. These two exercises — grouping and prediction — pursue different goals, but both are all the more difficult and unstable in their implementation, as more criteria are used. This is one of the manifestations of the well-known phenomenon in statistical learning, known as the ‘curse of dimensionality’. Hence the natural need to reduce the size of the problem by reducing the number of criteria used. Easier said than done. It’s even more difficult to achieve in practice if we add an interpretability constraint. In this article, we will see how the non-negative factorization algorithm (NMF) allows to get closer to these two objectives. Let’s now formalize the problem a bit. Suppose that the available data are represented by an X matrix of type (n,f), i.e. n rows and f columns. We assume that these data are positive or null and bounded — this assumption can be relaxed but that is the spirit. A non-negative factorization of X is an approximation of X by a decomposition of type: with W of type (n,c) and H of type (f,c), subject to the constraints W ≥ 0, H ≥ 0.Some important points to keep in mind: This decomposition is an approximation, not an equality. The solution W and H matrices minimize the quadratic error between the real data X and their approximation X^. The decomposition is not necessarily unique, even with the positivity constraint. One can indeed make unit change matrices in the form of positive diagonal D matrices, and then obtain identical decompositions in the form: c ≤ min(n,f) is an integer representing the number of selected components. As in K-Means clustering methods, this parameter represents a parametric degree of freedom of the method. Determining the optimal number of components requires an additional criterion. It is common in the literature to refer to lines of W matrix as factors. A nice introduction to NMF can be found here [5]. It is usual to consider the lines of X as n observations of objects of the same category (eg customers, patients, companies, etc). Each object has f attributes, and the data contained in the matrix correspond to the values taken by the attributes for the corresponding objects. The main effect of this decomposition is to decrease the information necessary to describe an observation. The original observations of the X matrix can be recovered, at the cost of an approximation, as linear combinations with positive coefficients — the lines of the H matrix. A reduction in size has thus been achieved: part of the information contained in the original matrix, comprising f data per individual, can be approximately summarized by a smaller set of c data per individual. Another interesting effect of the non-negative decomposition is the emergence of a natural clustering of observations and attributes. The underlying mathematical principles would take us too far in this paper, but you can find a very clear presentation in this article [2]. Intuitively, observations can be clustered according to the dominant factor, i.e. the factor among the c factors having the highest value. In the same way, the original features can be grouped according to the factor on which they have the greatest influence. This natural possibility of clustering is closely linked to the condition of positivity of the coefficients. This is an important difference with Principal Component Analysis (PCA), where the factors are required to be orthogonal in pairs, which makes it impossible to control the sign of the coefficients. The collection and publication of extra-financial corporate data for investors is an industry in its own right, whose players are rating agencies. Each agency has its own criteria and its own rating methodology, but a large number of criteria can be found from one agency to another. We are interested here in data characterizing the behavior of companies according to the three main pillars of environment (E), social (S) and governance (G). These data are called behavioural scores. They score, on a scale of 0 to 100, the company’s performance according to criteria such as equal pay for men and women, the proportion of independent directors in the board, water pollution, carbon footprint and many others. These scores are generally reviewed between one and two times a year by the agencies, mainly on a declarative basis by the companies. We will use the information contained in these scores for: Determine homogeneous groups of companies based on more intrinsic information than the industry sector, Group variables in clusters in order to reduce the number of influencing factors. The data used in this article are 77 behavioral scores from Vigeo-Eiris research, a subsidiary of the Moody’s rating agency specializing in extra-financial rating of global listed companies. The numerical experience we present here is based on the scores of the 500 largest European stocks, evaluated on average over the period September 2011– June 2020. Vigeo’s behavioural scores are grouped into 6 areas: Environment Corporate Governance Social: Business Behaviour Social: Human rights Social: Human Resources Social: Community involvement More elements about the scoring methodology can be found here. The variety and granularity of this data makes it possible to envisage a more relevant grouping of companies than one based simply on the industrial sector. We will test this hypothesis by applying an NMF to the score data. Behavioural scores are not known for all actions in all sectors and therefore the series have missing values. The scores on the leftmost side of the graph have 100% fill rates. This is the case, for example, for scores related to Business behaviour (starting with C_S) or Corporate Governance (starting with C_G). On the other hand, highly specialized scores such as the treatment of local pollution (named EnV2_6) have the lowest fill rate, which can go down to 0 for some sectors where the topic has low relevance (Finance, Real Estate). Like a vast variety of methods based on matrix algebra, NMF does not tolerate missing data. We will therefore replace the missing values of each score in the original matrix by the average of this same score, taken over all the companies for which this score is filled in. We are now almost ready to launch an NMF decomposition. All we have to do now is to choose a value for parameter c. We know very little a priori about the optimal values of this parameter, but we expect the following scheme to be true: Small values of c ==>Data-saving and imprecise model, Large values of c ==> Data intensive and more accurate model. This principle will help us to define an objective function integrating the notions of sparsity, stability and precision. Those concepts are indeed key ingredients for the interpretability of a predictive system, as explained here [3],[4]. For the sake of simplicity, we will leave stability aside in this article, and focus onto sparsity and precision. To quantify sparsity, let us observe that the initial matrix of size (n,f) has been replaced by two matrices of respective sizes (n, c) and (c, f)). We can therefore define a sparsity score given by the following formula: This score will of course be minimal for c = 1, in the theoretical case where all observations would be roughly multiples of a single vector. To quantify precision, it is natural to define the precision score err(c) analogous to the R2 of linear regressions, by the following formula: We can finally define an interpretability score by combining precision and sparsity: This score is a number between 0 and 1, with the convention that 0 is the best possible level for interpretability, and 1 the worst level. The score is calibrated to be 100% maximum when c = 1 or c = c*; the constant c* plays the role of a maximum acceptable number of dimensions, set here at 20. Here are a few lines of code you will have to write compute an NMF decomposition for a given dimension c: >>> import numpy as np>>> import pandas as pd>>> from sklearn.decomposition import NMF>>> X = pd.read_csv (scores_file_path) # reading the score data>>> c = 4>>> model = NMF(n_components=c, init='random', random_state=0)>>> W = model.fit_transform(X)>>> H = model.components_>>> err = model.reconstruction_err_ The matrix H and W are the main outputs of the calculation, they are needed to rebuild the approximating matrix and the error function err(c). The graph below is obtained by plotting the values of sp(c), err(c) and InterpScore(c). This graph clearly shows the trade-off between precision and parsimony, with a sharp decrease for c ranging between 2 and 6, followed by a slow, then accelerating increase for larger values of c. In the following, and for the sake of the example, we retain the value c=6 for the number of components. The most visible benefit that we get from the non-negative factorization is the replacement of the initial 77 features by a reduced subset of 6 positive linear combinations, the meta-features. This graph shows the distribution of the coefficients (the ‘loadings’) of the 6 new meta-features over the initial 77 features. As expected, these coefficients are spread over several features and the linear combination can be difficult to interpret. This is specially true of meta-feature #1, the coefficients being more and more concentrated as the rank of the meta-feature increases. This array shows the 6 most influent features of each meta-feature. Interestingly, the topics of these influent features are inter-related. We can therefore assign a main theme to each meta-feature. For example, the story told by feature V1 is mostly about Human Rights (hrts) and Human Resources (hr), while V4 speaks clearly about Environment (env). NMF has traded dimension and interpretability, by drastically lowering the dimension (from 77 to 6) at the price of getting more fuzzy, but still meaningful features. Interestingly, the symmetrical formulation of NMF also provides a natural way to group all companies into 6 possible clusters: we simply assign cluster #i to a stock when its largest value is in column i, i.e when its highest score is on the meta-feature #i. Let us take a look on how this new way of grouping companies corresponds to the usual sectors: The NMF-based clustering brings information that is not contained in the sole sectors. We can read each line of the previous graph as a ‘signature’ of each sector along the various meta-features. For example, the Energy sector is among the lowest scores on the meta-feature #4, associated to the Environment theme. Remember we have started with an X matrix that contained missing data. We have filled the empty cells with the global means of each columns, and fed our NMF algo with the resulting filled matrix. Now that we have a clustering of the stocks, why don’t we try to improve the filling of missing data by replacing empty cells by the average of each column, taken over stocks of the same clusters, instead of all stocks? This will provide a new estimate of X, that can be in turn used as input for the factorization. And so on and so forth... The lines clustering provided by the NMF allows to interpolate the missing values of the data matrix with an improved precision, compared to what can be obtained from mean-based priors. This method is very useful in many domains, the main advantage being the independence with respect to an exogeneous clustering like sectors: is it completely data-driven. This paper tends to illustrate and support how non-negative matrix factorization may be used as a powerful tool to create natural groups of observations and features. This had long been recognized in life sciences, especially in genomics, where the need to reduce the number of features and keep the analysis interpretable at the same time, is crucial. Applying NMF on extra-financial data is an innovative way of extracting the valuable information contained in these datasets. We have used the data of a particular provider — Vigeo-Eiris-, but the good news is that this method will be extremely robust when using multiple sources of data, to exhibit fundamental attributes of companies. [1] Ding, C.H.Q.; Tao, L.; Jordan, M.I. Convex and Semi-Nonnegative Matrix Factorizations (2010). IEEE Trans. PatternAnal. Mach. Intelli. Arch. 2010, 32, 44–55. [2] P.Fogel, Y. Gaston-Mathé et al., Applications of a Novel Clustering Approach Using Non-Negative Matrix Factorization to EnvironmentalResearch in Public Health (2016), International Journal of Environmental Research and Public Health. [3] B. Yu and K. Kumbier, Three principles of data science: predictability, computability, and stability (pcs) (2019), arXiv preprint arXiv:1901.08152. [4] V. Margot. A rigorous method to compare interpretability (2020), arXiv preprint arXiv:2004.01570. [5] Vigeo-Eiris, website (2020)
[ { "code": null, "e": 1046, "s": 171, "text": "Companies are complex entities that evolve over time. As a data-scientist involved in investment, I have long been asking myself the question of evaluating the most appropriate dimension for modeling enterprise data: in what space do these things live? No better answer could be found than this one: “Far too many!”. Another formulation of the question is to ask how many independent criteria are sufficient to characterize a company. As an example of criteria, we can think of market capitalization, industrial sector, number of employees, level of current earnings, carbon footprint, opinion of financial analysts, and much more: the number of available criteria easily exceeds one hundred. These criteria are not independent but, on the contrary, linked by a whole network of implicit correlations. This makes the choice of relevant subsets of variables a very hard task." }, { "code": null, "e": 1126, "s": 1046, "text": "Investment practitioners apply machine learning to these data in two main ways:" }, { "code": null, "e": 1348, "s": 1126, "text": "To predict, by means of more or less complex regressions, the future behavior of a company — generally the evolution of its stock market value — from historical data on its different criteria. This is supervised learning." }, { "code": null, "e": 1656, "s": 1348, "text": "To automatically group companies into homogeneous aggregates, and thus be able to compare these companies with their neighbors, without proper labels: this exercise is called unsupervised learning. An example of an aggregate very frequently used by the financial industry is the notion of industrial sector." }, { "code": null, "e": 1957, "s": 1656, "text": "These two exercises — grouping and prediction — pursue different goals, but both are all the more difficult and unstable in their implementation, as more criteria are used. This is one of the manifestations of the well-known phenomenon in statistical learning, known as the ‘curse of dimensionality’." }, { "code": null, "e": 2168, "s": 1957, "text": "Hence the natural need to reduce the size of the problem by reducing the number of criteria used. Easier said than done. It’s even more difficult to achieve in practice if we add an interpretability constraint." }, { "code": null, "e": 2294, "s": 2168, "text": "In this article, we will see how the non-negative factorization algorithm (NMF) allows to get closer to these two objectives." }, { "code": null, "e": 2333, "s": 2294, "text": "Let’s now formalize the problem a bit." }, { "code": null, "e": 2554, "s": 2333, "text": "Suppose that the available data are represented by an X matrix of type (n,f), i.e. n rows and f columns. We assume that these data are positive or null and bounded — this assumption can be relaxed but that is the spirit." }, { "code": null, "e": 2641, "s": 2554, "text": "A non-negative factorization of X is an approximation of X by a decomposition of type:" }, { "code": null, "e": 2762, "s": 2641, "text": "with W of type (n,c) and H of type (f,c), subject to the constraints W ≥ 0, H ≥ 0.Some important points to keep in mind:" }, { "code": null, "e": 2930, "s": 2762, "text": "This decomposition is an approximation, not an equality. The solution W and H matrices minimize the quadratic error between the real data X and their approximation X^." }, { "code": null, "e": 3152, "s": 2930, "text": "The decomposition is not necessarily unique, even with the positivity constraint. One can indeed make unit change matrices in the form of positive diagonal D matrices, and then obtain identical decompositions in the form:" }, { "code": null, "e": 3412, "s": 3152, "text": "c ≤ min(n,f) is an integer representing the number of selected components. As in K-Means clustering methods, this parameter represents a parametric degree of freedom of the method. Determining the optimal number of components requires an additional criterion." }, { "code": null, "e": 3485, "s": 3412, "text": "It is common in the literature to refer to lines of W matrix as factors." }, { "code": null, "e": 3535, "s": 3485, "text": "A nice introduction to NMF can be found here [5]." }, { "code": null, "e": 3813, "s": 3535, "text": "It is usual to consider the lines of X as n observations of objects of the same category (eg customers, patients, companies, etc). Each object has f attributes, and the data contained in the matrix correspond to the values taken by the attributes for the corresponding objects." }, { "code": null, "e": 4303, "s": 3813, "text": "The main effect of this decomposition is to decrease the information necessary to describe an observation. The original observations of the X matrix can be recovered, at the cost of an approximation, as linear combinations with positive coefficients — the lines of the H matrix. A reduction in size has thus been achieved: part of the information contained in the original matrix, comprising f data per individual, can be approximately summarized by a smaller set of c data per individual." }, { "code": null, "e": 4837, "s": 4303, "text": "Another interesting effect of the non-negative decomposition is the emergence of a natural clustering of observations and attributes. The underlying mathematical principles would take us too far in this paper, but you can find a very clear presentation in this article [2]. Intuitively, observations can be clustered according to the dominant factor, i.e. the factor among the c factors having the highest value. In the same way, the original features can be grouped according to the factor on which they have the greatest influence." }, { "code": null, "e": 5144, "s": 4837, "text": "This natural possibility of clustering is closely linked to the condition of positivity of the coefficients. This is an important difference with Principal Component Analysis (PCA), where the factors are required to be orthogonal in pairs, which makes it impossible to control the sign of the coefficients." }, { "code": null, "e": 5428, "s": 5144, "text": "The collection and publication of extra-financial corporate data for investors is an industry in its own right, whose players are rating agencies. Each agency has its own criteria and its own rating methodology, but a large number of criteria can be found from one agency to another." }, { "code": null, "e": 5855, "s": 5428, "text": "We are interested here in data characterizing the behavior of companies according to the three main pillars of environment (E), social (S) and governance (G). These data are called behavioural scores. They score, on a scale of 0 to 100, the company’s performance according to criteria such as equal pay for men and women, the proportion of independent directors in the board, water pollution, carbon footprint and many others." }, { "code": null, "e": 6048, "s": 5855, "text": "These scores are generally reviewed between one and two times a year by the agencies, mainly on a declarative basis by the companies. We will use the information contained in these scores for:" }, { "code": null, "e": 6152, "s": 6048, "text": "Determine homogeneous groups of companies based on more intrinsic information than the industry sector," }, { "code": null, "e": 6234, "s": 6152, "text": "Group variables in clusters in order to reduce the number of influencing factors." }, { "code": null, "e": 6589, "s": 6234, "text": "The data used in this article are 77 behavioral scores from Vigeo-Eiris research, a subsidiary of the Moody’s rating agency specializing in extra-financial rating of global listed companies. The numerical experience we present here is based on the scores of the 500 largest European stocks, evaluated on average over the period September 2011– June 2020." }, { "code": null, "e": 6642, "s": 6589, "text": "Vigeo’s behavioural scores are grouped into 6 areas:" }, { "code": null, "e": 6654, "s": 6642, "text": "Environment" }, { "code": null, "e": 6675, "s": 6654, "text": "Corporate Governance" }, { "code": null, "e": 6702, "s": 6675, "text": "Social: Business Behaviour" }, { "code": null, "e": 6723, "s": 6702, "text": "Social: Human rights" }, { "code": null, "e": 6747, "s": 6723, "text": "Social: Human Resources" }, { "code": null, "e": 6777, "s": 6747, "text": "Social: Community involvement" }, { "code": null, "e": 6840, "s": 6777, "text": "More elements about the scoring methodology can be found here." }, { "code": null, "e": 7064, "s": 6840, "text": "The variety and granularity of this data makes it possible to envisage a more relevant grouping of companies than one based simply on the industrial sector. We will test this hypothesis by applying an NMF to the score data." }, { "code": null, "e": 7174, "s": 7064, "text": "Behavioural scores are not known for all actions in all sectors and therefore the series have missing values." }, { "code": null, "e": 7604, "s": 7174, "text": "The scores on the leftmost side of the graph have 100% fill rates. This is the case, for example, for scores related to Business behaviour (starting with C_S) or Corporate Governance (starting with C_G). On the other hand, highly specialized scores such as the treatment of local pollution (named EnV2_6) have the lowest fill rate, which can go down to 0 for some sectors where the topic has low relevance (Finance, Real Estate)." }, { "code": null, "e": 7877, "s": 7604, "text": "Like a vast variety of methods based on matrix algebra, NMF does not tolerate missing data. We will therefore replace the missing values of each score in the original matrix by the average of this same score, taken over all the companies for which this score is filled in." }, { "code": null, "e": 8113, "s": 7877, "text": "We are now almost ready to launch an NMF decomposition. All we have to do now is to choose a value for parameter c. We know very little a priori about the optimal values of this parameter, but we expect the following scheme to be true:" }, { "code": null, "e": 8167, "s": 8113, "text": "Small values of c ==>Data-saving and imprecise model," }, { "code": null, "e": 8229, "s": 8167, "text": "Large values of c ==> Data intensive and more accurate model." }, { "code": null, "e": 8583, "s": 8229, "text": "This principle will help us to define an objective function integrating the notions of sparsity, stability and precision. Those concepts are indeed key ingredients for the interpretability of a predictive system, as explained here [3],[4]. For the sake of simplicity, we will leave stability aside in this article, and focus onto sparsity and precision." }, { "code": null, "e": 8805, "s": 8583, "text": "To quantify sparsity, let us observe that the initial matrix of size (n,f) has been replaced by two matrices of respective sizes (n, c) and (c, f)). We can therefore define a sparsity score given by the following formula:" }, { "code": null, "e": 8947, "s": 8805, "text": "This score will of course be minimal for c = 1, in the theoretical case where all observations would be roughly multiples of a single vector." }, { "code": null, "e": 9090, "s": 8947, "text": "To quantify precision, it is natural to define the precision score err(c) analogous to the R2 of linear regressions, by the following formula:" }, { "code": null, "e": 9175, "s": 9090, "text": "We can finally define an interpretability score by combining precision and sparsity:" }, { "code": null, "e": 9314, "s": 9175, "text": "This score is a number between 0 and 1, with the convention that 0 is the best possible level for interpretability, and 1 the worst level." }, { "code": null, "e": 9472, "s": 9314, "text": "The score is calibrated to be 100% maximum when c = 1 or c = c*; the constant c* plays the role of a maximum acceptable number of dimensions, set here at 20." }, { "code": null, "e": 9578, "s": 9472, "text": "Here are a few lines of code you will have to write compute an NMF decomposition for a given dimension c:" }, { "code": null, "e": 9890, "s": 9578, "text": ">>> import numpy as np>>> import pandas as pd>>> from sklearn.decomposition import NMF>>> X = pd.read_csv (scores_file_path) # reading the score data>>> c = 4>>> model = NMF(n_components=c, init='random', random_state=0)>>> W = model.fit_transform(X)>>> H = model.components_>>> err = model.reconstruction_err_" }, { "code": null, "e": 10033, "s": 9890, "text": "The matrix H and W are the main outputs of the calculation, they are needed to rebuild the approximating matrix and the error function err(c)." }, { "code": null, "e": 10121, "s": 10033, "text": "The graph below is obtained by plotting the values of sp(c), err(c) and InterpScore(c)." }, { "code": null, "e": 10422, "s": 10121, "text": "This graph clearly shows the trade-off between precision and parsimony, with a sharp decrease for c ranging between 2 and 6, followed by a slow, then accelerating increase for larger values of c. In the following, and for the sake of the example, we retain the value c=6 for the number of components." }, { "code": null, "e": 10615, "s": 10422, "text": "The most visible benefit that we get from the non-negative factorization is the replacement of the initial 77 features by a reduced subset of 6 positive linear combinations, the meta-features." }, { "code": null, "e": 11002, "s": 10615, "text": "This graph shows the distribution of the coefficients (the ‘loadings’) of the 6 new meta-features over the initial 77 features. As expected, these coefficients are spread over several features and the linear combination can be difficult to interpret. This is specially true of meta-feature #1, the coefficients being more and more concentrated as the rank of the meta-feature increases." }, { "code": null, "e": 11354, "s": 11002, "text": "This array shows the 6 most influent features of each meta-feature. Interestingly, the topics of these influent features are inter-related. We can therefore assign a main theme to each meta-feature. For example, the story told by feature V1 is mostly about Human Rights (hrts) and Human Resources (hr), while V4 speaks clearly about Environment (env)." }, { "code": null, "e": 11521, "s": 11354, "text": "NMF has traded dimension and interpretability, by drastically lowering the dimension (from 77 to 6) at the price of getting more fuzzy, but still meaningful features." }, { "code": null, "e": 11875, "s": 11521, "text": "Interestingly, the symmetrical formulation of NMF also provides a natural way to group all companies into 6 possible clusters: we simply assign cluster #i to a stock when its largest value is in column i, i.e when its highest score is on the meta-feature #i. Let us take a look on how this new way of grouping companies corresponds to the usual sectors:" }, { "code": null, "e": 12190, "s": 11875, "text": "The NMF-based clustering brings information that is not contained in the sole sectors. We can read each line of the previous graph as a ‘signature’ of each sector along the various meta-features. For example, the Energy sector is among the lowest scores on the meta-feature #4, associated to the Environment theme." }, { "code": null, "e": 12386, "s": 12190, "text": "Remember we have started with an X matrix that contained missing data. We have filled the empty cells with the global means of each columns, and fed our NMF algo with the resulting filled matrix." }, { "code": null, "e": 12728, "s": 12386, "text": "Now that we have a clustering of the stocks, why don’t we try to improve the filling of missing data by replacing empty cells by the average of each column, taken over stocks of the same clusters, instead of all stocks? This will provide a new estimate of X, that can be in turn used as input for the factorization. And so on and so forth..." }, { "code": null, "e": 13085, "s": 12728, "text": "The lines clustering provided by the NMF allows to interpolate the missing values of the data matrix with an improved precision, compared to what can be obtained from mean-based priors. This method is very useful in many domains, the main advantage being the independence with respect to an exogeneous clustering like sectors: is it completely data-driven." }, { "code": null, "e": 13438, "s": 13085, "text": "This paper tends to illustrate and support how non-negative matrix factorization may be used as a powerful tool to create natural groups of observations and features. This had long been recognized in life sciences, especially in genomics, where the need to reduce the number of features and keep the analysis interpretable at the same time, is crucial." }, { "code": null, "e": 13775, "s": 13438, "text": "Applying NMF on extra-financial data is an innovative way of extracting the valuable information contained in these datasets. We have used the data of a particular provider — Vigeo-Eiris-, but the good news is that this method will be extremely robust when using multiple sources of data, to exhibit fundamental attributes of companies." }, { "code": null, "e": 13936, "s": 13775, "text": "[1] Ding, C.H.Q.; Tao, L.; Jordan, M.I. Convex and Semi-Nonnegative Matrix Factorizations (2010). IEEE Trans. PatternAnal. Mach. Intelli. Arch. 2010, 32, 44–55." }, { "code": null, "e": 14175, "s": 13936, "text": "[2] P.Fogel, Y. Gaston-Mathé et al., Applications of a Novel Clustering Approach Using Non-Negative Matrix Factorization to EnvironmentalResearch in Public Health (2016), International Journal of Environmental Research and Public Health." }, { "code": null, "e": 14327, "s": 14175, "text": "[3] B. Yu and K. Kumbier, Three principles of data science: predictability, computability, and stability (pcs) (2019), arXiv preprint arXiv:1901.08152." }, { "code": null, "e": 14429, "s": 14327, "text": "[4] V. Margot. A rigorous method to compare interpretability (2020), arXiv preprint arXiv:2004.01570." } ]
Explain soft reset with an example in Git
Soft reset will move the HEAD pointer to the commit specified. This will not reset the staging area or the working directory. The diagram shows a file named File1.txt within the git repository. A, B, C and D represent lines that are added to the file. The diagram indicates that a commit is performed after adding each line A, B and C. c1 is the commit performed after adding line A, c2 is the commit after adding line B and C3 represents the commit after adding line C. Now add line D. This change is available in the working directory and this change is staged but yet to be committed. Now let us perform a soft reset to make the HEAD of master branch point to the commit c1 commit. After the soft reset, HEAD will point to the commit c1 without changing anything in the staging area or the working area. Step 1 − Create a repository and add File1.txt with content A. Commit the changes as shown in the below code snippet. $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo $ git init Initialized empty Git repository in E:/tut_repo/.git/ $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ echo A>File1.txt $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ cat File1.txt A $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git add . $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git commit -m 'A' [master (root-commit) c2bd7e5] A 1 file changed, 1 insertion(+) create mode 100644 File1.txt Step 2 − Perform 2 more commits with contents B and C as shown in the above diagram. $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ echo B>>File1.txt $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ cat File1.txt A B $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git add . $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git commit -m 'B' [master 05cf92e] B 1 file changed, 1 insertion(+) $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ echo C>>File1.txt $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ cat File1.txt A B C $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git add . $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git commit -m 'C' [master 36361c2] C 1 file changed, 1 insertion(+) $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git log --oneline 36361c2 (HEAD -> master) C 05cf92e B c2bd7e5 A Step 3 − Make a change in the working directory to add content D and stage the changes. $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ echo D>>File1.txt $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ cat File1.txt A B C D $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git add . $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git status -s M File1.txt Step 4 − Now let’s perform a soft reset to make the HEAD point to the first commit. In other words, we have to move the head pointer two commits back. However, no changes will be done in the staging area and the working directory. $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git log --oneline 36361c2 (HEAD -> master) C 05cf92e B c2bd7e5 A $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git reset --soft HEAD~2 $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git log --oneline c2bd7e5 (HEAD -> master) A $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git status -s M File1.txt $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ cat File1.txt A B C D $ git status On branch master Changes to be committed: (use "git restore --staged <file>..." to unstage) modified: File1.txt As shown in the below diagram, when we perform a soft reset, Git simply moves the HEAD to the specified commit without impacting the Working and the Staging area. After performing the soft reset, our working directory will contain all four lines in the file. The staged change - Content D will also be intact in the Staging Area.
[ { "code": null, "e": 1188, "s": 1062, "text": "Soft reset will move the HEAD pointer to the commit specified. This will not reset the staging area or the working directory." }, { "code": null, "e": 1533, "s": 1188, "text": "The diagram shows a file named File1.txt within the git repository. A, B, C and D represent lines that are added to the file. The diagram indicates that a commit is performed after adding each line A, B and C. c1 is the commit performed after adding line A, c2 is the commit after adding line B and C3 represents the commit after adding line C." }, { "code": null, "e": 1869, "s": 1533, "text": "Now add line D. This change is available in the working directory and this change is staged but yet to be committed. Now let us perform a soft reset to make the HEAD of master branch point to the commit c1 commit. After the soft reset, HEAD will point to the commit c1 without changing anything in the staging area or the working area." }, { "code": null, "e": 1987, "s": 1869, "text": "Step 1 − Create a repository and add File1.txt with content A. Commit the changes as shown in the below code snippet." }, { "code": null, "e": 2469, "s": 1987, "text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo\n$ git init\nInitialized empty Git repository in E:/tut_repo/.git/\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo A>File1.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ cat File1.txt\nA\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git commit -m 'A'\n[master (root-commit) c2bd7e5] A\n1 file changed, 1 insertion(+)\ncreate mode 100644 File1.txt" }, { "code": null, "e": 2554, "s": 2469, "text": "Step 2 − Perform 2 more commits with contents B and C as shown in the above diagram." }, { "code": null, "e": 3343, "s": 2554, "text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo B>>File1.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ cat File1.txt\nA\nB\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git commit -m 'B'\n[master 05cf92e] B\n1 file changed, 1 insertion(+)\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo C>>File1.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ cat File1.txt\nA\nB\nC\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git commit -m 'C'\n[master 36361c2] C\n1 file changed, 1 insertion(+)\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git log --oneline\n36361c2 (HEAD -> master) C\n05cf92e B\nc2bd7e5 A" }, { "code": null, "e": 3431, "s": 3343, "text": "Step 3 − Make a change in the working directory to add content D and stage the changes." }, { "code": null, "e": 3726, "s": 3431, "text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo D>>File1.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ cat File1.txt\nA\nB\nC\nD\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git status -s\nM File1.txt" }, { "code": null, "e": 3957, "s": 3726, "text": "Step 4 − Now let’s perform a soft reset to make the HEAD point to the first commit. In other words, we have to move the head pointer two commits back. However, no changes will be done in the staging area and the working directory." }, { "code": null, "e": 4538, "s": 3957, "text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git log --oneline\n36361c2 (HEAD -> master) C\n05cf92e B\nc2bd7e5 A\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git reset --soft HEAD~2\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git log --oneline\nc2bd7e5 (HEAD -> master) A\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git status -s\nM File1.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ cat File1.txt\nA\nB\nC\nD\n$ git status\nOn branch master\nChanges to be committed:\n(use \"git restore --staged <file>...\" to unstage)\nmodified: File1.txt" }, { "code": null, "e": 4868, "s": 4538, "text": "As shown in the below diagram, when we perform a soft reset, Git simply moves the HEAD to the specified commit without impacting the Working and the Staging area. After performing the soft reset, our working directory will contain all four lines in the file. The staged change - Content D will also be intact in the Staging Area." } ]
Java & MySQL - Statement
JDBC Statement interface defines the methods and properties to enable send SQL commands to MySQL database and retrieve data from the database. Statement is used for general-purpose access to your database. It is useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters. Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object's createStatement( ) method, as in the following example − Statement stmt = null; try { stmt = conn.createStatement( ); . . . } catch (SQLException e) { . . . } finally { . . . } Once you've created a Statement object, you can then use it to execute an SQL statement with one of its three execute methods. boolean execute (String SQL) − Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL. boolean execute (String SQL) − Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL. int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement. int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement. ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement. ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement. Just as you close a Connection object to save database resources, for the same reason you should also close the Statement object. A simple call to the close() method will do the job. If you close the Connection object first, it will close the Statement object as well. However, you should always explicitly close the Statement object to ensure proper cleanup. Statement stmt = null; try { stmt = conn.createStatement( ); . . . } catch (SQLException e) { . . . } finally { stmt.close(); } We're using try with resources which handles the resource closure automatically. Following example demonstrates all of the above said concepts. This code has been written based on the environment and database setup done in the previous chapter. Copy and paste the following example in TestApplication.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestApplication { static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT"; static final String USER = "guest"; static final String PASS = "guest123"; static final String QUERY = "SELECT id, first, last, age FROM Employees"; static final String UPDATE_QUERY = "UPDATE Employees set age=30 WHERE id=103"; public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); ) { // Let us check if it returns a true Result Set or not. Boolean ret = stmt.execute(UPDATE_QUERY); System.out.println("Return value is : " + ret.toString() ); // Let us update age of the record with ID = 103; int rows = stmt.executeUpdate(UPDATE_QUERY); System.out.println("Rows impacted : " + rows ); // Let us select all the records and display them. ResultSet rs = stmt.executeQuery(QUERY); // Extract data from result set while (rs.next()) { // Retrieve by column name System.out.print("ID: " + rs.getInt("id")); System.out.print(", Age: " + rs.getInt("age")); System.out.print(", First: " + rs.getString("first")); System.out.println(", Last: " + rs.getString("last")); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:\>javac TestApplication.java C:\> When you run TestApplication, it produces the following result − C:\>java TestApplication Return value is : false Rows impacted : 1 ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mehnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 30, First: Sumit, Last: Mittal C:\> 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 3008, "s": 2686, "text": "JDBC Statement interface defines the methods and properties to enable send SQL commands to MySQL database and retrieve data from the database. Statement is used for general-purpose access to your database. It is useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters." }, { "code": null, "e": 3184, "s": 3008, "text": "Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object's createStatement( ) method, as in the following example −" }, { "code": null, "e": 3316, "s": 3184, "text": "Statement stmt = null;\ntry {\n stmt = conn.createStatement( );\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n . . .\n}" }, { "code": null, "e": 3443, "s": 3316, "text": "Once you've created a Statement object, you can then use it to execute an SQL statement with one of its three execute methods." }, { "code": null, "e": 3664, "s": 3443, "text": "boolean execute (String SQL) − Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL." }, { "code": null, "e": 3885, "s": 3664, "text": "boolean execute (String SQL) − Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL." }, { "code": null, "e": 4144, "s": 3885, "text": "int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement." }, { "code": null, "e": 4403, "s": 4144, "text": "int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement." }, { "code": null, "e": 4560, "s": 4403, "text": "ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement." }, { "code": null, "e": 4717, "s": 4560, "text": "ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement." }, { "code": null, "e": 4848, "s": 4717, "text": "Just as you close a Connection object to save database resources, for the same reason you should also close the Statement object." }, { "code": null, "e": 5078, "s": 4848, "text": "A simple call to the close() method will do the job. If you close the Connection object first, it will close the Statement object as well. However, you should always explicitly close the Statement object to ensure proper cleanup." }, { "code": null, "e": 5218, "s": 5078, "text": "Statement stmt = null;\ntry {\n stmt = conn.createStatement( );\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n stmt.close();\n}" }, { "code": null, "e": 5362, "s": 5218, "text": "We're using try with resources which handles the resource closure automatically. Following example demonstrates all of the above said concepts." }, { "code": null, "e": 5463, "s": 5362, "text": "This code has been written based on the environment and database setup done in the previous chapter." }, { "code": null, "e": 5554, "s": 5463, "text": "Copy and paste the following example in TestApplication.java, compile and run as follows −" }, { "code": null, "e": 7200, "s": 5554, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Employees\";\n static final String UPDATE_QUERY = \"UPDATE Employees set age=30 WHERE id=103\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\n // Let us check if it returns a true Result Set or not.\n Boolean ret = stmt.execute(UPDATE_QUERY);\n System.out.println(\"Return value is : \" + ret.toString() );\n\n // Let us update age of the record with ID = 103;\n int rows = stmt.executeUpdate(UPDATE_QUERY);\n System.out.println(\"Rows impacted : \" + rows );\n\n // Let us select all the records and display them.\n ResultSet rs = stmt.executeQuery(QUERY);\t\t \n\n // Extract data from result set\n while (rs.next()) {\n // Retrieve by column name\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}" }, { "code": null, "e": 7250, "s": 7200, "text": "Now let us compile the above example as follows −" }, { "code": null, "e": 7287, "s": 7250, "text": "C:\\>javac TestApplication.java\nC:\\>\n" }, { "code": null, "e": 7352, "s": 7287, "text": "When you run TestApplication, it produces the following result −" }, { "code": null, "e": 7598, "s": 7352, "text": "C:\\>java TestApplication\nReturn value is : false\nRows impacted : 1\nID: 100, Age: 18, First: Zara, Last: Ali\nID: 101, Age: 25, First: Mehnaz, Last: Fatma\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 30, First: Sumit, Last: Mittal\nC:\\>\n" }, { "code": null, "e": 7631, "s": 7598, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 7647, "s": 7631, "text": " Malhar Lathkar" }, { "code": null, "e": 7680, "s": 7647, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 7696, "s": 7680, "text": " Malhar Lathkar" }, { "code": null, "e": 7731, "s": 7696, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7745, "s": 7731, "text": " Anadi Sharma" }, { "code": null, "e": 7779, "s": 7745, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 7793, "s": 7779, "text": " Tushar Kale" }, { "code": null, "e": 7830, "s": 7793, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7845, "s": 7830, "text": " Monica Mittal" }, { "code": null, "e": 7878, "s": 7845, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 7897, "s": 7878, "text": " Arnab Chakraborty" }, { "code": null, "e": 7904, "s": 7897, "text": " Print" }, { "code": null, "e": 7915, "s": 7904, "text": " Add Notes" } ]
Faster YOLOv4 Performance with CUDA enabled OpenCV | by Akash James | Towards Data Science
YOLO, short for You-Only-Look-Once has been undoubtedly one of the best object detectors trained on the COCO dataset. YOLOv4 being the latest iteration has a great accuracy-performance trade-off, establishing itself as one of the State-of-the-art object detectors. Typical mechanisms of employing any object detector in an intelligent video analytics pipeline involve accelerating model inference using a library like Tensorflow or PyTorch which are capable of operations on an NVIDIA GPU. OpenCV is used for image/video-stream input, pre-processing and post-processed visuals. What if I told you that OpenCV is now capable of running YOLOv4 natively with the DNN module utilizing the goodness of NVIDIA CUDA? In this blog, I will walk you through building OpenCV with CUDA and cuDNN to accelerate YOLOv4 inference using the DNN module. Most enthusiasts I know have GPU enabled devices. The goal for me has always been to make GPU acceleration mainstream. Well, who doesn’t like to go faster? I have used OpenCV 4.5.1, CUDA 11.2 and cuDNN 8.1.0 to get the ball rolling and make inference easier! First, you need to setup CUDA, then install cuDNN and finally conclude with building OpenCV. Also, the blog is divided into sections so that it is easier to follow! The section that has the highest chance of rendering your machine un-bootable. Just kidding! Do everything right and this should be a breeze. Begin with downloading the deb file from the CUDA repository based on your platform. Once you have selected your platform appropriately, you will be provided installation commands. If your platform is similar to that of mine, you can install it as follows — wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-ubuntu2004.pinsudo mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600wget https://developer.download.nvidia.com/compute/cuda/11.2.1/local_installers/cuda-repo-ubuntu2004-11-2-local_11.2.1-460.32.03-1_amd64.debsudo dpkg -i cuda-repo-ubuntu2004-11-2-local_11.2.1-460.32.03-1_amd64.debsudo apt-key add /var/cuda-repo-ubuntu2004-11-2-local/7fa2af80.pubsudo apt updatesudo apt -y install cudasudo reboot If done right, you should have the following output when you run nvidia-smi Finally, finish off by pasting the following in your .bashrc or .zshrc # CUDAexport CUDA=11.2export PATH=/usr/local/cuda-$CUDA/bin${PATH:+:${PATH}}export CUDA_PATH=/usr/local/cuda-$CUDAexport CUDA_HOME=/usr/local/cuda-$CUDAexport LIBRARY_PATH=$CUDA_HOME/lib64:$LIBRARY_PATHexport LD_LIBRARY_PATH=/usr/local/cuda-$CUDA/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}export LD_LIBRARY_PATH=/usr/local/cuda/extras/CUPTI/lib64:$LD_LIBRARY_PATHexport NVCC=/usr/local/cuda-$CUDA/bin/nvccexport CFLAGS="-I$CUDA_HOME/include $CFLAGS" Don’t forget to follow up with source ~/.bashrc or source ~/.zshrc For this, you will need to have an account with NVIDIA, so make sure you sign on. Once you do, head here and download the marked files. Once you have the deb files downloaded, run the following commands — sudo dpkg -i libcudnn8_8.1.0.77-1+cuda11.2_amd64.debsudo dpkg -i libcudnn8-dev_8.1.0.77-1+cuda11.2_amd64.deb This marks the completion of NVIDIA CUDA and cuDNN installation! Here’s the fun bit, that gets me excited! This section will help you build OpenCV from source with CUDA, GStreamer and FFMPEG! There’s a long list of commands to execute, so get started. First, install python developer packages — sudo apt install python3-dev python3-pip python3-testresources Next, let’s install dependencies needed to build OpenCV sudo apt install build-essential cmake pkg-config unzip yasm git checkinstallsudo apt install libjpeg-dev libpng-dev libtiff-devsudo apt install libavcodec-dev libavformat-dev libswscale-dev libavresample-devsudo apt install libgstreamer1.0-dev libgstreamer-plugins-base1.0-devsudo apt install libxvidcore-dev x264 libx264-dev libfaac-dev libmp3lame-dev libtheora-devsudo apt install libfaac-dev libmp3lame-dev libvorbis-devsudo apt install libopencore-amrnb-dev libopencore-amrwb-devsudo apt-get install libgtk-3-devsudo apt-get install libtbb-devsudo apt-get install libatlas-base-dev gfortransudo apt-get install libprotobuf-dev protobuf-compilersudo apt-get install libgoogle-glog-dev libgflags-devsudo apt-get install libgphoto2-dev libeigen3-dev libhdf5-dev doxygen Numpy is one crucial python package for this build. Install it using pip — pip3 install numpy Now, you should have everything ready for the build. Run the following commands to download and extract the source — mkdir opencvbuild && cd opencvbuildwget -O opencv.zip https://github.com/opencv/opencv/archive/4.5.1.zipwget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.5.1.zipunzip opencv.zipunzip opencv_contrib.zipmv opencv-4.5.1 opencvmv opencv_contrib-4.5.1 opencv_contrib Let’s prepare the recipe! cd opencvmkdir build && cd build Make sure to change CUDA_ARCH_BIN based on your GPU. cmake \-D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_C_COMPILER=/usr/bin/gcc-7 \-D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON \-D INSTALL_C_EXAMPLES=ON -D WITH_TBB=ON -D WITH_CUDA=ON -D WITH_CUDNN=ON \-D OPENCV_DNN_CUDA=ON -D CUDA_ARCH_BIN=7.5 -D BUILD_opencv_cudacodec=OFF \-D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 \-D WITH_V4L=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D WITH_GSTREAMER=ON \-D WITH_FFMPEG=ON -D OPENCV_GENERATE_PKGCONFIG=ON \-D OPENCV_PC_FILE_NAME=opencv4.pc -D OPENCV_ENABLE_NONFREE=ON \-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \-D PYTHON_DEFAULT_EXECUTABLE=$(which python3) -D BUILD_EXAMPLES=ON .. You should see a successful build similar to this — Make sure CUDA is detected and the build paths are accurate. If everything looks good, go ahead and execute the following commands to initiate the build — make -j$(nproc)sudo make install To check if you built OpenCV successfully, run this command — pkg-config --libs --cflags opencv4 It should give you an output like so on successful installation — It’s great to see you make it this far! Now you should be all set to run the sample application. Go ahead and clone this repository and pull the weights. Start with install git-lfs sudo apt install git git-lfs Clone the repository with the model files # Using HTTPSgit clone https://github.com/aj-ames/YOLOv4-OpenCV-CUDA-DNN.git# Using SSHgit clone git@github.com:aj-ames/YOLOv4-OpenCV-CUDA-DNN.gitcd YOLOv4-OpenCV-CUDA-DNN/git lfs installgit lfs pull You can run the application on either image, video webcam, or RTSP inputs. # Imagepython3 dnn_infernece.py --image images/example.jpg --use_gpu# Videopython3 dnn_inference.py --stream video.mp4 --use_gpu# RTSPpython3 dnn_inference.py --stream rtsp://192.168.1.1:554/stream --use_gpu# Webcampython3 dnn_inference.py --stream webcam --use_gpu P.S — Remove the --use-gpu flag to disable the GPU. Counter-productive isn’t it? We wouldn’t be doing this if the gain wasn’t substantial. Trust me, it is! Running on GPU gave me an increase in FPS by 10–15x! I have tested on two configurations Intel Core i5 7300HQ + NVIDIA GeForce GTX 1050TiIntel Xeon E5–1650 v4 + NVIDIA Tesla T4 Intel Core i5 7300HQ + NVIDIA GeForce GTX 1050Ti Intel Xeon E5–1650 v4 + NVIDIA Tesla T4 I’ll let the numbers do the talking! | Device | FPS | Device | FPS || :------------: | :----------: | :------------: | :----------: || Core i5 7300HQ | 2.1 | GTX 1050 Ti | 20.1 || Xeon E5-1650 | 3.5 | Tesla T4 | 42.3 | GPU acceleration is percolating into several libraries and applications enabling users to run heavier workloads faster than ever! Computer Vision was once a piece of technology not accessible to all, but with improvement in neural networks and an increase in hardware compute capability, the gap has narrowed down significantly. With AI booming faster than ever, we are in for a lot of hardware flex! 💪
[ { "code": null, "e": 1009, "s": 172, "text": "YOLO, short for You-Only-Look-Once has been undoubtedly one of the best object detectors trained on the COCO dataset. YOLOv4 being the latest iteration has a great accuracy-performance trade-off, establishing itself as one of the State-of-the-art object detectors. Typical mechanisms of employing any object detector in an intelligent video analytics pipeline involve accelerating model inference using a library like Tensorflow or PyTorch which are capable of operations on an NVIDIA GPU. OpenCV is used for image/video-stream input, pre-processing and post-processed visuals. What if I told you that OpenCV is now capable of running YOLOv4 natively with the DNN module utilizing the goodness of NVIDIA CUDA? In this blog, I will walk you through building OpenCV with CUDA and cuDNN to accelerate YOLOv4 inference using the DNN module." }, { "code": null, "e": 1433, "s": 1009, "text": "Most enthusiasts I know have GPU enabled devices. The goal for me has always been to make GPU acceleration mainstream. Well, who doesn’t like to go faster? I have used OpenCV 4.5.1, CUDA 11.2 and cuDNN 8.1.0 to get the ball rolling and make inference easier! First, you need to setup CUDA, then install cuDNN and finally conclude with building OpenCV. Also, the blog is divided into sections so that it is easier to follow!" }, { "code": null, "e": 1575, "s": 1433, "text": "The section that has the highest chance of rendering your machine un-bootable. Just kidding! Do everything right and this should be a breeze." }, { "code": null, "e": 1660, "s": 1575, "text": "Begin with downloading the deb file from the CUDA repository based on your platform." }, { "code": null, "e": 1833, "s": 1660, "text": "Once you have selected your platform appropriately, you will be provided installation commands. If your platform is similar to that of mine, you can install it as follows —" }, { "code": null, "e": 2336, "s": 1833, "text": "wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-ubuntu2004.pinsudo mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600wget https://developer.download.nvidia.com/compute/cuda/11.2.1/local_installers/cuda-repo-ubuntu2004-11-2-local_11.2.1-460.32.03-1_amd64.debsudo dpkg -i cuda-repo-ubuntu2004-11-2-local_11.2.1-460.32.03-1_amd64.debsudo apt-key add /var/cuda-repo-ubuntu2004-11-2-local/7fa2af80.pubsudo apt updatesudo apt -y install cudasudo reboot" }, { "code": null, "e": 2412, "s": 2336, "text": "If done right, you should have the following output when you run nvidia-smi" }, { "code": null, "e": 2483, "s": 2412, "text": "Finally, finish off by pasting the following in your .bashrc or .zshrc" }, { "code": null, "e": 2935, "s": 2483, "text": "# CUDAexport CUDA=11.2export PATH=/usr/local/cuda-$CUDA/bin${PATH:+:${PATH}}export CUDA_PATH=/usr/local/cuda-$CUDAexport CUDA_HOME=/usr/local/cuda-$CUDAexport LIBRARY_PATH=$CUDA_HOME/lib64:$LIBRARY_PATHexport LD_LIBRARY_PATH=/usr/local/cuda-$CUDA/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}export LD_LIBRARY_PATH=/usr/local/cuda/extras/CUPTI/lib64:$LD_LIBRARY_PATHexport NVCC=/usr/local/cuda-$CUDA/bin/nvccexport CFLAGS=\"-I$CUDA_HOME/include $CFLAGS\"" }, { "code": null, "e": 3002, "s": 2935, "text": "Don’t forget to follow up with source ~/.bashrc or source ~/.zshrc" }, { "code": null, "e": 3138, "s": 3002, "text": "For this, you will need to have an account with NVIDIA, so make sure you sign on. Once you do, head here and download the marked files." }, { "code": null, "e": 3207, "s": 3138, "text": "Once you have the deb files downloaded, run the following commands —" }, { "code": null, "e": 3316, "s": 3207, "text": "sudo dpkg -i libcudnn8_8.1.0.77-1+cuda11.2_amd64.debsudo dpkg -i libcudnn8-dev_8.1.0.77-1+cuda11.2_amd64.deb" }, { "code": null, "e": 3381, "s": 3316, "text": "This marks the completion of NVIDIA CUDA and cuDNN installation!" }, { "code": null, "e": 3568, "s": 3381, "text": "Here’s the fun bit, that gets me excited! This section will help you build OpenCV from source with CUDA, GStreamer and FFMPEG! There’s a long list of commands to execute, so get started." }, { "code": null, "e": 3611, "s": 3568, "text": "First, install python developer packages —" }, { "code": null, "e": 3674, "s": 3611, "text": "sudo apt install python3-dev python3-pip python3-testresources" }, { "code": null, "e": 3730, "s": 3674, "text": "Next, let’s install dependencies needed to build OpenCV" }, { "code": null, "e": 4502, "s": 3730, "text": "sudo apt install build-essential cmake pkg-config unzip yasm git checkinstallsudo apt install libjpeg-dev libpng-dev libtiff-devsudo apt install libavcodec-dev libavformat-dev libswscale-dev libavresample-devsudo apt install libgstreamer1.0-dev libgstreamer-plugins-base1.0-devsudo apt install libxvidcore-dev x264 libx264-dev libfaac-dev libmp3lame-dev libtheora-devsudo apt install libfaac-dev libmp3lame-dev libvorbis-devsudo apt install libopencore-amrnb-dev libopencore-amrwb-devsudo apt-get install libgtk-3-devsudo apt-get install libtbb-devsudo apt-get install libatlas-base-dev gfortransudo apt-get install libprotobuf-dev protobuf-compilersudo apt-get install libgoogle-glog-dev libgflags-devsudo apt-get install libgphoto2-dev libeigen3-dev libhdf5-dev doxygen" }, { "code": null, "e": 4577, "s": 4502, "text": "Numpy is one crucial python package for this build. Install it using pip —" }, { "code": null, "e": 4596, "s": 4577, "text": "pip3 install numpy" }, { "code": null, "e": 4713, "s": 4596, "text": "Now, you should have everything ready for the build. Run the following commands to download and extract the source —" }, { "code": null, "e": 5003, "s": 4713, "text": "mkdir opencvbuild && cd opencvbuildwget -O opencv.zip https://github.com/opencv/opencv/archive/4.5.1.zipwget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.5.1.zipunzip opencv.zipunzip opencv_contrib.zipmv opencv-4.5.1 opencvmv opencv_contrib-4.5.1 opencv_contrib" }, { "code": null, "e": 5029, "s": 5003, "text": "Let’s prepare the recipe!" }, { "code": null, "e": 5062, "s": 5029, "text": "cd opencvmkdir build && cd build" }, { "code": null, "e": 5115, "s": 5062, "text": "Make sure to change CUDA_ARCH_BIN based on your GPU." }, { "code": null, "e": 5773, "s": 5115, "text": "cmake \\-D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_C_COMPILER=/usr/bin/gcc-7 \\-D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON \\-D INSTALL_C_EXAMPLES=ON -D WITH_TBB=ON -D WITH_CUDA=ON -D WITH_CUDNN=ON \\-D OPENCV_DNN_CUDA=ON -D CUDA_ARCH_BIN=7.5 -D BUILD_opencv_cudacodec=OFF \\-D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 \\-D WITH_V4L=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D WITH_GSTREAMER=ON \\-D WITH_FFMPEG=ON -D OPENCV_GENERATE_PKGCONFIG=ON \\-D OPENCV_PC_FILE_NAME=opencv4.pc -D OPENCV_ENABLE_NONFREE=ON \\-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \\-D PYTHON_DEFAULT_EXECUTABLE=$(which python3) -D BUILD_EXAMPLES=ON .." }, { "code": null, "e": 5825, "s": 5773, "text": "You should see a successful build similar to this —" }, { "code": null, "e": 5980, "s": 5825, "text": "Make sure CUDA is detected and the build paths are accurate. If everything looks good, go ahead and execute the following commands to initiate the build —" }, { "code": null, "e": 6013, "s": 5980, "text": "make -j$(nproc)sudo make install" }, { "code": null, "e": 6075, "s": 6013, "text": "To check if you built OpenCV successfully, run this command —" }, { "code": null, "e": 6110, "s": 6075, "text": "pkg-config --libs --cflags opencv4" }, { "code": null, "e": 6176, "s": 6110, "text": "It should give you an output like so on successful installation —" }, { "code": null, "e": 6273, "s": 6176, "text": "It’s great to see you make it this far! Now you should be all set to run the sample application." }, { "code": null, "e": 6357, "s": 6273, "text": "Go ahead and clone this repository and pull the weights. Start with install git-lfs" }, { "code": null, "e": 6386, "s": 6357, "text": "sudo apt install git git-lfs" }, { "code": null, "e": 6428, "s": 6386, "text": "Clone the repository with the model files" }, { "code": null, "e": 6628, "s": 6428, "text": "# Using HTTPSgit clone https://github.com/aj-ames/YOLOv4-OpenCV-CUDA-DNN.git# Using SSHgit clone git@github.com:aj-ames/YOLOv4-OpenCV-CUDA-DNN.gitcd YOLOv4-OpenCV-CUDA-DNN/git lfs installgit lfs pull" }, { "code": null, "e": 6703, "s": 6628, "text": "You can run the application on either image, video webcam, or RTSP inputs." }, { "code": null, "e": 6969, "s": 6703, "text": "# Imagepython3 dnn_infernece.py --image images/example.jpg --use_gpu# Videopython3 dnn_inference.py --stream video.mp4 --use_gpu# RTSPpython3 dnn_inference.py --stream rtsp://192.168.1.1:554/stream --use_gpu# Webcampython3 dnn_inference.py --stream webcam --use_gpu" }, { "code": null, "e": 7050, "s": 6969, "text": "P.S — Remove the --use-gpu flag to disable the GPU. Counter-productive isn’t it?" }, { "code": null, "e": 7178, "s": 7050, "text": "We wouldn’t be doing this if the gain wasn’t substantial. Trust me, it is! Running on GPU gave me an increase in FPS by 10–15x!" }, { "code": null, "e": 7214, "s": 7178, "text": "I have tested on two configurations" }, { "code": null, "e": 7302, "s": 7214, "text": "Intel Core i5 7300HQ + NVIDIA GeForce GTX 1050TiIntel Xeon E5–1650 v4 + NVIDIA Tesla T4" }, { "code": null, "e": 7351, "s": 7302, "text": "Intel Core i5 7300HQ + NVIDIA GeForce GTX 1050Ti" }, { "code": null, "e": 7391, "s": 7351, "text": "Intel Xeon E5–1650 v4 + NVIDIA Tesla T4" }, { "code": null, "e": 7428, "s": 7391, "text": "I’ll let the numbers do the talking!" }, { "code": null, "e": 7689, "s": 7428, "text": "| Device | FPS | Device | FPS || :------------: | :----------: | :------------: | :----------: || Core i5 7300HQ | 2.1 | GTX 1050 Ti | 20.1 || Xeon E5-1650 | 3.5 | Tesla T4 | 42.3 |" } ]
Java Program to get random letters
To generate random letters, set letters as a strong and use the toCharArray() to convert it into character array − "abcdefghijklmnopqrstuvwxyz".toCharArray() Now, use the nextInt() to generate random letters from it − System.out.println("" + "abcdefghijklmnopqrstuvwxyz".toCharArray()[randNum.nextInt("abcdefghijklmnopqrstuvwxyz".toCharArray().length)]); Above, initially we have created a Random object − static Random randNum = new Random(); Live Demo import java.util.Random; public class Demo { static Random randNum = new Random(); public static void main(String args[]) { System.out.println("Lowercase random letters..."); for (int i = 0; i < 5; i++) { System.out.println("" + "abcdefghijklmnopqrstuvwxyz".toCharArray()[randNum.nextInt("abcdefghijklmnopqrstuvwxyz".toCharArray().length)]); } System.out.println("Uppercase random letters..."); for (int i = 0; i < 5; i++) { System.out.println("" + "ABCDEFGHIJKLMNOPQRSTUVWZYZ".toCharArray()[randNum.nextInt("ABCDEFGHIJKLMNOPQRSTUVWZYZ".toCharArray().length)]); } } } Lowercase random letters... d l h j s Uppercase random letters... B K I Z N
[ { "code": null, "e": 1177, "s": 1062, "text": "To generate random letters, set letters as a strong and use the toCharArray() to convert it into character array −" }, { "code": null, "e": 1220, "s": 1177, "text": "\"abcdefghijklmnopqrstuvwxyz\".toCharArray()" }, { "code": null, "e": 1280, "s": 1220, "text": "Now, use the nextInt() to generate random letters from it −" }, { "code": null, "e": 1417, "s": 1280, "text": "System.out.println(\"\" + \"abcdefghijklmnopqrstuvwxyz\".toCharArray()[randNum.nextInt(\"abcdefghijklmnopqrstuvwxyz\".toCharArray().length)]);" }, { "code": null, "e": 1468, "s": 1417, "text": "Above, initially we have created a Random object −" }, { "code": null, "e": 1506, "s": 1468, "text": "static Random randNum = new Random();" }, { "code": null, "e": 1517, "s": 1506, "text": " Live Demo" }, { "code": null, "e": 2148, "s": 1517, "text": "import java.util.Random;\npublic class Demo {\n static Random randNum = new Random();\n public static void main(String args[]) {\n System.out.println(\"Lowercase random letters...\");\n for (int i = 0; i < 5; i++) {\n System.out.println(\"\" + \"abcdefghijklmnopqrstuvwxyz\".toCharArray()[randNum.nextInt(\"abcdefghijklmnopqrstuvwxyz\".toCharArray().length)]);\n }\n System.out.println(\"Uppercase random letters...\");\n for (int i = 0; i < 5; i++) {\n System.out.println(\"\" + \"ABCDEFGHIJKLMNOPQRSTUVWZYZ\".toCharArray()[randNum.nextInt(\"ABCDEFGHIJKLMNOPQRSTUVWZYZ\".toCharArray().length)]);\n }\n }\n}" }, { "code": null, "e": 2224, "s": 2148, "text": "Lowercase random letters...\nd\nl\nh\nj\ns\nUppercase random letters...\nB\nK\nI\nZ\nN" } ]
GATE | GATE CS 2019 | Question 55 - GeeksforGeeks
19 Feb, 2019 Let T be a full binary tree with 8 leaves. (A full binary tree has every level full.) Suppose two leaves a and b of T are chosen uniformly and independently at random. The expected value of the distance between a and b in T (i.e., the number of edges in the unique path between a and b) is (rounded off to 2 decimal places) ___________ . Note: This was Numerical Type question.(A) 5.71 to 5.73(B) 4.85 to 4.86(C) 2.71 to 2.73(D) 4.24 to 4.26Answer: (D)Explanation: Full binary tree with 8 leaf nodes, Two leaf nodes can be selected in 8*8 = 64 ways. Where, X is length between two nodes selected. The expected value of the length between a and b in T, = E[X] = X * P[X] = 0*(8/64) + 2*(8/64) + 4*(16/64) + 6*(32/64) = 272/64 = 4.25 So, answer is 4.25. Alternative way:Sum of distances from a particular leaf to the remaining 7 leaves is 34. The sum would remain the same for each leaf node. Therefore total sum of distance of all the leaf nodes = 34*8. Two leaf nodes can be selected in 8*8 = 64 ways. Therefore, the expected value of the length between a and b in T, = (34*8) / (8*8) = 34 / 8 = 4.25 Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25631, "s": 25603, "text": "\n19 Feb, 2019" }, { "code": null, "e": 25969, "s": 25631, "text": "Let T be a full binary tree with 8 leaves. (A full binary tree has every level full.) Suppose two leaves a and b of T are chosen uniformly and independently at random. The expected value of the distance between a and b in T (i.e., the number of edges in the unique path between a and b) is (rounded off to 2 decimal places) ___________ ." }, { "code": null, "e": 26132, "s": 25969, "text": "Note: This was Numerical Type question.(A) 5.71 to 5.73(B) 4.85 to 4.86(C) 2.71 to 2.73(D) 4.24 to 4.26Answer: (D)Explanation: Full binary tree with 8 leaf nodes," }, { "code": null, "e": 26181, "s": 26132, "text": "Two leaf nodes can be selected in 8*8 = 64 ways." }, { "code": null, "e": 26228, "s": 26181, "text": "Where, X is length between two nodes selected." }, { "code": null, "e": 26283, "s": 26228, "text": "The expected value of the length between a and b in T," }, { "code": null, "e": 26364, "s": 26283, "text": "= E[X]\n= X * P[X]\n= 0*(8/64) + 2*(8/64) + 4*(16/64) + 6*(32/64)\n= 272/64\n= 4.25 " }, { "code": null, "e": 26384, "s": 26364, "text": "So, answer is 4.25." }, { "code": null, "e": 26585, "s": 26384, "text": "Alternative way:Sum of distances from a particular leaf to the remaining 7 leaves is 34. The sum would remain the same for each leaf node. Therefore total sum of distance of all the leaf nodes = 34*8." }, { "code": null, "e": 26634, "s": 26585, "text": "Two leaf nodes can be selected in 8*8 = 64 ways." }, { "code": null, "e": 26700, "s": 26634, "text": "Therefore, the expected value of the length between a and b in T," }, { "code": null, "e": 26733, "s": 26700, "text": "= (34*8) / (8*8)\n= 34 / 8\n= 4.25" }, { "code": null, "e": 26755, "s": 26733, "text": "Quiz of this Question" }, { "code": null, "e": 26760, "s": 26755, "text": "GATE" }, { "code": null, "e": 26858, "s": 26760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26892, "s": 26858, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26926, "s": 26892, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26960, "s": 26926, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26993, "s": 26960, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27029, "s": 26993, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27063, "s": 27029, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27099, "s": 27063, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27133, "s": 27099, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27167, "s": 27133, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Find minimum difference between any two elements - GeeksforGeeks
21 Jan, 2022 Given an unsorted array, find the minimum difference between any pair in given array.Examples : Input : {1, 5, 3, 19, 18, 25}; Output : 1 Minimum difference is between 18 and 19 Input : {30, 5, 20, 9}; Output : 4 Minimum difference is between 5 and 9 Input : {1, 19, -4, 31, 38, 25, 100}; Output : 5 Minimum difference is between 1 and -4 Method 1 (Simple: O(n2) A simple solution is to use two loops. C++ Java Python3 C# PHP Javascript // C++ implementation of simple method to find// minimum difference between any pair#include <bits/stdc++.h>using namespace std; // Returns minimum difference between any pairint findMinDiff(int arr[], int n){// Initialize difference as infiniteint diff = INT_MAX; // Find the min diff by comparing difference// of all possible pairs in given arrayfor (int i=0; i<n-1; i++) for (int j=i+1; j<n; j++) if (abs(arr[i] - arr[j]) < diff) diff = abs(arr[i] - arr[j]); // Return min diffreturn diff;} // Driver codeint main(){int arr[] = {1, 5, 3, 19, 18, 25};int n = sizeof(arr)/sizeof(arr[0]);cout << "Minimum difference is " << findMinDiff(arr, n);return 0;} // Java implementation of simple method to find// minimum difference between any pair class GFG{ // Returns minimum difference between any pair static int findMinDiff(int[] arr, int n) { // Initialize difference as infinite int diff = Integer.MAX_VALUE; // Find the min diff by comparing difference // of all possible pairs in given array for (int i=0; i<n-1; i++) for (int j=i+1; j<n; j++) if (Math.abs((arr[i] - arr[j]) )< diff) diff = Math.abs((arr[i] - arr[j])); // Return min diff return diff; } // Driver method to test the above function public static void main(String[] args) { int arr[] = new int[]{1, 5, 3, 19, 18, 25}; System.out.println("Minimum difference is "+ findMinDiff(arr, arr.length)); }} # Python implementation of simple method to find# minimum difference between any pair # Returns minimum difference between any pairdef findMinDiff(arr, n): # Initialize difference as infinite diff = 10**20 # Find the min diff by comparing difference # of all possible pairs in given array for i in range(n-1): for j in range(i+1,n): if abs(arr[i]-arr[j]) < diff: diff = abs(arr[i] - arr[j]) # Return min diff return diff # Driver codearr = [1, 5, 3, 19, 18, 25]n = len(arr)print("Minimum difference is " + str(findMinDiff(arr, n))) # This code is contributed by Pratik Chhajer // C# implementation of simple method to find// minimum difference between any pairusing System; class GFG { // Returns minimum difference between any pair static int findMinDiff(int []arr, int n) { // Initialize difference as infinite int diff = int.MaxValue; // Find the min diff by comparing difference // of all possible pairs in given array for (int i = 0; i < n-1; i++) for (int j = i+1; j < n; j++) if (Math.Abs((arr[i] - arr[j]) ) < diff) diff = Math.Abs((arr[i] - arr[j])); // Return min diff return diff; } // Driver method to test the above function public static void Main() { int []arr = new int[]{1, 5, 3, 19, 18, 25}; Console.Write("Minimum difference is " + findMinDiff(arr, arr.Length)); }} // This code is contributed by nitin mittal. <?php// PHP implementation of simple// method to find minimum// difference between any pair // Returns minimum difference// between any pairfunction findMinDiff($arr, $n){// Initialize difference// as infinite$diff = PHP_INT_MAX; // Find the min diff by comparing// difference of all possible// pairs in given arrayfor ($i = 0; $i < $n - 1; $i++) for ($j = $i + 1; $j < $n; $j++) if (abs($arr[$i] - $arr[$j]) < $diff) $diff = abs($arr[$i] - $arr[$j]); // Return min diffreturn $diff;} // Driver code$arr = array(1, 5, 3, 19, 18, 25);$n = sizeof($arr);echo "Minimum difference is " , findMinDiff($arr, $n); // This code is contributed by ajit?> <script> // JavaScript program implementation of simple method to find// minimum difference between any pair // Returns minimum difference between any pair function findMinDiff( arr, n) { // Initialize difference as infinite let diff = Number.MAX_VALUE; // Find the min diff by comparing difference // of all possible pairs in given array for (let i=0; i<n-1; i++) for (let j=i+1; j<n; j++) if (Math.abs((arr[i] - arr[j]) )< diff) diff = Math.abs((arr[i] - arr[j])); // Return min diff return diff; } // Driver Code let arr = [1, 5, 3, 19, 18, 25]; document.write("Minimum difference is "+ findMinDiff(arr, arr.length)); </script> Output : Minimum difference is 1 Method 2 (Efficient: O(n Log n) The idea is to use sorting. Below are steps. 1) Sort array in ascending order. This step takes O(n Log n) time. 2) Initialize difference as infinite. This step takes O(1) time. 3) Compare all adjacent pairs in sorted array and keep track of minimum difference. This step takes O(n) time.Below is implementation of above idea. C++ Java Python3 C# PHP Javascript // C++ program to find minimum difference between// any pair in an unsorted array#include <bits/stdc++.h>using namespace std; // Returns minimum difference between any pairint findMinDiff(int arr[], int n){ // Sort array in non-decreasing order sort(arr, arr+n); // Initialize difference as infinite int diff = INT_MAX; // Find the min diff by comparing adjacent // pairs in sorted array for (int i=0; i<n-1; i++) if (arr[i+1] - arr[i] < diff) diff = arr[i+1] - arr[i]; // Return min diff return diff;} // Driver codeint main(){ int arr[] = {1, 5, 3, 19, 18, 25}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Minimum difference is " << findMinDiff(arr, n); return 0;} // Java program to find minimum difference between// any pair in an unsorted array import java.util.Arrays; class GFG{ // Returns minimum difference between any pair static int findMinDiff(int[] arr, int n) { // Sort array in non-decreasing order Arrays.sort(arr); // Initialize difference as infinite int diff = Integer.MAX_VALUE; // Find the min diff by comparing adjacent // pairs in sorted array for (int i=0; i<n-1; i++) if (arr[i+1] - arr[i] < diff) diff = arr[i+1] - arr[i]; // Return min diff return diff; } // Driver method to test the above function public static void main(String[] args) { int arr[] = new int[]{1, 5, 3, 19, 18, 25}; System.out.println("Minimum difference is "+ findMinDiff(arr, arr.length)); }} # Python program to find minimum difference between# any pair in an unsorted array # Returns minimum difference between any pairdef findMinDiff(arr, n): # Sort array in non-decreasing order arr = sorted(arr) # Initialize difference as infinite diff = 10**20 # Find the min diff by comparing adjacent # pairs in sorted array for i in range(n-1): if arr[i+1] - arr[i] < diff: diff = arr[i+1] - arr[i] # Return min diff return diff # Driver codearr = [1, 5, 3, 19, 18, 25]n = len(arr)print("Minimum difference is " + str(findMinDiff(arr, n))) # This code is contributed by Pratik Chhajer // C# program to find minimum// difference between any pair// in an unsorted arrayusing System; class GFG{ // Returns minimum difference // between any pair static int findMinDiff(int[] arr, int n) { // Sort array in // non-decreasing order Array.Sort(arr); // Initialize difference // as infinite int diff = int.MaxValue; // Find the min diff by // comparing adjacent pairs // in sorted array for (int i = 0; i < n - 1; i++) if (arr[i + 1] - arr[i] < diff) diff = arr[i + 1] - arr[i]; // Return min diff return diff; } // Driver Code public static void Main() { int []arr = new int[]{1, 5, 3, 19, 18, 25}; Console.WriteLine("Minimum difference is " + findMinDiff(arr, arr.Length)); }} //This code is contributed by anuj_67. <?php// PHP program to find minimum// difference between any pair// in an unsorted array // Returns minimum difference// between any pairfunction findMinDiff($arr, $n){ // Sort array in// non-decreasing ordersort($arr); // Initialize difference// as infinite$diff = PHP_INT_MAX; // Find the min diff by// comparing adjacent// pairs in sorted arrayfor ($i = 0; $i < $n - 1; $i++) if ($arr[$i + 1] - $arr[$i] < $diff) $diff = $arr[$i + 1] - $arr[$i]; // Return min diffreturn $diff;} // Driver code$arr = array(1, 5, 3, 19, 18, 25);$n = sizeof($arr);echo "Minimum difference is " , findMinDiff($arr, $n); // This code is contributed ajit?> <script> // Javascript program to find minimum // difference between any pair // in an unsorted array // Returns minimum difference // between any pair function findMinDiff(arr, n) { // Sort array in // non-decreasing order arr.sort(function(a, b) {return a - b}); // Initialize difference // as infinite let diff = Number.MAX_VALUE; // Find the min diff by // comparing adjacent pairs // in sorted array for (let i = 0; i < n - 1; i++) if (arr[i + 1] - arr[i] < diff) diff = arr[i + 1] - arr[i]; // Return min diff return diff; } let arr = [1, 5, 3, 19, 18, 25]; document.write("Minimum difference is " + findMinDiff(arr, arr.length)); </script> Output : Minimum difference is 1 YouTubeGeeksforGeeks507K subscribersFind minimum difference between any two elements | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:02•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Cr20pvlhqBU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Harshit Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal vt_m jit_t chinmoy1997pal divyesh072019 amartyaniel20 Amazon Arrays Sorting Amazon Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays in C/C++ Write a program to reverse an array or string Program for array rotation Largest Sum Contiguous Subarray
[ { "code": null, "e": 42520, "s": 42492, "text": "\n21 Jan, 2022" }, { "code": null, "e": 42616, "s": 42520, "text": "Given an unsorted array, find the minimum difference between any pair in given array.Examples :" }, { "code": null, "e": 42864, "s": 42616, "text": "Input : {1, 5, 3, 19, 18, 25};\nOutput : 1\nMinimum difference is between 18 and 19\n\nInput : {30, 5, 20, 9};\nOutput : 4\nMinimum difference is between 5 and 9\n\nInput : {1, 19, -4, 31, 38, 25, 100};\nOutput : 5\nMinimum difference is between 1 and -4" }, { "code": null, "e": 42931, "s": 42866, "text": "Method 1 (Simple: O(n2) A simple solution is to use two loops. " }, { "code": null, "e": 42935, "s": 42931, "text": "C++" }, { "code": null, "e": 42940, "s": 42935, "text": "Java" }, { "code": null, "e": 42948, "s": 42940, "text": "Python3" }, { "code": null, "e": 42951, "s": 42948, "text": "C#" }, { "code": null, "e": 42955, "s": 42951, "text": "PHP" }, { "code": null, "e": 42966, "s": 42955, "text": "Javascript" }, { "code": "// C++ implementation of simple method to find// minimum difference between any pair#include <bits/stdc++.h>using namespace std; // Returns minimum difference between any pairint findMinDiff(int arr[], int n){// Initialize difference as infiniteint diff = INT_MAX; // Find the min diff by comparing difference// of all possible pairs in given arrayfor (int i=0; i<n-1; i++) for (int j=i+1; j<n; j++) if (abs(arr[i] - arr[j]) < diff) diff = abs(arr[i] - arr[j]); // Return min diffreturn diff;} // Driver codeint main(){int arr[] = {1, 5, 3, 19, 18, 25};int n = sizeof(arr)/sizeof(arr[0]);cout << \"Minimum difference is \" << findMinDiff(arr, n);return 0;}", "e": 43646, "s": 42966, "text": null }, { "code": "// Java implementation of simple method to find// minimum difference between any pair class GFG{ // Returns minimum difference between any pair static int findMinDiff(int[] arr, int n) { // Initialize difference as infinite int diff = Integer.MAX_VALUE; // Find the min diff by comparing difference // of all possible pairs in given array for (int i=0; i<n-1; i++) for (int j=i+1; j<n; j++) if (Math.abs((arr[i] - arr[j]) )< diff) diff = Math.abs((arr[i] - arr[j])); // Return min diff return diff; } // Driver method to test the above function public static void main(String[] args) { int arr[] = new int[]{1, 5, 3, 19, 18, 25}; System.out.println(\"Minimum difference is \"+ findMinDiff(arr, arr.length)); }}", "e": 44535, "s": 43646, "text": null }, { "code": "# Python implementation of simple method to find# minimum difference between any pair # Returns minimum difference between any pairdef findMinDiff(arr, n): # Initialize difference as infinite diff = 10**20 # Find the min diff by comparing difference # of all possible pairs in given array for i in range(n-1): for j in range(i+1,n): if abs(arr[i]-arr[j]) < diff: diff = abs(arr[i] - arr[j]) # Return min diff return diff # Driver codearr = [1, 5, 3, 19, 18, 25]n = len(arr)print(\"Minimum difference is \" + str(findMinDiff(arr, n))) # This code is contributed by Pratik Chhajer", "e": 45172, "s": 44535, "text": null }, { "code": "// C# implementation of simple method to find// minimum difference between any pairusing System; class GFG { // Returns minimum difference between any pair static int findMinDiff(int []arr, int n) { // Initialize difference as infinite int diff = int.MaxValue; // Find the min diff by comparing difference // of all possible pairs in given array for (int i = 0; i < n-1; i++) for (int j = i+1; j < n; j++) if (Math.Abs((arr[i] - arr[j]) ) < diff) diff = Math.Abs((arr[i] - arr[j])); // Return min diff return diff; } // Driver method to test the above function public static void Main() { int []arr = new int[]{1, 5, 3, 19, 18, 25}; Console.Write(\"Minimum difference is \" + findMinDiff(arr, arr.Length)); }} // This code is contributed by nitin mittal.", "e": 46105, "s": 45172, "text": null }, { "code": "<?php// PHP implementation of simple// method to find minimum// difference between any pair // Returns minimum difference// between any pairfunction findMinDiff($arr, $n){// Initialize difference// as infinite$diff = PHP_INT_MAX; // Find the min diff by comparing// difference of all possible// pairs in given arrayfor ($i = 0; $i < $n - 1; $i++) for ($j = $i + 1; $j < $n; $j++) if (abs($arr[$i] - $arr[$j]) < $diff) $diff = abs($arr[$i] - $arr[$j]); // Return min diffreturn $diff;} // Driver code$arr = array(1, 5, 3, 19, 18, 25);$n = sizeof($arr);echo \"Minimum difference is \" , findMinDiff($arr, $n); // This code is contributed by ajit?>", "e": 46782, "s": 46105, "text": null }, { "code": "<script> // JavaScript program implementation of simple method to find// minimum difference between any pair // Returns minimum difference between any pair function findMinDiff( arr, n) { // Initialize difference as infinite let diff = Number.MAX_VALUE; // Find the min diff by comparing difference // of all possible pairs in given array for (let i=0; i<n-1; i++) for (let j=i+1; j<n; j++) if (Math.abs((arr[i] - arr[j]) )< diff) diff = Math.abs((arr[i] - arr[j])); // Return min diff return diff; } // Driver Code let arr = [1, 5, 3, 19, 18, 25]; document.write(\"Minimum difference is \"+ findMinDiff(arr, arr.length)); </script>", "e": 47581, "s": 46782, "text": null }, { "code": null, "e": 47590, "s": 47581, "text": "Output :" }, { "code": null, "e": 47614, "s": 47590, "text": "Minimum difference is 1" }, { "code": null, "e": 47975, "s": 47614, "text": " Method 2 (Efficient: O(n Log n) The idea is to use sorting. Below are steps. 1) Sort array in ascending order. This step takes O(n Log n) time. 2) Initialize difference as infinite. This step takes O(1) time. 3) Compare all adjacent pairs in sorted array and keep track of minimum difference. This step takes O(n) time.Below is implementation of above idea. " }, { "code": null, "e": 47979, "s": 47975, "text": "C++" }, { "code": null, "e": 47984, "s": 47979, "text": "Java" }, { "code": null, "e": 47992, "s": 47984, "text": "Python3" }, { "code": null, "e": 47995, "s": 47992, "text": "C#" }, { "code": null, "e": 47999, "s": 47995, "text": "PHP" }, { "code": null, "e": 48010, "s": 47999, "text": "Javascript" }, { "code": "// C++ program to find minimum difference between// any pair in an unsorted array#include <bits/stdc++.h>using namespace std; // Returns minimum difference between any pairint findMinDiff(int arr[], int n){ // Sort array in non-decreasing order sort(arr, arr+n); // Initialize difference as infinite int diff = INT_MAX; // Find the min diff by comparing adjacent // pairs in sorted array for (int i=0; i<n-1; i++) if (arr[i+1] - arr[i] < diff) diff = arr[i+1] - arr[i]; // Return min diff return diff;} // Driver codeint main(){ int arr[] = {1, 5, 3, 19, 18, 25}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Minimum difference is \" << findMinDiff(arr, n); return 0;}", "e": 48721, "s": 48010, "text": null }, { "code": "// Java program to find minimum difference between// any pair in an unsorted array import java.util.Arrays; class GFG{ // Returns minimum difference between any pair static int findMinDiff(int[] arr, int n) { // Sort array in non-decreasing order Arrays.sort(arr); // Initialize difference as infinite int diff = Integer.MAX_VALUE; // Find the min diff by comparing adjacent // pairs in sorted array for (int i=0; i<n-1; i++) if (arr[i+1] - arr[i] < diff) diff = arr[i+1] - arr[i]; // Return min diff return diff; } // Driver method to test the above function public static void main(String[] args) { int arr[] = new int[]{1, 5, 3, 19, 18, 25}; System.out.println(\"Minimum difference is \"+ findMinDiff(arr, arr.length)); }}", "e": 49668, "s": 48721, "text": null }, { "code": "# Python program to find minimum difference between# any pair in an unsorted array # Returns minimum difference between any pairdef findMinDiff(arr, n): # Sort array in non-decreasing order arr = sorted(arr) # Initialize difference as infinite diff = 10**20 # Find the min diff by comparing adjacent # pairs in sorted array for i in range(n-1): if arr[i+1] - arr[i] < diff: diff = arr[i+1] - arr[i] # Return min diff return diff # Driver codearr = [1, 5, 3, 19, 18, 25]n = len(arr)print(\"Minimum difference is \" + str(findMinDiff(arr, n))) # This code is contributed by Pratik Chhajer", "e": 50302, "s": 49668, "text": null }, { "code": "// C# program to find minimum// difference between any pair// in an unsorted arrayusing System; class GFG{ // Returns minimum difference // between any pair static int findMinDiff(int[] arr, int n) { // Sort array in // non-decreasing order Array.Sort(arr); // Initialize difference // as infinite int diff = int.MaxValue; // Find the min diff by // comparing adjacent pairs // in sorted array for (int i = 0; i < n - 1; i++) if (arr[i + 1] - arr[i] < diff) diff = arr[i + 1] - arr[i]; // Return min diff return diff; } // Driver Code public static void Main() { int []arr = new int[]{1, 5, 3, 19, 18, 25}; Console.WriteLine(\"Minimum difference is \" + findMinDiff(arr, arr.Length)); }} //This code is contributed by anuj_67.", "e": 51263, "s": 50302, "text": null }, { "code": "<?php// PHP program to find minimum// difference between any pair// in an unsorted array // Returns minimum difference// between any pairfunction findMinDiff($arr, $n){ // Sort array in// non-decreasing ordersort($arr); // Initialize difference// as infinite$diff = PHP_INT_MAX; // Find the min diff by// comparing adjacent// pairs in sorted arrayfor ($i = 0; $i < $n - 1; $i++) if ($arr[$i + 1] - $arr[$i] < $diff) $diff = $arr[$i + 1] - $arr[$i]; // Return min diffreturn $diff;} // Driver code$arr = array(1, 5, 3, 19, 18, 25);$n = sizeof($arr);echo \"Minimum difference is \" , findMinDiff($arr, $n); // This code is contributed ajit?>", "e": 51923, "s": 51263, "text": null }, { "code": "<script> // Javascript program to find minimum // difference between any pair // in an unsorted array // Returns minimum difference // between any pair function findMinDiff(arr, n) { // Sort array in // non-decreasing order arr.sort(function(a, b) {return a - b}); // Initialize difference // as infinite let diff = Number.MAX_VALUE; // Find the min diff by // comparing adjacent pairs // in sorted array for (let i = 0; i < n - 1; i++) if (arr[i + 1] - arr[i] < diff) diff = arr[i + 1] - arr[i]; // Return min diff return diff; } let arr = [1, 5, 3, 19, 18, 25]; document.write(\"Minimum difference is \" + findMinDiff(arr, arr.length)); </script>", "e": 52765, "s": 51923, "text": null }, { "code": null, "e": 52775, "s": 52765, "text": "Output : " }, { "code": null, "e": 52799, "s": 52775, "text": "Minimum difference is 1" }, { "code": null, "e": 53648, "s": 52801, "text": "YouTubeGeeksforGeeks507K subscribersFind minimum difference between any two elements | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:02•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Cr20pvlhqBU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 53824, "s": 53650, "text": "This article is contributed by Harshit Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 53837, "s": 53824, "text": "nitin mittal" }, { "code": null, "e": 53842, "s": 53837, "text": "vt_m" }, { "code": null, "e": 53848, "s": 53842, "text": "jit_t" }, { "code": null, "e": 53863, "s": 53848, "text": "chinmoy1997pal" }, { "code": null, "e": 53877, "s": 53863, "text": "divyesh072019" }, { "code": null, "e": 53891, "s": 53877, "text": "amartyaniel20" }, { "code": null, "e": 53898, "s": 53891, "text": "Amazon" }, { "code": null, "e": 53905, "s": 53898, "text": "Arrays" }, { "code": null, "e": 53913, "s": 53905, "text": "Sorting" }, { "code": null, "e": 53920, "s": 53913, "text": "Amazon" }, { "code": null, "e": 53927, "s": 53920, "text": "Arrays" }, { "code": null, "e": 53935, "s": 53927, "text": "Sorting" }, { "code": null, "e": 54033, "s": 53935, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54048, "s": 54033, "text": "Arrays in Java" }, { "code": null, "e": 54064, "s": 54048, "text": "Arrays in C/C++" }, { "code": null, "e": 54110, "s": 54064, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 54137, "s": 54110, "text": "Program for array rotation" } ]
NLP | Brill Tagger - GeeksforGeeks
05 Jun, 2020 BrillTagger class is a transformation-based tagger. It is not a subclass of SequentialBackoffTagger. Moreover, it uses a series of rules to correct the results of an initial tagger. These rules it follows are scored based. This score is equal to the no. of errors they correct minus the no. of new errors they produce. Code #1 : Training a BrillTagger class # Loading Librariesfrom nltk.tag import brill, brill_trainer def train_brill_tagger(initial_tagger, train_sents, **kwargs): templates = [ brill.Template(brill.Pos([-1])), brill.Template(brill.Pos([1])), brill.Template(brill.Pos([-2])), brill.Template(brill.Pos([2])), brill.Template(brill.Pos([-2, -1])), brill.Template(brill.Pos([1, 2])), brill.Template(brill.Pos([-3, -2, -1])), brill.Template(brill.Pos([1, 2, 3])), brill.Template(brill.Pos([-1]), brill.Pos([1])), brill.Template(brill.Word([-1])), brill.Template(brill.Word([1])), brill.Template(brill.Word([-2])), brill.Template(brill.Word([2])), brill.Template(brill.Word([-2, -1])), brill.Template(brill.Word([1, 2])), brill.Template(brill.Word([-3, -2, -1])), brill.Template(brill.Word([1, 2, 3])), brill.Template(brill.Word([-1]), brill.Word([1])), ] # Using BrillTaggerTrainer to train trainer = brill_trainer.BrillTaggerTrainer( initial_tagger, templates, deterministic = True) return trainer.train(train_sents, **kwargs) Code #2 : Let’s use the trained BrillTagger from nltk.tag import brill, brill_trainerfrom nltk.tag import DefaultTaggerfrom nltk.corpus import treebankfrom tag_util import train_brill_tagger # Initializingdefault_tag = DefaultTagger('NN') # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] initial_tag = backoff_tagger( train_data, [UnigramTagger, BigramTagger, TrigramTagger], backoff = default_tagger) a = initial_tag.evaluate(test_data)print ("Accuracy of Initial Tag : ", a) Output : Accuracy of Initial Tag : 0.8806820634578028 Code #3 : brill_tag = train_brill_tagger(initial_tag, train_data)b = brill_tag.evaluate(test_data) print ("Accuracy of brill_tag : ", b) Output : Accuracy of brill_tag : 0.8827541549751781 Akanksha_Rai Code_Mech Natural-language-processing Python-nltk Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25589, "s": 25561, "text": "\n05 Jun, 2020" }, { "code": null, "e": 25690, "s": 25589, "text": "BrillTagger class is a transformation-based tagger. It is not a subclass of SequentialBackoffTagger." }, { "code": null, "e": 25771, "s": 25690, "text": "Moreover, it uses a series of rules to correct the results of an initial tagger." }, { "code": null, "e": 25908, "s": 25771, "text": "These rules it follows are scored based. This score is equal to the no. of errors they correct minus the no. of new errors they produce." }, { "code": null, "e": 25947, "s": 25908, "text": "Code #1 : Training a BrillTagger class" }, { "code": "# Loading Librariesfrom nltk.tag import brill, brill_trainer def train_brill_tagger(initial_tagger, train_sents, **kwargs): templates = [ brill.Template(brill.Pos([-1])), brill.Template(brill.Pos([1])), brill.Template(brill.Pos([-2])), brill.Template(brill.Pos([2])), brill.Template(brill.Pos([-2, -1])), brill.Template(brill.Pos([1, 2])), brill.Template(brill.Pos([-3, -2, -1])), brill.Template(brill.Pos([1, 2, 3])), brill.Template(brill.Pos([-1]), brill.Pos([1])), brill.Template(brill.Word([-1])), brill.Template(brill.Word([1])), brill.Template(brill.Word([-2])), brill.Template(brill.Word([2])), brill.Template(brill.Word([-2, -1])), brill.Template(brill.Word([1, 2])), brill.Template(brill.Word([-3, -2, -1])), brill.Template(brill.Word([1, 2, 3])), brill.Template(brill.Word([-1]), brill.Word([1])), ] # Using BrillTaggerTrainer to train trainer = brill_trainer.BrillTaggerTrainer( initial_tagger, templates, deterministic = True) return trainer.train(train_sents, **kwargs)", "e": 27176, "s": 25947, "text": null }, { "code": null, "e": 27221, "s": 27176, "text": " Code #2 : Let’s use the trained BrillTagger" }, { "code": "from nltk.tag import brill, brill_trainerfrom nltk.tag import DefaultTaggerfrom nltk.corpus import treebankfrom tag_util import train_brill_tagger # Initializingdefault_tag = DefaultTagger('NN') # initializing training and testing set train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:] initial_tag = backoff_tagger( train_data, [UnigramTagger, BigramTagger, TrigramTagger], backoff = default_tagger) a = initial_tag.evaluate(test_data)print (\"Accuracy of Initial Tag : \", a)", "e": 27769, "s": 27221, "text": null }, { "code": null, "e": 27778, "s": 27769, "text": "Output :" }, { "code": null, "e": 27824, "s": 27778, "text": "Accuracy of Initial Tag : 0.8806820634578028\n" }, { "code": null, "e": 27835, "s": 27824, "text": " Code #3 :" }, { "code": "brill_tag = train_brill_tagger(initial_tag, train_data)b = brill_tag.evaluate(test_data) print (\"Accuracy of brill_tag : \", b)", "e": 27963, "s": 27835, "text": null }, { "code": null, "e": 27972, "s": 27963, "text": "Output :" }, { "code": null, "e": 28016, "s": 27972, "text": "Accuracy of brill_tag : 0.8827541549751781\n" }, { "code": null, "e": 28029, "s": 28016, "text": "Akanksha_Rai" }, { "code": null, "e": 28039, "s": 28029, "text": "Code_Mech" }, { "code": null, "e": 28067, "s": 28039, "text": "Natural-language-processing" }, { "code": null, "e": 28079, "s": 28067, "text": "Python-nltk" }, { "code": null, "e": 28096, "s": 28079, "text": "Machine Learning" }, { "code": null, "e": 28103, "s": 28096, "text": "Python" }, { "code": null, "e": 28120, "s": 28103, "text": "Machine Learning" }, { "code": null, "e": 28218, "s": 28120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28259, "s": 28218, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 28292, "s": 28259, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28320, "s": 28292, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 28356, "s": 28320, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 28411, "s": 28356, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 28439, "s": 28411, "text": "Read JSON file using Python" }, { "code": null, "e": 28489, "s": 28439, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28511, "s": 28489, "text": "Python map() function" } ]
Dictionary get() Method in Java with Examples - GeeksforGeeks
27 Dec, 2018 The get() method of Dictionary class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the dictionary contains no such mapping for the key. Syntax: DICTIONARY.get(Object key_element) Parameters: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched. Return Value: The method returns the value associated with the key_element in the parameter. Below programs are used to illustrate the working of java.util.Dictionary.get() Method:Program 1: // Java code to illustrate the get() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<Integer, String> dict = new Hashtable<Integer, String>(); // Inserting the values into dictionary dict.put(10, "Geeks"); dict.put(15, "4"); dict.put(20, "Geeks"); dict.put(25, "Welcomes"); dict.put(30, "You"); // Displaying the Dictionary System.out.println("Initial Dictionary is: " + dict); // Getting the value of 25 System.out.println("The Value is: " + dict.get(25)); // Getting the value of 10 System.out.println("The Value is: " + dict.get(10)); }} Initial Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes} The Value is: Welcomes The Value is: Geeks Program 2: // Java code to illustrate the get() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<String, Integer> dict = new Hashtable<String, Integer>(); // Inserting the values into dictionary dict.put("Geeks", 10); dict.put("4", 15); dict.put("Geeks", 20); dict.put("Welcomes", 25); dict.put("You", 30); // Displaying the Dictionary System.out.println("Initial Dictionary is: " + dict); // Getting the value of 25 System.out.println("The Value is: " + dict.get("Geeks")); // Getting the value of 10 System.out.println("The Value is: " + dict.get(20)); }} Initial Dictionary is: {You=30, Welcomes=25, 4=15, Geeks=20} The Value is: 20 The Value is: null Java - util package Java-Collections Java-Dictionary Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25695, "s": 25667, "text": "\n27 Dec, 2018" }, { "code": null, "e": 25900, "s": 25695, "text": "The get() method of Dictionary class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the dictionary contains no such mapping for the key." }, { "code": null, "e": 25908, "s": 25900, "text": "Syntax:" }, { "code": null, "e": 25943, "s": 25908, "text": "DICTIONARY.get(Object key_element)" }, { "code": null, "e": 26085, "s": 25943, "text": "Parameters: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched." }, { "code": null, "e": 26178, "s": 26085, "text": "Return Value: The method returns the value associated with the key_element in the parameter." }, { "code": null, "e": 26276, "s": 26178, "text": "Below programs are used to illustrate the working of java.util.Dictionary.get() Method:Program 1:" }, { "code": "// Java code to illustrate the get() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<Integer, String> dict = new Hashtable<Integer, String>(); // Inserting the values into dictionary dict.put(10, \"Geeks\"); dict.put(15, \"4\"); dict.put(20, \"Geeks\"); dict.put(25, \"Welcomes\"); dict.put(30, \"You\"); // Displaying the Dictionary System.out.println(\"Initial Dictionary is: \" + dict); // Getting the value of 25 System.out.println(\"The Value is: \" + dict.get(25)); // Getting the value of 10 System.out.println(\"The Value is: \" + dict.get(10)); }}", "e": 27039, "s": 26276, "text": null }, { "code": null, "e": 27154, "s": 27039, "text": "Initial Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}\nThe Value is: Welcomes\nThe Value is: Geeks\n" }, { "code": null, "e": 27165, "s": 27154, "text": "Program 2:" }, { "code": "// Java code to illustrate the get() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<String, Integer> dict = new Hashtable<String, Integer>(); // Inserting the values into dictionary dict.put(\"Geeks\", 10); dict.put(\"4\", 15); dict.put(\"Geeks\", 20); dict.put(\"Welcomes\", 25); dict.put(\"You\", 30); // Displaying the Dictionary System.out.println(\"Initial Dictionary is: \" + dict); // Getting the value of 25 System.out.println(\"The Value is: \" + dict.get(\"Geeks\")); // Getting the value of 10 System.out.println(\"The Value is: \" + dict.get(20)); }}", "e": 28011, "s": 27165, "text": null }, { "code": null, "e": 28109, "s": 28011, "text": "Initial Dictionary is: {You=30, Welcomes=25, 4=15, Geeks=20}\nThe Value is: 20\nThe Value is: null\n" }, { "code": null, "e": 28129, "s": 28109, "text": "Java - util package" }, { "code": null, "e": 28146, "s": 28129, "text": "Java-Collections" }, { "code": null, "e": 28162, "s": 28146, "text": "Java-Dictionary" }, { "code": null, "e": 28177, "s": 28162, "text": "Java-Functions" }, { "code": null, "e": 28182, "s": 28177, "text": "Java" }, { "code": null, "e": 28187, "s": 28182, "text": "Java" }, { "code": null, "e": 28204, "s": 28187, "text": "Java-Collections" }, { "code": null, "e": 28302, "s": 28204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28353, "s": 28302, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28383, "s": 28353, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28398, "s": 28383, "text": "Stream In Java" }, { "code": null, "e": 28417, "s": 28398, "text": "Interfaces in Java" }, { "code": null, "e": 28448, "s": 28417, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28466, "s": 28448, "text": "ArrayList in Java" }, { "code": null, "e": 28498, "s": 28466, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28518, "s": 28498, "text": "Stack Class in Java" }, { "code": null, "e": 28550, "s": 28518, "text": "Multidimensional Arrays in Java" } ]
Highest power of 2 that divides a number represented in binary - GeeksforGeeks
16 Nov, 2021 Given binary string str, the task is to find the largest power of 2 that divides the decimal equivalent of the given binary number. Examples: Input: str = “100100” Output: 2 22 = 4 is the highest power of 2 that divides 36 (100100).Input: str = “10010” Output: 1 Approach: Starting from the right, count the number of 0s in the binary representation which is the highest power of 2 which will divide the number. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the highest power of 2// which divides the given binary numberint highestPower(string str, int len){ // To store the highest required power of 2 int ans = 0; // Counting number of consecutive zeros // from the end in the given binary string for (int i = len - 1; i >= 0; i--) { if (str[i] == '0') ans++; else break; } return ans;} // Driver codeint main(){ string str = "100100"; int len = str.length(); cout << highestPower(str, len); return 0;} // Java implementation of the approachclass GFG{ // Function to return the highest power of 2// which divides the given binary numberstatic int highestPower(String str, int len){ // To store the highest required power of 2 int ans = 0; // Counting number of consecutive zeros // from the end in the given binary string for (int i = len - 1; i >= 0; i--) { if (str.charAt(i) == '0') ans++; else break; } return ans;} // Driver codepublic static void main(String[] args){ String str = "100100"; int len = str.length(); System.out.println(highestPower(str, len));}} // This code is contributed by Code_Mech. # Python3 implementation of the approach # Function to return the highest power of 2# which divides the given binary numberdef highestPower(str, length): # To store the highest required power of 2 ans = 0; # Counting number of consecutive zeros # from the end in the given binary string for i in range(length-1,-1,-1): if (str[i] == '0'): ans+=1; else: break; return ans; # Driver codedef main(): str = "100100"; length = len(str); print(highestPower(str, length)); if __name__ == '__main__': main() # This code contributed by PrinciRaj1992 // C# implementation of the approachusing System; class GFG{ // Function to return the highest power of 2// which divides the given binary numberstatic int highestPower(String str, int len){ // To store the highest required power of 2 int ans = 0; // Counting number of consecutive zeros // from the end in the given binary string for (int i = len - 1; i >= 0; i--) { if (str[i] == '0') ans++; else break; } return ans;} // Driver codepublic static void Main(String[] args){ String str = "100100"; int len = str.Length; Console.WriteLine(highestPower(str, len));}} /* This code contributed by PrinciRaj1992 */ <?php// PHP implementation of the approach // Function to return the highest power of 2// which divides the given binary numberfunction highestPower($str, $len){ // To store the highest required power of 2 $ans = 0; // Counting number of consecutive zeros // from the end in the given binary string for ($i = $len - 1; $i >= 0; $i--) { if ($str[$i] == '0') $ans++; else break; } return $ans;} // Driver code$str = "100100";$len = strlen($str);echo highestPower($str, $len); // This code is contributed by Ryuga?> <script>// Javascript implementation of the approach // Function to return the highest power of 2// which divides the given binary numberfunction highestPower(str, len){ // To store the highest required power of 2 let ans = 0; // Counting number of consecutive zeros // from the end in the given binary string for (let i = len - 1; i >= 0; i--) { if (str[i] == '0') ans++; else break; } return ans;} // Driver code let str = "100100"; let len = str.length; document.write(highestPower(str, len)); </script> 2 Time Complexity: O(N) Auxiliary Space: O(1) ankthon Code_Mech princiraj1992 rishavmahato348 simmytarika5 surindertarika1234 rohan07 binary-representation Number Divisibility Bit Magic Competitive Programming Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Binary representation of a given number Add two numbers without using arithmetic operators Josephus problem | Set 1 (A O(n) Solution) Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 26553, "s": 26525, "text": "\n16 Nov, 2021" }, { "code": null, "e": 26685, "s": 26553, "text": "Given binary string str, the task is to find the largest power of 2 that divides the decimal equivalent of the given binary number." }, { "code": null, "e": 26697, "s": 26685, "text": "Examples: " }, { "code": null, "e": 26820, "s": 26697, "text": "Input: str = “100100” Output: 2 22 = 4 is the highest power of 2 that divides 36 (100100).Input: str = “10010” Output: 1 " }, { "code": null, "e": 26969, "s": 26820, "text": "Approach: Starting from the right, count the number of 0s in the binary representation which is the highest power of 2 which will divide the number." }, { "code": null, "e": 27021, "s": 26969, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27025, "s": 27021, "text": "C++" }, { "code": null, "e": 27030, "s": 27025, "text": "Java" }, { "code": null, "e": 27038, "s": 27030, "text": "Python3" }, { "code": null, "e": 27041, "s": 27038, "text": "C#" }, { "code": null, "e": 27045, "s": 27041, "text": "PHP" }, { "code": null, "e": 27056, "s": 27045, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the highest power of 2// which divides the given binary numberint highestPower(string str, int len){ // To store the highest required power of 2 int ans = 0; // Counting number of consecutive zeros // from the end in the given binary string for (int i = len - 1; i >= 0; i--) { if (str[i] == '0') ans++; else break; } return ans;} // Driver codeint main(){ string str = \"100100\"; int len = str.length(); cout << highestPower(str, len); return 0;}", "e": 27680, "s": 27056, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the highest power of 2// which divides the given binary numberstatic int highestPower(String str, int len){ // To store the highest required power of 2 int ans = 0; // Counting number of consecutive zeros // from the end in the given binary string for (int i = len - 1; i >= 0; i--) { if (str.charAt(i) == '0') ans++; else break; } return ans;} // Driver codepublic static void main(String[] args){ String str = \"100100\"; int len = str.length(); System.out.println(highestPower(str, len));}} // This code is contributed by Code_Mech.", "e": 28361, "s": 27680, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the highest power of 2# which divides the given binary numberdef highestPower(str, length): # To store the highest required power of 2 ans = 0; # Counting number of consecutive zeros # from the end in the given binary string for i in range(length-1,-1,-1): if (str[i] == '0'): ans+=1; else: break; return ans; # Driver codedef main(): str = \"100100\"; length = len(str); print(highestPower(str, length)); if __name__ == '__main__': main() # This code contributed by PrinciRaj1992", "e": 28970, "s": 28361, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the highest power of 2// which divides the given binary numberstatic int highestPower(String str, int len){ // To store the highest required power of 2 int ans = 0; // Counting number of consecutive zeros // from the end in the given binary string for (int i = len - 1; i >= 0; i--) { if (str[i] == '0') ans++; else break; } return ans;} // Driver codepublic static void Main(String[] args){ String str = \"100100\"; int len = str.Length; Console.WriteLine(highestPower(str, len));}} /* This code contributed by PrinciRaj1992 */", "e": 29660, "s": 28970, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the highest power of 2// which divides the given binary numberfunction highestPower($str, $len){ // To store the highest required power of 2 $ans = 0; // Counting number of consecutive zeros // from the end in the given binary string for ($i = $len - 1; $i >= 0; $i--) { if ($str[$i] == '0') $ans++; else break; } return $ans;} // Driver code$str = \"100100\";$len = strlen($str);echo highestPower($str, $len); // This code is contributed by Ryuga?>", "e": 30236, "s": 29660, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the highest power of 2// which divides the given binary numberfunction highestPower(str, len){ // To store the highest required power of 2 let ans = 0; // Counting number of consecutive zeros // from the end in the given binary string for (let i = len - 1; i >= 0; i--) { if (str[i] == '0') ans++; else break; } return ans;} // Driver code let str = \"100100\"; let len = str.length; document.write(highestPower(str, len)); </script>", "e": 30816, "s": 30236, "text": null }, { "code": null, "e": 30818, "s": 30816, "text": "2" }, { "code": null, "e": 30840, "s": 30818, "text": "Time Complexity: O(N)" }, { "code": null, "e": 30862, "s": 30840, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 30870, "s": 30862, "text": "ankthon" }, { "code": null, "e": 30880, "s": 30870, "text": "Code_Mech" }, { "code": null, "e": 30894, "s": 30880, "text": "princiraj1992" }, { "code": null, "e": 30910, "s": 30894, "text": "rishavmahato348" }, { "code": null, "e": 30923, "s": 30910, "text": "simmytarika5" }, { "code": null, "e": 30942, "s": 30923, "text": "surindertarika1234" }, { "code": null, "e": 30950, "s": 30942, "text": "rohan07" }, { "code": null, "e": 30972, "s": 30950, "text": "binary-representation" }, { "code": null, "e": 30992, "s": 30972, "text": "Number Divisibility" }, { "code": null, "e": 31002, "s": 30992, "text": "Bit Magic" }, { "code": null, "e": 31026, "s": 31002, "text": "Competitive Programming" }, { "code": null, "e": 31039, "s": 31026, "text": "Mathematical" }, { "code": null, "e": 31052, "s": 31039, "text": "Mathematical" }, { "code": null, "e": 31062, "s": 31052, "text": "Bit Magic" }, { "code": null, "e": 31160, "s": 31062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31190, "s": 31160, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 31236, "s": 31190, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 31276, "s": 31236, "text": "Binary representation of a given number" }, { "code": null, "e": 31327, "s": 31276, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 31370, "s": 31327, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 31413, "s": 31370, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 31456, "s": 31413, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 31497, "s": 31456, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31575, "s": 31497, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
PHP | Constructors and Destructors - GeeksforGeeks
04 Jul, 2021 Constructors are special member functions for initial settings of newly created object instances from a class, which is the key part of the object-oriented concept in PHP5.Constructors are the very basic building blocks that define the future object and its nature. You can say that the Constructors are the blueprints for object creation providing values for member functions and member variables.Once the object is initialized, the constructor is automatically called. Destructors are for destroying objects and automatically called at the end of execution.In this article, we are going to learn about object-oriented concepts of constructors and destructors. Both are special member functions of any class with different concepts but the same name except destructors are preceded by a ~ Tilda operator.Syntax: __construct(): function __construct() { // initialize the object and its properties by assigning //values } __destruct(): function __destruct() { // destroying the object or clean up resources here } Note: The constructor is defined in the public section of the Class. Even the values to properties of the class are set by Constructors.Constructor types: Default Constructor:It has no parameters, but the values to the default constructor can be passed dynamically. Parameterized Constructor: It takes the parameters, and also you can pass different values to the data members. Copy Constructor: It accepts the address of the other objects as a parameter. Inheritance: As Inheritance is an object-oriented concept, the Constructors are inherited from parent class to child class derived from it. Whenever the child class has constructor and destructor of their own, these are called in order of priority or preference. Pre-defined Default Constructor: By using function __construct(), you can define a constructor.Note: In the case of Pre-defined Constructor(__construct) and user-defined constructor in the same class, the Pre-defined Constructor becomes Constructor while user-defined constructor becomes the normal method.Program: php <?PHPclass Tree{ function Tree() { echo "Its a User-defined Constructor of the class Tree"; } function __construct() { echo "Its a Pre-defined Constructor of the class Tree"; }} $obj= new Tree();?> Output: Its a Pre-defined Constructor of the class Tree Parameterized Constructor: The constructor of the class accepts arguments or parameters. The -> operator is used to set value for the variables. In the constructor method, you can assign values to the variables during object creation.Program: php <?php class Employee{ Public $name; Public $position; function __construct($name,$position) { // This is initializing the class properties $this->name=$name; $this->profile=$position; } function show_details() { echo $this->name." : "; echo "Your position is ".$this->profile."\n"; }} $employee_obj= new Employee("Rakesh","developer");$employee_obj->show_details(); $employee2= new Employee("Vikas","Manager");$employee2->show_details(); ?> Output: Rakesh : Your position is developer Vikas : Your position is Manager Constructors start with two underscores and generally look like normal PHP functions. Sometimes these constructors are called as magic functions starting with two underscores and with some extra functionality than normal methods. After creating an object of some class that includes constructor, the content of constructor will be automatically executed.Note: If the PHP Class has a constructor, then at the time of object creation, the constructor of the class is called. The constructors have no Return Type, so they do not return anything not even void.Advantages of using Constructors: Constructors provides the ability to pass parameters which are helpful in automatic initialization of the member variables during creation time . The Constructors can have as many parameters as required and they can be defined with the default arguments. They encourage re-usability avoiding re-initializing whenever instance of the class is created . You can start session in constructor method so that you don’t have to start in all the functions everytime. They can call class member methods and functions. They can call other Constructors even from Parent class. Note : The __construct() method always have the public visibility factor. Program: php <?phpclass ParentClass { function __construct() { print "Parent class constructor.\n"; } } class ChildClass extends Parentclass { function __construct() { parent::__construct(); print "Child Class constructor"; } }$obj = new ParentClass();$obj = new ChildClass(); ?> Output Parent class constructor. Parent class constructor. Child Class constructor Note: Whenever child class object is created, the constructor of subclass will be automatically called.Destructor: Destructor is also a special member function which is exactly the reverse of constructor method and is called when an instance of the class is deleted from the memory. Destructors (__destruct ( void): void) are methods which are called when there is no reference to any object of the class or goes out of scope or about to release explicitly. They don’t have any types or return value. It is just called before de-allocating memory for an object or during the finish of execution of PHP scripts or as soon as the execution control leaves the block. Global objects are destroyed when the full script or code terminates. Cleaning up of resources before memory release or closing of files takes place in the destructor method, whenever they are no longer needed in the code. The automatic destruction of class objects is handled by PHP Garbage Collector. ~ ClassName() { } Note: The destructor method is called when the PHP code is executed completely by its last line by using PHP exit() or die() functions. Program: php <?phpclass SomeClass { function __construct() { echo "In constructor, "; $this->name = "Class object! "; } function __destruct() { echo "destroying " . $this->name . "\n"; } }$obj = new Someclass(); ?> Output: In constructor, destroying Class object! Note: In the case of inheritance, and if both the child and parent Class have destructors then, the destructor of the derived class is called first, and then the destructor of the parent class. Advantages of destructors: Destructors give chance to objects to free up memory allocation , so that enough space is available for new objects or free up resources for other tasks. It effectively makes programs run more efficiently and are very useful as they carry out clean up tasks. Comparison between __constructors and __destructors: Conclusion: In the real programming world, Constructors and Destructor methods are very useful as they make very crucial tasks easier during coding. These encourage re-usability of code without unnecessary repetition. Both of them are implicitly called by compiler even they are not defined in the class. anikaseth98 PHP-OOP PHP PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ? How to delete an array element based on key in PHP? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? Comparing two dates in PHP PHP | strval() Function
[ { "code": null, "e": 32676, "s": 32648, "text": "\n04 Jul, 2021" }, { "code": null, "e": 33491, "s": 32676, "text": "Constructors are special member functions for initial settings of newly created object instances from a class, which is the key part of the object-oriented concept in PHP5.Constructors are the very basic building blocks that define the future object and its nature. You can say that the Constructors are the blueprints for object creation providing values for member functions and member variables.Once the object is initialized, the constructor is automatically called. Destructors are for destroying objects and automatically called at the end of execution.In this article, we are going to learn about object-oriented concepts of constructors and destructors. Both are special member functions of any class with different concepts but the same name except destructors are preceded by a ~ Tilda operator.Syntax: " }, { "code": null, "e": 33508, "s": 33491, "text": "__construct(): " }, { "code": null, "e": 33630, "s": 33508, "text": "function __construct()\n {\n // initialize the object and its properties by assigning \n //values\n }" }, { "code": null, "e": 33648, "s": 33632, "text": "__destruct(): " }, { "code": null, "e": 33749, "s": 33648, "text": "function __destruct() \n {\n // destroying the object or clean up resources here \n }" }, { "code": null, "e": 33906, "s": 33749, "text": "Note: The constructor is defined in the public section of the Class. Even the values to properties of the class are set by Constructors.Constructor types: " }, { "code": null, "e": 34017, "s": 33906, "text": "Default Constructor:It has no parameters, but the values to the default constructor can be passed dynamically." }, { "code": null, "e": 34129, "s": 34017, "text": "Parameterized Constructor: It takes the parameters, and also you can pass different values to the data members." }, { "code": null, "e": 34207, "s": 34129, "text": "Copy Constructor: It accepts the address of the other objects as a parameter." }, { "code": null, "e": 34787, "s": 34207, "text": "Inheritance: As Inheritance is an object-oriented concept, the Constructors are inherited from parent class to child class derived from it. Whenever the child class has constructor and destructor of their own, these are called in order of priority or preference. Pre-defined Default Constructor: By using function __construct(), you can define a constructor.Note: In the case of Pre-defined Constructor(__construct) and user-defined constructor in the same class, the Pre-defined Constructor becomes Constructor while user-defined constructor becomes the normal method.Program: " }, { "code": null, "e": 34791, "s": 34787, "text": "php" }, { "code": "<?PHPclass Tree{ function Tree() { echo \"Its a User-defined Constructor of the class Tree\"; } function __construct() { echo \"Its a Pre-defined Constructor of the class Tree\"; }} $obj= new Tree();?>", "e": 35022, "s": 34791, "text": null }, { "code": null, "e": 35032, "s": 35022, "text": "Output: " }, { "code": null, "e": 35080, "s": 35032, "text": "Its a Pre-defined Constructor of the class Tree" }, { "code": null, "e": 35325, "s": 35080, "text": "Parameterized Constructor: The constructor of the class accepts arguments or parameters. The -> operator is used to set value for the variables. In the constructor method, you can assign values to the variables during object creation.Program: " }, { "code": null, "e": 35329, "s": 35325, "text": "php" }, { "code": "<?php class Employee{ Public $name; Public $position; function __construct($name,$position) { // This is initializing the class properties $this->name=$name; $this->profile=$position; } function show_details() { echo $this->name.\" : \"; echo \"Your position is \".$this->profile.\"\\n\"; }} $employee_obj= new Employee(\"Rakesh\",\"developer\");$employee_obj->show_details(); $employee2= new Employee(\"Vikas\",\"Manager\");$employee2->show_details(); ?>", "e": 35851, "s": 35329, "text": null }, { "code": null, "e": 35861, "s": 35851, "text": "Output: " }, { "code": null, "e": 35930, "s": 35861, "text": "Rakesh : Your position is developer\nVikas : Your position is Manager" }, { "code": null, "e": 36522, "s": 35930, "text": "Constructors start with two underscores and generally look like normal PHP functions. Sometimes these constructors are called as magic functions starting with two underscores and with some extra functionality than normal methods. After creating an object of some class that includes constructor, the content of constructor will be automatically executed.Note: If the PHP Class has a constructor, then at the time of object creation, the constructor of the class is called. The constructors have no Return Type, so they do not return anything not even void.Advantages of using Constructors: " }, { "code": null, "e": 36668, "s": 36522, "text": "Constructors provides the ability to pass parameters which are helpful in automatic initialization of the member variables during creation time ." }, { "code": null, "e": 36777, "s": 36668, "text": "The Constructors can have as many parameters as required and they can be defined with the default arguments." }, { "code": null, "e": 36874, "s": 36777, "text": "They encourage re-usability avoiding re-initializing whenever instance of the class is created ." }, { "code": null, "e": 36982, "s": 36874, "text": "You can start session in constructor method so that you don’t have to start in all the functions everytime." }, { "code": null, "e": 37032, "s": 36982, "text": "They can call class member methods and functions." }, { "code": null, "e": 37089, "s": 37032, "text": "They can call other Constructors even from Parent class." }, { "code": null, "e": 37174, "s": 37089, "text": "Note : The __construct() method always have the public visibility factor. Program: " }, { "code": null, "e": 37178, "s": 37174, "text": "php" }, { "code": "<?phpclass ParentClass { function __construct() { print \"Parent class constructor.\\n\"; } } class ChildClass extends Parentclass { function __construct() { parent::__construct(); print \"Child Class constructor\"; } }$obj = new ParentClass();$obj = new ChildClass(); ?>", "e": 37532, "s": 37178, "text": null }, { "code": null, "e": 37541, "s": 37532, "text": "Output " }, { "code": null, "e": 37617, "s": 37541, "text": "Parent class constructor.\nParent class constructor.\nChild Class constructor" }, { "code": null, "e": 38585, "s": 37617, "text": "Note: Whenever child class object is created, the constructor of subclass will be automatically called.Destructor: Destructor is also a special member function which is exactly the reverse of constructor method and is called when an instance of the class is deleted from the memory. Destructors (__destruct ( void): void) are methods which are called when there is no reference to any object of the class or goes out of scope or about to release explicitly. They don’t have any types or return value. It is just called before de-allocating memory for an object or during the finish of execution of PHP scripts or as soon as the execution control leaves the block. Global objects are destroyed when the full script or code terminates. Cleaning up of resources before memory release or closing of files takes place in the destructor method, whenever they are no longer needed in the code. The automatic destruction of class objects is handled by PHP Garbage Collector. " }, { "code": null, "e": 38604, "s": 38585, "text": "~ ClassName()\n{\n\n}" }, { "code": null, "e": 38740, "s": 38604, "text": "Note: The destructor method is called when the PHP code is executed completely by its last line by using PHP exit() or die() functions." }, { "code": null, "e": 38751, "s": 38740, "text": "Program: " }, { "code": null, "e": 38755, "s": 38751, "text": "php" }, { "code": "<?phpclass SomeClass { function __construct() { echo \"In constructor, \"; $this->name = \"Class object! \"; } function __destruct() { echo \"destroying \" . $this->name . \"\\n\"; } }$obj = new Someclass(); ?>", "e": 39040, "s": 38755, "text": null }, { "code": null, "e": 39050, "s": 39040, "text": "Output: " }, { "code": null, "e": 39092, "s": 39050, "text": "In constructor, destroying Class object! " }, { "code": null, "e": 39288, "s": 39092, "text": "Note: In the case of inheritance, and if both the child and parent Class have destructors then, the destructor of the derived class is called first, and then the destructor of the parent class. " }, { "code": null, "e": 39317, "s": 39288, "text": "Advantages of destructors: " }, { "code": null, "e": 39471, "s": 39317, "text": "Destructors give chance to objects to free up memory allocation , so that enough space is available for new objects or free up resources for other tasks." }, { "code": null, "e": 39576, "s": 39471, "text": "It effectively makes programs run more efficiently and are very useful as they carry out clean up tasks." }, { "code": null, "e": 39630, "s": 39576, "text": "Comparison between __constructors and __destructors: " }, { "code": null, "e": 39938, "s": 39632, "text": "Conclusion: In the real programming world, Constructors and Destructor methods are very useful as they make very crucial tasks easier during coding. These encourage re-usability of code without unnecessary repetition. Both of them are implicitly called by compiler even they are not defined in the class. " }, { "code": null, "e": 39950, "s": 39938, "text": "anikaseth98" }, { "code": null, "e": 39958, "s": 39950, "text": "PHP-OOP" }, { "code": null, "e": 39962, "s": 39958, "text": "PHP" }, { "code": null, "e": 39966, "s": 39962, "text": "PHP" }, { "code": null, "e": 40064, "s": 39966, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40109, "s": 40064, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 40159, "s": 40109, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 40199, "s": 40159, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 40223, "s": 40199, "text": "PHP in_array() Function" }, { "code": null, "e": 40267, "s": 40223, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 40319, "s": 40267, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 40380, "s": 40319, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 40430, "s": 40380, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 40457, "s": 40430, "text": "Comparing two dates in PHP" } ]
PHP | Remove duplicate elements from Array - GeeksforGeeks
30 Mar, 2018 You are given an Array of n-elements.You have to remove the duplicate values without using any loop in PHP and print the array. Examples: Input : array[] = {2, 3, 1, 6, 1, 6, 2, 3} Output : array ( [6] => 2 [7] => 3 [4] => 1 [5] => 6 ) Input : array[] = {4, 2, 7, 3, 2, 7, 3} Output : array ( [0] => 4 [4] => 2 [5] => 7 [6] => 3 ) In C/Java, we have to traverse the array and for each element you have to check if its duplicate is present. But PHP provides an inbuilt function (array_flip()) with the use of which we can remove duplicate elements without the use of loop. The array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys. Note that the values of array need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be included in the result. Note: If a value has several occurrences, the latest key will be used as its value, and all others will be lost. Also as array_flip() returns array with preserved keys, we will use array_values() which will re-order the keys. Approach: The idea is to use this property of the array_flip() function of selecting the latest key as its value if the value has multiple occurrences. We will use the array_flip() function twice to remove the duplicate values. On using the array_flip() function for the first time, it will return an array with keys and values exchanged with removed duplicates. On using it the second time, it will again reorder it to the original configuration. Below is the implementation of above idea: <?php // define array $a = array(1, 5, 2, 5, 1, 3, 2, 4, 5); // print original array echo "Original Array : \n"; print_r($a); // remove duplicate values by using // flipping keys and values $a = array_flip($a); // restore the array elements by again // flipping keys and values. $a = array_flip($a); // re-order the array keys $a= array_values($a); // print updated array echo "\nUpdated Array : \n "; print_r($a);?> Output: Original Array : Array ( [0] => 1 [1] => 5 [2] => 2 [3] => 5 [4] => 1 [5] => 3 [6] => 2 [7] => 4 [8] => 5 ) Updated Array : Array ( [0] => 1 [1] => 5 [2] => 2 [3] => 3 [4] => 4 ) PHP-array PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP 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": 25717, "s": 25689, "text": "\n30 Mar, 2018" }, { "code": null, "e": 25845, "s": 25717, "text": "You are given an Array of n-elements.You have to remove the duplicate values without using any loop in PHP and print the array." }, { "code": null, "e": 25855, "s": 25845, "text": "Examples:" }, { "code": null, "e": 26209, "s": 25855, "text": "Input : array[] = {2, 3, 1, 6, 1, 6, 2, 3}\nOutput : array (\n [6] => 2\n [7] => 3\n [4] => 1\n [5] => 6\n )\n\nInput : array[] = {4, 2, 7, 3, 2, 7, 3}\nOutput : array (\n [0] => 4\n [4] => 2\n [5] => 7\n [6] => 3 \n )\n" }, { "code": null, "e": 26450, "s": 26209, "text": "In C/Java, we have to traverse the array and for each element you have to check if its duplicate is present. But PHP provides an inbuilt function (array_flip()) with the use of which we can remove duplicate elements without the use of loop." }, { "code": null, "e": 26569, "s": 26450, "text": "The array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys." }, { "code": null, "e": 26797, "s": 26569, "text": "Note that the values of array need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be included in the result." }, { "code": null, "e": 27023, "s": 26797, "text": "Note: If a value has several occurrences, the latest key will be used as its value, and all others will be lost. Also as array_flip() returns array with preserved keys, we will use array_values() which will re-order the keys." }, { "code": null, "e": 27471, "s": 27023, "text": "Approach: The idea is to use this property of the array_flip() function of selecting the latest key as its value if the value has multiple occurrences. We will use the array_flip() function twice to remove the duplicate values. On using the array_flip() function for the first time, it will return an array with keys and values exchanged with removed duplicates. On using it the second time, it will again reorder it to the original configuration." }, { "code": null, "e": 27514, "s": 27471, "text": "Below is the implementation of above idea:" }, { "code": "<?php // define array $a = array(1, 5, 2, 5, 1, 3, 2, 4, 5); // print original array echo \"Original Array : \\n\"; print_r($a); // remove duplicate values by using // flipping keys and values $a = array_flip($a); // restore the array elements by again // flipping keys and values. $a = array_flip($a); // re-order the array keys $a= array_values($a); // print updated array echo \"\\nUpdated Array : \\n \"; print_r($a);?>", "e": 27999, "s": 27514, "text": null }, { "code": null, "e": 28007, "s": 27999, "text": "Output:" }, { "code": null, "e": 28246, "s": 28007, "text": "Original Array : \nArray\n(\n [0] => 1\n [1] => 5\n [2] => 2\n [3] => 5\n [4] => 1\n [5] => 3\n [6] => 2\n [7] => 4\n [8] => 5\n)\n\nUpdated Array : \nArray\n(\n [0] => 1\n [1] => 5\n [2] => 2\n [3] => 3\n [4] => 4\n)\n" }, { "code": null, "e": 28256, "s": 28246, "text": "PHP-array" }, { "code": null, "e": 28260, "s": 28256, "text": "PHP" }, { "code": null, "e": 28277, "s": 28260, "text": "Web Technologies" }, { "code": null, "e": 28281, "s": 28277, "text": "PHP" }, { "code": null, "e": 28379, "s": 28281, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28429, "s": 28379, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28469, "s": 28429, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28514, "s": 28469, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 28556, "s": 28514, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 28608, "s": 28556, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 28648, "s": 28608, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28681, "s": 28648, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28726, "s": 28681, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28769, "s": 28726, "text": "How to fetch data from an API in ReactJS ?" } ]
SetUID, SetGID, and Sticky Bits in Linux File Permissions - GeeksforGeeks
07 Aug, 2019 As explained in the article Permissions in Linux, Linux uses a combination of bits to store the permissions of a file. We can change the permissions using the chmod command, which essentially changes the ‘r’, ‘w’ and ‘x’ characters associated with the file. Further, the ownership of files also depends on the uid (user ID) and the gid (group ID) of the creator, as discussed in this article. Similarly, when we launch a process, it runs with the uid and gid of the user who launched it. 1. The setuid bitThis bit is present for files which have executable permissions. The setuid bit simply indicates that when running the executable, it will set its permissions to that of the user who created it (owner), instead of setting it to the user who launched it. Similarly, there is a setgid bit which does the same for the gid. To locate the setuid, look for an ‘s’ instead of an ‘x’ in the executable bit of the file permissions. An example of an executable with setuid permission is passwd, as can be seen in the following output. ls -l /etc/passwd This returns the following output: -rwsr-xr-x root root 2447 Aug 29 2018 /etc/passwd As we can observe, the ‘x’ is replaced by an ‘s’ in the user section of the file permissions. To set the setuid bit, use the following command. chmod u+s To remove the setuid bit, use the following command. chmod u-s 2. The setgid bit The setgid affects both files as well as directories. When used on a file, it executes with the privileges of the group of the user who owns it instead of executing with those of the group of the user who executed it.When the bit is set for a directory, the set of files in that directory will have the same group as the group of the parent directory, and not that of the user who created those files. This is used for file sharing since they can be now modified by all the users who are part of the group of the parent directory. To locate the setgid bit, look for an ‘s’ in the group section of the file permissions, as shown in the example below. -rwxrwsr-x root root 1427 Aug 2 2019 sample_file To set the setgid bit, use the following command. chmod g+s To remove the setgid bit, use the following command. chmod g-s Security Risks The setuid bit is indeed quite useful in various applications, however, the executable programs supporting this feature should be carefully designed so as to not compromise on any security risks that follow, such as buffer overruns and path injection. If a vulnerable program runs with root privileges, the attacker could gain root access to the system through it. To dodge such possibilities, some operating systems ignore the setuid bit for executable shell scripts. 3. The sticky bitThe sticky bit was initially introduced to ‘stick’ an executable program’s text segment in the swap space even after the program has completed execution, to speed up the subsequent runs of the same program. However, these days the sticky bit means something entirely different. When a directory has the sticky bit set, its files can be deleted or renamed only by the file owner, directory owner and the root user. The command below shows how the sticky bit can be set. chmod +t Simply look for a ‘t’ character in the file permissions to locate the sticky bit. The snippet below shows how we can set the sticky bit for some directory “Gatos”, and how it prevents the new user from deleting a file in the directory. To remove the sticky bit, simply use the following command. chmod -t Since deleting a file is controlled by the write permission of the file, practical uses of the sticky bit involve world-writable directories such as ‘/tmp’ so that the delete permissions are reserved only for the owners of the file. linux-command Linux-Unix Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples Banker's Algorithm in Operating System Types of Operating Systems Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Paging in Operating System
[ { "code": null, "e": 25815, "s": 25787, "text": "\n07 Aug, 2019" }, { "code": null, "e": 26073, "s": 25815, "text": "As explained in the article Permissions in Linux, Linux uses a combination of bits to store the permissions of a file. We can change the permissions using the chmod command, which essentially changes the ‘r’, ‘w’ and ‘x’ characters associated with the file." }, { "code": null, "e": 26303, "s": 26073, "text": "Further, the ownership of files also depends on the uid (user ID) and the gid (group ID) of the creator, as discussed in this article. Similarly, when we launch a process, it runs with the uid and gid of the user who launched it." }, { "code": null, "e": 26640, "s": 26303, "text": "1. The setuid bitThis bit is present for files which have executable permissions. The setuid bit simply indicates that when running the executable, it will set its permissions to that of the user who created it (owner), instead of setting it to the user who launched it. Similarly, there is a setgid bit which does the same for the gid." }, { "code": null, "e": 26743, "s": 26640, "text": "To locate the setuid, look for an ‘s’ instead of an ‘x’ in the executable bit of the file permissions." }, { "code": null, "e": 26845, "s": 26743, "text": "An example of an executable with setuid permission is passwd, as can be seen in the following output." }, { "code": null, "e": 26864, "s": 26845, "text": "ls -l /etc/passwd\n" }, { "code": null, "e": 26899, "s": 26864, "text": "This returns the following output:" }, { "code": null, "e": 26951, "s": 26899, "text": "-rwsr-xr-x root root 2447 Aug 29 2018 /etc/passwd\n" }, { "code": null, "e": 27045, "s": 26951, "text": "As we can observe, the ‘x’ is replaced by an ‘s’ in the user section of the file permissions." }, { "code": null, "e": 27095, "s": 27045, "text": "To set the setuid bit, use the following command." }, { "code": null, "e": 27107, "s": 27095, "text": "chmod u+s \n" }, { "code": null, "e": 27160, "s": 27107, "text": "To remove the setuid bit, use the following command." }, { "code": null, "e": 27172, "s": 27160, "text": "chmod u-s \n" }, { "code": null, "e": 27190, "s": 27172, "text": "2. The setgid bit" }, { "code": null, "e": 27721, "s": 27190, "text": "The setgid affects both files as well as directories. When used on a file, it executes with the privileges of the group of the user who owns it instead of executing with those of the group of the user who executed it.When the bit is set for a directory, the set of files in that directory will have the same group as the group of the parent directory, and not that of the user who created those files. This is used for file sharing since they can be now modified by all the users who are part of the group of the parent directory." }, { "code": null, "e": 27840, "s": 27721, "text": "To locate the setgid bit, look for an ‘s’ in the group section of the file permissions, as shown in the example below." }, { "code": null, "e": 27890, "s": 27840, "text": "-rwxrwsr-x root root 1427 Aug 2 2019 sample_file\n" }, { "code": null, "e": 27940, "s": 27890, "text": "To set the setgid bit, use the following command." }, { "code": null, "e": 27952, "s": 27940, "text": "chmod g+s \n" }, { "code": null, "e": 28005, "s": 27952, "text": "To remove the setgid bit, use the following command." }, { "code": null, "e": 28017, "s": 28005, "text": "chmod g-s \n" }, { "code": null, "e": 28032, "s": 28017, "text": "Security Risks" }, { "code": null, "e": 28501, "s": 28032, "text": "The setuid bit is indeed quite useful in various applications, however, the executable programs supporting this feature should be carefully designed so as to not compromise on any security risks that follow, such as buffer overruns and path injection. If a vulnerable program runs with root privileges, the attacker could gain root access to the system through it. To dodge such possibilities, some operating systems ignore the setuid bit for executable shell scripts." }, { "code": null, "e": 28796, "s": 28501, "text": "3. The sticky bitThe sticky bit was initially introduced to ‘stick’ an executable program’s text segment in the swap space even after the program has completed execution, to speed up the subsequent runs of the same program. However, these days the sticky bit means something entirely different." }, { "code": null, "e": 28987, "s": 28796, "text": "When a directory has the sticky bit set, its files can be deleted or renamed only by the file owner, directory owner and the root user. The command below shows how the sticky bit can be set." }, { "code": null, "e": 28998, "s": 28987, "text": "chmod +t \n" }, { "code": null, "e": 29234, "s": 28998, "text": "Simply look for a ‘t’ character in the file permissions to locate the sticky bit. The snippet below shows how we can set the sticky bit for some directory “Gatos”, and how it prevents the new user from deleting a file in the directory." }, { "code": null, "e": 29294, "s": 29234, "text": "To remove the sticky bit, simply use the following command." }, { "code": null, "e": 29305, "s": 29294, "text": "chmod -t \n" }, { "code": null, "e": 29538, "s": 29305, "text": "Since deleting a file is controlled by the write permission of the file, practical uses of the sticky bit involve world-writable directories such as ‘/tmp’ so that the delete permissions are reserved only for the owners of the file." }, { "code": null, "e": 29552, "s": 29538, "text": "linux-command" }, { "code": null, "e": 29563, "s": 29552, "text": "Linux-Unix" }, { "code": null, "e": 29581, "s": 29563, "text": "Operating Systems" }, { "code": null, "e": 29599, "s": 29581, "text": "Operating Systems" }, { "code": null, "e": 29697, "s": 29599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29732, "s": 29697, "text": "tar command in Linux with examples" }, { "code": null, "e": 29768, "s": 29732, "text": "curl command in Linux with Examples" }, { "code": null, "e": 29806, "s": 29768, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 29839, "s": 29806, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 29875, "s": 29839, "text": "diff command in Linux with examples" }, { "code": null, "e": 29914, "s": 29875, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 29941, "s": 29914, "text": "Types of Operating Systems" }, { "code": null, "e": 29990, "s": 29941, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 30030, "s": 29990, "text": "Program for FCFS CPU Scheduling | Set 1" } ]
Substrings starting with vowel and ending with consonants and vice versa - GeeksforGeeks
04 May, 2022 Given a string s, count special substrings in it. A Substring of S is said to be special if either of the following properties is satisfied. It starts with a vowel and ends with a consonant. It starts with a consonant and ends with a vowel. Examples: Input : S = "aba" Output : 2 Substrings of S are : a, ab, aba, b, ba, a Out of these only 'ab' and 'ba' satisfy the condition for special Substring. So the answer is 2. Input : S = "adceba" Output : 9 A simple solution is to generate all substrings. For every substring check the condition of special string. If yes increment count. An efficient solution is to count vowels and consonants in every suffix of string. After counting these, we traverse string from beginning. For every consonant, we add number of vowels after it to result. Similarly, for every vowel, we add number of consonants after it. C++ Java Python3 C# Javascript // CPP program to count special strings#include <bits/stdc++.h>using namespace std; // Returns true if ch is vowelbool isVowel(char ch){ return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');} // function to check consonantbool isCons(char ch){ return (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u');} int countSpecial(string &str){ int len = str.length(); //in case of empty string, we can't fulfill the //required condition, hence we return ans as 0. if(len == 0) return 0; // co[i] is going to store counts // of consonants from str[len-1] // to str[i]. // vo[i] is going to store counts // of vowels from str[len-1] // to str[i]. int co[len + 1]; int vo[len + 1]; memset(co, 0, sizeof(co)); memset(vo, 0, sizeof(vo)); // Counting consonants and vowels // from end of string. if (isCons(str[len - 1]) == 1) co[len-1] = 1; else vo[len-1] = 1; for (int i = len-2; i >= 0; i--) { if (isCons(str[i]) == 1) { co[i] = co[i + 1] + 1; vo[i] = vo[i + 1]; } else { co[i] = co[i + 1]; vo[i] = vo[i + 1] + 1; } } // Now we traverse string from beginning long long ans = 0; for (int i = 0; i < len; i++) { // If vowel, then count of substrings // starting with str[i] is equal to // count of consonants after it. if (isVowel(str[i])) ans = ans + co[i + 1]; // If consonant, then count of // substrings starting with str[i] // is equal to count of vowels // after it. else ans = ans + vo[i + 1]; } return ans;} // driver programint main(){ string str = "adceba"; cout << countSpecial(str); return 0;} // Java program to count special stringsclass GfG{ // Returns true if ch is vowelstatic boolean isVowel(char ch){ return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');} // function to check consonantstatic boolean isCons(char ch){ return (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u');} static int countSpecial(char []str){ int len = str.length; //in case of empty string, we can't fullfill the //required condition, hence we return ans as 0. if(len == 0) return 0; // co[i] is going to store counts // of consonants from str[len-1] // to str[i]. // vo[i] is going to store counts // of vowels from str[len-1] // to str[i]. int co[] = new int[len + 1]; int vo[] = new int[len + 1]; // Counting consonants and vowels // from end of string. if (isCons(str[len - 1]) == true) co[len-1] = 1; else vo[len-1] = 1; for (int i = len-2; i >= 0; i--) { if (isCons(str[i]) == true) { co[i] = co[i + 1] + 1; vo[i] = vo[i + 1]; } else { co[i] = co[i + 1]; vo[i] = vo[i + 1] + 1; } } // Now we traverse string from beginning long ans = 0; for (int i = 0; i < len; i++) { // If vowel, then count of substrings // starting with str[i] is equal to // count of consonants after it. if (isVowel(str[i])) ans = ans + co[i + 1]; // If consonant, then count of // substrings starting with str[i] // is equal to count of vowels // after it. else ans = ans + vo[i + 1]; } return (int) ans;} // Driver programpublic static void main(String[] args){ String str = "adceba"; System.out.println(countSpecial(str.toCharArray()));}} // This code contributed by Rajput-Ji # Python3 program to count special strings # Returns true if ch is voweldef isVowel(ch): return (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u') # Function to check consonantdef isCons( ch): return (ch != 'a' and ch != 'e' and ch != 'i' and ch != 'o' and ch != 'u') def countSpecial(str): lent = len(str) #in case of empty string, we can't fullfill the #required condition, hence we return ans as 0. if lent == 0: return 0; # co[i] is going to store counts # of consonants from str[len-1] # to str[i]. # vo[i] is going to store counts # of vowels from str[len-1] # to str[i]. co = [] vo = [] for i in range(0, lent + 1): co.append(0) for i in range(0, lent + 1): vo.append(0) # Counting consonants and vowels # from end of string. if isCons(str[lent - 1]) == 1: co[lent-1] = 1 else: vo[lent - 1] = 1 for i in range(lent-2, -1,-1): if isCons(str[i]) == 1: co[i] = co[i + 1] + 1 vo[i] = vo[i + 1] else: co[i] = co[i + 1] vo[i] = vo[i + 1] + 1 # Now we traverse string from beginning ans = 0 for i in range(lent): #If vowel, then count of substrings # starting with str[i] is equal to # count of consonants after it. if isVowel(str[i]): ans = ans + co[i + 1] #If consonant, then count of # substrings starting with str[i] # is equal to count of vowels # after it. else: ans = ans + vo[i + 1] return ans # Driver Codestr = "adceba"print(countSpecial(str)) # This code is contributed by Upendra singh bartwal // C# program to count special stringsusing System; class GFG{ // Returns true if ch is vowelstatic Boolean isVowel(char ch){ return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');} // function to check consonantstatic Boolean isCons(char ch){ return (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u');} static int countSpecial(char []str){ int len = str.Length; //in case of empty string, we can't fullfill the //required condition, hence we return ans as 0. if(len == 0) return 0; // co[i] is going to store counts // of consonants from str[len-1] // to str[i]. // vo[i] is going to store counts // of vowels from str[len-1] // to str[i]. int []co = new int[len + 1]; int []vo = new int[len + 1]; // Counting consonants and vowels // from end of string. if (isCons(str[len - 1]) == true) co[len - 1] = 1; else vo[len - 1] = 1; for (int i = len - 2; i >= 0; i--) { if (isCons(str[i]) == true) { co[i] = co[i + 1] + 1; vo[i] = vo[i + 1]; } else { co[i] = co[i + 1]; vo[i] = vo[i + 1] + 1; } } // Now we traverse string from beginning long ans = 0; for (int i = 0; i < len; i++) { // If vowel, then count of substrings // starting with str[i] is equal to // count of consonants after it. if (isVowel(str[i])) ans = ans + co[i + 1]; // If consonant, then count of // substrings starting with str[i] // is equal to count of vowels // after it. else ans = ans + vo[i + 1]; } return (int) ans;} // Driver programpublic static void Main(String[] args){ String str = "adceba"; Console.WriteLine(countSpecial(str.ToCharArray()));}} // This code is contributed by Rajput-Ji <script> // JavaScript program to count special strings// Returns true if ch is vowelfunction isVowel(ch){ return(ch === "a" || ch === "e" || ch === "i" || ch === "o" || ch === "u");} // Function to check consonantfunction isCons(ch){ return(ch !== "a" && ch !== "e" && ch !== "i" && ch !== "o" && ch !== "u");} function countSpecial(str){ var len = str.length; //in case of empty string, we can't fullfill the //required condition, hence we return ans as 0. if(len == 0) return 0; // co[i] is going to store counts // of consonants from str[len-1] // to str[i]. // vo[i] is going to store counts // of vowels from str[len-1] // to str[i]. var co = new Array(len + 1).fill(0); var vo = new Array(len + 1).fill(0); // Counting consonants and vowels // from end of string. if (isCons(str[len - 1]) === true) co[len - 1] = 1; else vo[len - 1] = 1; for(var i = len - 2; i >= 0; i--) { if (isCons(str[i]) === true) { co[i] = co[i + 1] + 1; vo[i] = vo[i + 1]; } else { co[i] = co[i + 1]; vo[i] = vo[i + 1] + 1; } } // Now we traverse string from beginning var ans = 0; for(var i = 0; i < len; i++) { // If vowel, then count of substrings // starting with str[i] is equal to // count of consonants after it. if (isVowel(str[i])) ans = ans + co[i + 1]; // If consonant, then count of // substrings starting with str[i] // is equal to count of vowels // after it. else ans = ans + vo[i + 1]; } return parseInt(ans);} // Driver codevar str = "adceba"; document.write(countSpecial(str.split(""))); // This code is contributed by rdtank </script> 9 Time Complexity : O( |str| ) , as we make a linear traversal to count the number of vowels and consonants. Space Complexity for above solution : O( |str| ), as we make two arrays vo[] and co[] to store the number of vowels at any index i. The above solution can be optimized to be done in O(1) space complexity, by using only two variables instead of making two arrays to store vowels and consonants at any index i. Following code depicts the same : C++ C Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // function to check if a character is vowel or notbool isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; return false;} long long countSpecial(string str){ long long cnt = 0; int n = str.size(); // in case of single character or empty string // we can't fulfill the given condition , hence the // count is 0. if (n == 1 || n == 0) return 0; // variables to store count of total vowels and // consonants in the string long long vow = 0, cons = 0; for (int i = 0; i < n; i++) vow += isVowel(str[i]); cons = n - vow; for (int i = 0; i < n; i++) { // as we encounter a vowel, we add no. of consonants // after it to our answer and decrease the value of // vow by 1, indicating that now the remaining // string has one vowel less than current string if (isVowel(str[i])) { vow--; cnt += cons; } // same case as above for consonants else { cons--; cnt += vow; } } // finally we return the cnt as our answer return cnt;} int main(){ string str = "adceba"; cout << countSpecial(str); return 0;} #include <stdio.h> // function to check if a character is vowel or notint isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; return 0;} long long countSpecial(char str[], int n){ long long cnt = 0; // in case of single character or empty string // we can't fulfill the given condition , hence the // count is 0. if (n == 1 || n == 0) return 0; // variables to store count of total vowels and // consonants in the string long long vow = 0, cons = 0; for (int i = 0; i < n; i++) vow += isVowel(str[i]); cons = n - vow; for (int i = 0; i < n; i++) { // as we encounter a vowel, we add no. of consonants // after it to our answer and decrease the value of // vow by 1, indicating that now the remaining // string has one vowel less than current string if (isVowel(str[i])) { vow--; cnt += cons; } // same case as above for consonants else { cons--; cnt += vow; } } // finally we return the cnt as our answer return cnt;} int main(){ char str[] = { 'a', 'd', 'c', 'e', 'b', 'a' }; int n = sizeof(str) / sizeof(char); if (n == 0) { printf("0"); } else { long long count = countSpecial(str, n); printf("%lld", count); } return 0;} /*package whatever //do not write package name here */ import java.io.*; class GFG { // function to check if a character is vowel or not public static int isVowel(char ch) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; return 0; } public static long countSpecial(String str) { long cnt = 0; int n = str.length(); // in case of single character or empty string // we can't fulfill the given condition , hence the // count is 0. if (n == 1 || n == 0) return 0; // variables to store count of total vowels and // consonants in the string long vow = 0, cons = 0; for (int i = 0; i < n; i++) { char ch = str.charAt(i); vow += isVowel(ch); } cons = n - vow; for (int i = 0; i < n; i++) { char ch = str.charAt(i); // as we encounter a vowel, we add no. of // consonants after it to our answer // and decrease the value of vow by 1, // indicating that now the remaining // string has one vowel less than current string if (isVowel(ch) == 1) { vow--; cnt += cons; } // same case as above for consonants else { cons--; cnt += vow; } } // finally we return the cnt as our answer return cnt; } public static void main(String[] args) { String str = "adceba"; long count = countSpecial(str); System.out.println(count); }} '''package whatever #do not write package name here ''' # function to check if a character is vowel or notdef isVowel(ch): if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'): return 1; return 0; def countSpecial( str): cnt = 0; n = len(str); # in case of single character or empty string # we can't fulfill the given condition , hence the # count is 0. if (n == 1 or n == 0): return 0; # variables to store count of total vowels and # consonants in the string vow = 0 cons = 0; for i in range(n): ch = str[i]; vow += isVowel(ch); cons = n - vow; for i in range(n): ch = str[i]; # as we encounter a vowel, we add no. of # consonants after it to our answer # and decrease the value of vow by 1, # indicating that now the remaining # string has one vowel less than current string if (isVowel(ch) == 1): vow -= 1; cnt += cons; # same case as above for consonants else: cons -= 1; cnt += vow; # finally we return the cnt as our answer return cnt; # Driver codeif __name__ == '__main__': str = "adceba"; count = countSpecial(str); print(count); # This code is contributed by Rajput-Ji /*package whatever //do not write package name here */using System;class GFG{ // function to check if a character is vowel or not public static int isVowel(char ch) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; return 0; } public static long countSpecial(String str) { long cnt = 0; int n = str.Length; // in case of single character or empty string // we can't fulfill the given condition , hence the // count is 0. if (n == 1 || n == 0) return 0; // variables to store count of total vowels and // consonants in the string long vow = 0, cons = 0; for (int i = 0; i < n; i++) { char ch = str[i]; vow += isVowel(ch); } cons = n - vow; for (int i = 0; i < n; i++) { char ch = str[i]; // as we encounter a vowel, we add no. of // consonants after it to our answer // and decrease the value of vow by 1, // indicating that now the remaining // string has one vowel less than current string if (isVowel(ch) == 1) { vow--; cnt += cons; } // same case as above for consonants else { cons--; cnt += vow; } } // finally we return the cnt as our answer return cnt; } // Driver code public static void Main(String[] args) { string str = "adceba"; long count = countSpecial(str); Console.Write(count); }} // This code is contributed by shivanisinghss2110 <script>/*package whatever //do not write package name here */ // function to check if a character is vowel or notfunction isVowel(ch) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; return 0; } function countSpecial(str) { var cnt = 0; var n = str.length; // in case of single character or empty string // we can't fulfill the given condition , hence the // count is 0. if (n == 1 || n == 0) return 0; // variables to store count of total vowels and // consonants in the string var vow = 0, cons = 0; for (var i = 0; i < n; i++) { var ch = str.charAt(i); vow += isVowel(ch); } cons = n - vow; for (var i = 0; i < n; i++) { var ch = str.charAt(i); // as we encounter a vowel, we add no. of // consonants after it to our answer // and decrease the value of vow by 1, // indicating that now the remaining // string has one vowel less than current string if (isVowel(ch) == 1) { vow--; cnt += cons; } // same case as above for consonants else { cons--; cnt += vow; } } // finally we return the cnt as our answer return cnt; } var str = "adceba"; var count = countSpecial(str); document.write(count); // This code is contributed by shivanisinghss2110</script> 9 Time Complexity : O( |str| ) Space Complexity : O(1) Rajput-Ji rdtank rishabhdevba saurabh1990aror shivanisinghss2110 rkbhola5 prefix-sum Strings prefix-sum Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Check whether two strings are anagram of each other Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26619, "s": 26591, "text": "\n04 May, 2022" }, { "code": null, "e": 26761, "s": 26619, "text": "Given a string s, count special substrings in it. A Substring of S is said to be special if either of the following properties is satisfied. " }, { "code": null, "e": 26811, "s": 26761, "text": "It starts with a vowel and ends with a consonant." }, { "code": null, "e": 26861, "s": 26811, "text": "It starts with a consonant and ends with a vowel." }, { "code": null, "e": 26873, "s": 26861, "text": "Examples: " }, { "code": null, "e": 27077, "s": 26873, "text": "Input : S = \"aba\"\nOutput : 2\nSubstrings of S are : a, ab, aba, b, ba, a \nOut of these only 'ab' and 'ba' satisfy the\ncondition for special Substring. So the \nanswer is 2.\n\nInput : S = \"adceba\"\nOutput : 9" }, { "code": null, "e": 27481, "s": 27077, "text": "A simple solution is to generate all substrings. For every substring check the condition of special string. If yes increment count. An efficient solution is to count vowels and consonants in every suffix of string. After counting these, we traverse string from beginning. For every consonant, we add number of vowels after it to result. Similarly, for every vowel, we add number of consonants after it. " }, { "code": null, "e": 27485, "s": 27481, "text": "C++" }, { "code": null, "e": 27490, "s": 27485, "text": "Java" }, { "code": null, "e": 27498, "s": 27490, "text": "Python3" }, { "code": null, "e": 27501, "s": 27498, "text": "C#" }, { "code": null, "e": 27512, "s": 27501, "text": "Javascript" }, { "code": "// CPP program to count special strings#include <bits/stdc++.h>using namespace std; // Returns true if ch is vowelbool isVowel(char ch){ return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');} // function to check consonantbool isCons(char ch){ return (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u');} int countSpecial(string &str){ int len = str.length(); //in case of empty string, we can't fulfill the //required condition, hence we return ans as 0. if(len == 0) return 0; // co[i] is going to store counts // of consonants from str[len-1] // to str[i]. // vo[i] is going to store counts // of vowels from str[len-1] // to str[i]. int co[len + 1]; int vo[len + 1]; memset(co, 0, sizeof(co)); memset(vo, 0, sizeof(vo)); // Counting consonants and vowels // from end of string. if (isCons(str[len - 1]) == 1) co[len-1] = 1; else vo[len-1] = 1; for (int i = len-2; i >= 0; i--) { if (isCons(str[i]) == 1) { co[i] = co[i + 1] + 1; vo[i] = vo[i + 1]; } else { co[i] = co[i + 1]; vo[i] = vo[i + 1] + 1; } } // Now we traverse string from beginning long long ans = 0; for (int i = 0; i < len; i++) { // If vowel, then count of substrings // starting with str[i] is equal to // count of consonants after it. if (isVowel(str[i])) ans = ans + co[i + 1]; // If consonant, then count of // substrings starting with str[i] // is equal to count of vowels // after it. else ans = ans + vo[i + 1]; } return ans;} // driver programint main(){ string str = \"adceba\"; cout << countSpecial(str); return 0;}", "e": 29381, "s": 27512, "text": null }, { "code": "// Java program to count special stringsclass GfG{ // Returns true if ch is vowelstatic boolean isVowel(char ch){ return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');} // function to check consonantstatic boolean isCons(char ch){ return (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u');} static int countSpecial(char []str){ int len = str.length; //in case of empty string, we can't fullfill the //required condition, hence we return ans as 0. if(len == 0) return 0; // co[i] is going to store counts // of consonants from str[len-1] // to str[i]. // vo[i] is going to store counts // of vowels from str[len-1] // to str[i]. int co[] = new int[len + 1]; int vo[] = new int[len + 1]; // Counting consonants and vowels // from end of string. if (isCons(str[len - 1]) == true) co[len-1] = 1; else vo[len-1] = 1; for (int i = len-2; i >= 0; i--) { if (isCons(str[i]) == true) { co[i] = co[i + 1] + 1; vo[i] = vo[i + 1]; } else { co[i] = co[i + 1]; vo[i] = vo[i + 1] + 1; } } // Now we traverse string from beginning long ans = 0; for (int i = 0; i < len; i++) { // If vowel, then count of substrings // starting with str[i] is equal to // count of consonants after it. if (isVowel(str[i])) ans = ans + co[i + 1]; // If consonant, then count of // substrings starting with str[i] // is equal to count of vowels // after it. else ans = ans + vo[i + 1]; } return (int) ans;} // Driver programpublic static void main(String[] args){ String str = \"adceba\"; System.out.println(countSpecial(str.toCharArray()));}} // This code contributed by Rajput-Ji", "e": 31288, "s": 29381, "text": null }, { "code": "# Python3 program to count special strings # Returns true if ch is voweldef isVowel(ch): return (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u') # Function to check consonantdef isCons( ch): return (ch != 'a' and ch != 'e' and ch != 'i' and ch != 'o' and ch != 'u') def countSpecial(str): lent = len(str) #in case of empty string, we can't fullfill the #required condition, hence we return ans as 0. if lent == 0: return 0; # co[i] is going to store counts # of consonants from str[len-1] # to str[i]. # vo[i] is going to store counts # of vowels from str[len-1] # to str[i]. co = [] vo = [] for i in range(0, lent + 1): co.append(0) for i in range(0, lent + 1): vo.append(0) # Counting consonants and vowels # from end of string. if isCons(str[lent - 1]) == 1: co[lent-1] = 1 else: vo[lent - 1] = 1 for i in range(lent-2, -1,-1): if isCons(str[i]) == 1: co[i] = co[i + 1] + 1 vo[i] = vo[i + 1] else: co[i] = co[i + 1] vo[i] = vo[i + 1] + 1 # Now we traverse string from beginning ans = 0 for i in range(lent): #If vowel, then count of substrings # starting with str[i] is equal to # count of consonants after it. if isVowel(str[i]): ans = ans + co[i + 1] #If consonant, then count of # substrings starting with str[i] # is equal to count of vowels # after it. else: ans = ans + vo[i + 1] return ans # Driver Codestr = \"adceba\"print(countSpecial(str)) # This code is contributed by Upendra singh bartwal", "e": 33083, "s": 31288, "text": null }, { "code": "// C# program to count special stringsusing System; class GFG{ // Returns true if ch is vowelstatic Boolean isVowel(char ch){ return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');} // function to check consonantstatic Boolean isCons(char ch){ return (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u');} static int countSpecial(char []str){ int len = str.Length; //in case of empty string, we can't fullfill the //required condition, hence we return ans as 0. if(len == 0) return 0; // co[i] is going to store counts // of consonants from str[len-1] // to str[i]. // vo[i] is going to store counts // of vowels from str[len-1] // to str[i]. int []co = new int[len + 1]; int []vo = new int[len + 1]; // Counting consonants and vowels // from end of string. if (isCons(str[len - 1]) == true) co[len - 1] = 1; else vo[len - 1] = 1; for (int i = len - 2; i >= 0; i--) { if (isCons(str[i]) == true) { co[i] = co[i + 1] + 1; vo[i] = vo[i + 1]; } else { co[i] = co[i + 1]; vo[i] = vo[i + 1] + 1; } } // Now we traverse string from beginning long ans = 0; for (int i = 0; i < len; i++) { // If vowel, then count of substrings // starting with str[i] is equal to // count of consonants after it. if (isVowel(str[i])) ans = ans + co[i + 1]; // If consonant, then count of // substrings starting with str[i] // is equal to count of vowels // after it. else ans = ans + vo[i + 1]; } return (int) ans;} // Driver programpublic static void Main(String[] args){ String str = \"adceba\"; Console.WriteLine(countSpecial(str.ToCharArray()));}} // This code is contributed by Rajput-Ji", "e": 35008, "s": 33083, "text": null }, { "code": "<script> // JavaScript program to count special strings// Returns true if ch is vowelfunction isVowel(ch){ return(ch === \"a\" || ch === \"e\" || ch === \"i\" || ch === \"o\" || ch === \"u\");} // Function to check consonantfunction isCons(ch){ return(ch !== \"a\" && ch !== \"e\" && ch !== \"i\" && ch !== \"o\" && ch !== \"u\");} function countSpecial(str){ var len = str.length; //in case of empty string, we can't fullfill the //required condition, hence we return ans as 0. if(len == 0) return 0; // co[i] is going to store counts // of consonants from str[len-1] // to str[i]. // vo[i] is going to store counts // of vowels from str[len-1] // to str[i]. var co = new Array(len + 1).fill(0); var vo = new Array(len + 1).fill(0); // Counting consonants and vowels // from end of string. if (isCons(str[len - 1]) === true) co[len - 1] = 1; else vo[len - 1] = 1; for(var i = len - 2; i >= 0; i--) { if (isCons(str[i]) === true) { co[i] = co[i + 1] + 1; vo[i] = vo[i + 1]; } else { co[i] = co[i + 1]; vo[i] = vo[i + 1] + 1; } } // Now we traverse string from beginning var ans = 0; for(var i = 0; i < len; i++) { // If vowel, then count of substrings // starting with str[i] is equal to // count of consonants after it. if (isVowel(str[i])) ans = ans + co[i + 1]; // If consonant, then count of // substrings starting with str[i] // is equal to count of vowels // after it. else ans = ans + vo[i + 1]; } return parseInt(ans);} // Driver codevar str = \"adceba\"; document.write(countSpecial(str.split(\"\"))); // This code is contributed by rdtank </script>", "e": 36865, "s": 35008, "text": null }, { "code": null, "e": 36867, "s": 36865, "text": "9" }, { "code": null, "e": 36974, "s": 36867, "text": "Time Complexity : O( |str| ) , as we make a linear traversal to count the number of vowels and consonants." }, { "code": null, "e": 37106, "s": 36974, "text": "Space Complexity for above solution : O( |str| ), as we make two arrays vo[] and co[] to store the number of vowels at any index i." }, { "code": null, "e": 37317, "s": 37106, "text": "The above solution can be optimized to be done in O(1) space complexity, by using only two variables instead of making two arrays to store vowels and consonants at any index i. Following code depicts the same :" }, { "code": null, "e": 37321, "s": 37317, "text": "C++" }, { "code": null, "e": 37323, "s": 37321, "text": "C" }, { "code": null, "e": 37328, "s": 37323, "text": "Java" }, { "code": null, "e": 37336, "s": 37328, "text": "Python3" }, { "code": null, "e": 37339, "s": 37336, "text": "C#" }, { "code": null, "e": 37350, "s": 37339, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // function to check if a character is vowel or notbool isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; return false;} long long countSpecial(string str){ long long cnt = 0; int n = str.size(); // in case of single character or empty string // we can't fulfill the given condition , hence the // count is 0. if (n == 1 || n == 0) return 0; // variables to store count of total vowels and // consonants in the string long long vow = 0, cons = 0; for (int i = 0; i < n; i++) vow += isVowel(str[i]); cons = n - vow; for (int i = 0; i < n; i++) { // as we encounter a vowel, we add no. of consonants // after it to our answer and decrease the value of // vow by 1, indicating that now the remaining // string has one vowel less than current string if (isVowel(str[i])) { vow--; cnt += cons; } // same case as above for consonants else { cons--; cnt += vow; } } // finally we return the cnt as our answer return cnt;} int main(){ string str = \"adceba\"; cout << countSpecial(str); return 0;}", "e": 38633, "s": 37350, "text": null }, { "code": "#include <stdio.h> // function to check if a character is vowel or notint isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; return 0;} long long countSpecial(char str[], int n){ long long cnt = 0; // in case of single character or empty string // we can't fulfill the given condition , hence the // count is 0. if (n == 1 || n == 0) return 0; // variables to store count of total vowels and // consonants in the string long long vow = 0, cons = 0; for (int i = 0; i < n; i++) vow += isVowel(str[i]); cons = n - vow; for (int i = 0; i < n; i++) { // as we encounter a vowel, we add no. of consonants // after it to our answer and decrease the value of // vow by 1, indicating that now the remaining // string has one vowel less than current string if (isVowel(str[i])) { vow--; cnt += cons; } // same case as above for consonants else { cons--; cnt += vow; } } // finally we return the cnt as our answer return cnt;} int main(){ char str[] = { 'a', 'd', 'c', 'e', 'b', 'a' }; int n = sizeof(str) / sizeof(char); if (n == 0) { printf(\"0\"); } else { long long count = countSpecial(str, n); printf(\"%lld\", count); } return 0;}", "e": 40035, "s": 38633, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { // function to check if a character is vowel or not public static int isVowel(char ch) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; return 0; } public static long countSpecial(String str) { long cnt = 0; int n = str.length(); // in case of single character or empty string // we can't fulfill the given condition , hence the // count is 0. if (n == 1 || n == 0) return 0; // variables to store count of total vowels and // consonants in the string long vow = 0, cons = 0; for (int i = 0; i < n; i++) { char ch = str.charAt(i); vow += isVowel(ch); } cons = n - vow; for (int i = 0; i < n; i++) { char ch = str.charAt(i); // as we encounter a vowel, we add no. of // consonants after it to our answer // and decrease the value of vow by 1, // indicating that now the remaining // string has one vowel less than current string if (isVowel(ch) == 1) { vow--; cnt += cons; } // same case as above for consonants else { cons--; cnt += vow; } } // finally we return the cnt as our answer return cnt; } public static void main(String[] args) { String str = \"adceba\"; long count = countSpecial(str); System.out.println(count); }}", "e": 41695, "s": 40035, "text": null }, { "code": "'''package whatever #do not write package name here ''' # function to check if a character is vowel or notdef isVowel(ch): if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'): return 1; return 0; def countSpecial( str): cnt = 0; n = len(str); # in case of single character or empty string # we can't fulfill the given condition , hence the # count is 0. if (n == 1 or n == 0): return 0; # variables to store count of total vowels and # consonants in the string vow = 0 cons = 0; for i in range(n): ch = str[i]; vow += isVowel(ch); cons = n - vow; for i in range(n): ch = str[i]; # as we encounter a vowel, we add no. of # consonants after it to our answer # and decrease the value of vow by 1, # indicating that now the remaining # string has one vowel less than current string if (isVowel(ch) == 1): vow -= 1; cnt += cons; # same case as above for consonants else: cons -= 1; cnt += vow; # finally we return the cnt as our answer return cnt; # Driver codeif __name__ == '__main__': str = \"adceba\"; count = countSpecial(str); print(count); # This code is contributed by Rajput-Ji", "e": 43012, "s": 41695, "text": null }, { "code": "/*package whatever //do not write package name here */using System;class GFG{ // function to check if a character is vowel or not public static int isVowel(char ch) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; return 0; } public static long countSpecial(String str) { long cnt = 0; int n = str.Length; // in case of single character or empty string // we can't fulfill the given condition , hence the // count is 0. if (n == 1 || n == 0) return 0; // variables to store count of total vowels and // consonants in the string long vow = 0, cons = 0; for (int i = 0; i < n; i++) { char ch = str[i]; vow += isVowel(ch); } cons = n - vow; for (int i = 0; i < n; i++) { char ch = str[i]; // as we encounter a vowel, we add no. of // consonants after it to our answer // and decrease the value of vow by 1, // indicating that now the remaining // string has one vowel less than current string if (isVowel(ch) == 1) { vow--; cnt += cons; } // same case as above for consonants else { cons--; cnt += vow; } } // finally we return the cnt as our answer return cnt; } // Driver code public static void Main(String[] args) { string str = \"adceba\"; long count = countSpecial(str); Console.Write(count); }} // This code is contributed by shivanisinghss2110", "e": 44735, "s": 43012, "text": null }, { "code": "<script>/*package whatever //do not write package name here */ // function to check if a character is vowel or notfunction isVowel(ch) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; return 0; } function countSpecial(str) { var cnt = 0; var n = str.length; // in case of single character or empty string // we can't fulfill the given condition , hence the // count is 0. if (n == 1 || n == 0) return 0; // variables to store count of total vowels and // consonants in the string var vow = 0, cons = 0; for (var i = 0; i < n; i++) { var ch = str.charAt(i); vow += isVowel(ch); } cons = n - vow; for (var i = 0; i < n; i++) { var ch = str.charAt(i); // as we encounter a vowel, we add no. of // consonants after it to our answer // and decrease the value of vow by 1, // indicating that now the remaining // string has one vowel less than current string if (isVowel(ch) == 1) { vow--; cnt += cons; } // same case as above for consonants else { cons--; cnt += vow; } } // finally we return the cnt as our answer return cnt; } var str = \"adceba\"; var count = countSpecial(str); document.write(count); // This code is contributed by shivanisinghss2110</script>", "e": 46328, "s": 44735, "text": null }, { "code": null, "e": 46330, "s": 46328, "text": "9" }, { "code": null, "e": 46359, "s": 46330, "text": "Time Complexity : O( |str| )" }, { "code": null, "e": 46384, "s": 46359, "text": "Space Complexity : O(1) " }, { "code": null, "e": 46394, "s": 46384, "text": "Rajput-Ji" }, { "code": null, "e": 46401, "s": 46394, "text": "rdtank" }, { "code": null, "e": 46414, "s": 46401, "text": "rishabhdevba" }, { "code": null, "e": 46430, "s": 46414, "text": "saurabh1990aror" }, { "code": null, "e": 46449, "s": 46430, "text": "shivanisinghss2110" }, { "code": null, "e": 46458, "s": 46449, "text": "rkbhola5" }, { "code": null, "e": 46469, "s": 46458, "text": "prefix-sum" }, { "code": null, "e": 46477, "s": 46469, "text": "Strings" }, { "code": null, "e": 46488, "s": 46477, "text": "prefix-sum" }, { "code": null, "e": 46496, "s": 46488, "text": "Strings" }, { "code": null, "e": 46594, "s": 46496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46669, "s": 46594, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 46726, "s": 46669, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 46762, "s": 46726, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 46809, "s": 46762, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 46862, "s": 46809, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 46898, "s": 46862, "text": "Convert string to char array in C++" }, { "code": null, "e": 46950, "s": 46898, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 46988, "s": 46950, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 47018, "s": 46988, "text": "Caesar Cipher in Cryptography" } ]
HTML <a> ping Attribute - GeeksforGeeks
02 Jun, 2021 The HTML <a> ping Attribute is generally used to either specify a particular URL or a list of URLs that will be notified when the user will click on the hyperlink passed int HTML <a> href Attribute. This is achieved by sending a short HTTP post request to the specified URL as soon as the user clicks on the hyperlink. Syntax : <a href="url_hyperlink" ping="specified_url" /> Attribute Values: specified_url: This is the URL where the short HTTP post request will be sent as soon as the user follows the link given in url_hyperlink. Example: HTML <!DOCTYPE html><html> <head> </head> <body> <h2>Welcome To GFG</h2> <a href="https://auth.geeksforgeeks.org/user/codersaty/articles" ping="https://www.geeksforgeeks.org/"> Read codersaty articles </a> </body></html> Output: Note: A short HTTP post request will be sent to “https://www.geeksforgeeks.org/” whenever someone clicks “Read codersaty articles” Supported Browsers: Edge 17.0 Apple Safari 6.0 Opera 15.0 Google Chrome 15.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML-Basics 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": 33003, "s": 32975, "text": "\n02 Jun, 2021" }, { "code": null, "e": 33323, "s": 33003, "text": "The HTML <a> ping Attribute is generally used to either specify a particular URL or a list of URLs that will be notified when the user will click on the hyperlink passed int HTML <a> href Attribute. This is achieved by sending a short HTTP post request to the specified URL as soon as the user clicks on the hyperlink. " }, { "code": null, "e": 33332, "s": 33323, "text": "Syntax :" }, { "code": null, "e": 33380, "s": 33332, "text": "<a href=\"url_hyperlink\" ping=\"specified_url\" />" }, { "code": null, "e": 33398, "s": 33380, "text": "Attribute Values:" }, { "code": null, "e": 33537, "s": 33398, "text": "specified_url: This is the URL where the short HTTP post request will be sent as soon as the user follows the link given in url_hyperlink." }, { "code": null, "e": 33546, "s": 33537, "text": "Example:" }, { "code": null, "e": 33551, "s": 33546, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> </head> <body> <h2>Welcome To GFG</h2> <a href=\"https://auth.geeksforgeeks.org/user/codersaty/articles\" ping=\"https://www.geeksforgeeks.org/\"> Read codersaty articles </a> </body></html>", "e": 33790, "s": 33551, "text": null }, { "code": null, "e": 33798, "s": 33790, "text": "Output:" }, { "code": null, "e": 33930, "s": 33798, "text": "Note: A short HTTP post request will be sent to “https://www.geeksforgeeks.org/” whenever someone clicks “Read codersaty articles”" }, { "code": null, "e": 33951, "s": 33930, "text": "Supported Browsers: " }, { "code": null, "e": 33961, "s": 33951, "text": "Edge 17.0" }, { "code": null, "e": 33978, "s": 33961, "text": "Apple Safari 6.0" }, { "code": null, "e": 33989, "s": 33978, "text": "Opera 15.0" }, { "code": null, "e": 34008, "s": 33989, "text": "Google Chrome 15.0" }, { "code": null, "e": 34145, "s": 34008, "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": 34161, "s": 34145, "text": "HTML-Attributes" }, { "code": null, "e": 34173, "s": 34161, "text": "HTML-Basics" }, { "code": null, "e": 34178, "s": 34173, "text": "HTML" }, { "code": null, "e": 34195, "s": 34178, "text": "Web Technologies" }, { "code": null, "e": 34200, "s": 34195, "text": "HTML" }, { "code": null, "e": 34298, "s": 34200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34360, "s": 34298, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34410, "s": 34360, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34458, "s": 34410, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34518, "s": 34458, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34571, "s": 34518, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 34611, "s": 34571, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34644, "s": 34611, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34689, "s": 34644, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34732, "s": 34689, "text": "How to fetch data from an API in ReactJS ?" } ]
MultiAutoCompleteTextView in Android with Example - GeeksforGeeks
20 Apr, 2022 MultiAutoCompleteTextView is an editable TextView, extending AutoCompleteTextView. In a text view, when the user starts to type a text, MultiAutoCompleteTextView shows completion suggestions for the substring of the text and it is useful for the user to select the option instead of typing. This feature is very much useful in all kinds of apps like educational/commercial/entertainment apps etc., This feature is one way allows the user to select the correct term and since multiple suggestions are allowed, it makes the user’s life very simple. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. An AutoCompleteTextView only offers suggestion about the whole text. But MultiAutoCompleteTextView offers multiple suggestions for the substring of the text. 1. setTokenizer(): The Tokenizer is set inside the method setTokenizer(). By default, we have CommaTokenizer. In this example, we are using two MultiAutoCompleteTextView instances. One(multiAutoCompleteTextViewDefault) with default CommaTokenizer. multiAutoCompleteTextViewDefault.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); Here when the user finishes typing or selects a substring, a comma is appended at the end of the substring. For second instance(multiAutoCompleteTextViewCustom), we are using SpaceTokenizer. It is nothing but a Java class and in that we need to write the code inside 3 methods namely findTokenStart, findTokenEnd, and terminateToken. multiAutoCompleteTextViewCustom.setTokenizer(new SpaceTokenizer()); Here when the user finishes typing or selects a substring, space is appended at the end of the substring. 2. setThreshold(): setThreshold() is used to specify the number of characters after which the dropdown with the autocomplete suggestions list would be displayed. It can be 1 or 2 or depends upon your requirement. For this example, // For multiAutoCompleteTextViewDefault, after user types a character, // the dropdown is shown multiAutoCompleteTextViewDefault.setThreshold(1); // For multiAutoCompleteTextViewCustom, after user types 2 characters, // the dropdown is shown multiAutoCompleteTextViewCustom.setThreshold(2); 3. setAdapter(): In order to show the substring items in the dropdown, we need to fill string array in “ArrayAdapter”. // First instance ArrayAdapter<String> randomArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fewRandomSuggestedText); multiAutoCompleteTextViewDefault.setAdapter(randomArrayAdapter); // second instance ArrayAdapter<String> tagArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fewTags); multiAutoCompleteTextViewCustom.setAdapter(tagArrayAdapter); Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file For this example in the activity_main.xml file add two TextViews and two MultiAutoCompleteTextViews. Below is the complete code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. XML <?xml version="1.0" encoding="utf-8"?><!--In linearlayout, screen is rendered and hence all the below components come line by line and provide neat layout --><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_margin="16dp" android:orientation="vertical" tools:context=".MainActivity"> <!-- To indicate the user that first MultiAutoCompleteTextView is supported with comma separated this textview is introduced. It just displays Text Separated by Commas at the top --> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Text Separated by Commas" android:textSize="18sp" /> <!-- 1st MultiAutoCompleteTextView instance identified with multiAutoCompleteTextViewDefault and here when user starts to type, it will show relevant substrings and after user chooses it, the text is ended with "," as comma is the default tokenizer --> <MultiAutoCompleteTextView android:id="@+id/multiAutoCompleteTextViewDefault" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:ems="10" android:hint="Enter Search Terms here" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Text Separated by Custom Token" android:textSize="18sp" /> <!-- 2nd MultiAutoCompleteTextView instance identified with multiAutoCompleteTextViewCustom and here when user starts to type, it will show relevant substrings and after user chooses it, the text is ended with " " as code is done to have space as separator --> <MultiAutoCompleteTextView android:id="@+id/multiAutoCompleteTextViewCustom" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:ems="10" android:hint="Add your necessary tags here" /> </LinearLayout> The UI looks like the following: Step 3: Working with the Java files Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.MultiAutoCompleteTextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // Defining two MultiAutoCompleteTextView // This is to recognize comma separated. MultiAutoCompleteTextView multiAutoCompleteTextViewDefault; // This is the second one and required for custom features MultiAutoCompleteTextView multiAutoCompleteTextViewCustom; // As a sample, few text are given below which can be populated in dropdown, when user starts typing // For example, when user types "a", text whichever starting with "a" will be displayed in dropdown // As we are using two MultiAutoCompleteTextView components, using two string array separately String[] fewRandomSuggestedText = {"a", "ant", "apple", "asp", "android", "animation", "adobe", "chrome", "chromium", "firefox", "freeware", "fedora"}; String[] fewTags = {"Java", "JavaScript", "Spring", "Java EE", "Java 8", "Java 9", "Java 10", "MongoDB", "MarshMallow", "NoSQL", "NativeApp", "SQL", "SQLite"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); multiAutoCompleteTextViewDefault = findViewById(R.id.multiAutoCompleteTextViewDefault); multiAutoCompleteTextViewCustom = findViewById(R.id.multiAutoCompleteTextViewCustom); // In order to show the substring options in a dropdown, we need ArrayAdapter // and here it is using simple_list_item_1 ArrayAdapter<String> randomArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fewRandomSuggestedText); multiAutoCompleteTextViewDefault.setAdapter(randomArrayAdapter); // setThreshold() is used to specify the number of characters after which // the dropdown with the autocomplete suggestions list would be displayed. // For multiAutoCompleteTextViewDefault, after 1 character, the dropdown shows substring multiAutoCompleteTextViewDefault.setThreshold(1); // Default CommaTokenizer is used here multiAutoCompleteTextViewDefault.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); ArrayAdapter<String> tagArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fewTags); multiAutoCompleteTextViewCustom.setAdapter(tagArrayAdapter); // For multiAutoCompleteTextViewCustom, after 2 characters, the dropdown shows substring multiAutoCompleteTextViewCustom.setThreshold(2); // As multiAutoCompleteTextViewCustom is customized , we are using SpaceTokenizer // which is written as a separate java class to handle space // SpaceTokenizer can be customized as per our needs, here for this example, // after user types 2 character // the substring of the text is shown in the dropdown and once selected, // a space is appended at the // end of the substring. So for customized MultiAutoCompleteTextView, // we need to write code like SpaceTokenizer // It has 3 methods namely findTokenStart,findTokenEnd and terminateToken multiAutoCompleteTextViewCustom.setTokenizer(new SpaceTokenizer()); }} For 2nd instance of MultiAutoCompleteTextViewActivity, here used space tokenizer and only comma tokenizer is default and if we are using other tokenizers, need to write the code in java and it should have 3 methods implemented namely findTokenStart, findTokenEnd, and terminateToken. Now create another Java file (app > java > your package name > New > Java Class) and named it as SpaceTokenizer. Below is the complete code for the SpaceTokenizer.java file. Comments are added inside the code to understand the code in more detail. Java import android.text.SpannableString;import android.text.Spanned;import android.text.TextUtils;import android.widget.MultiAutoCompleteTextView; // As this java class implements MultiAutoCompleteTextView.Tokenizer,// we should write 3 methods i.e. findTokenStart,findTokenEnd and terminateTokenpublic class SpaceTokenizer implements MultiAutoCompleteTextView.Tokenizer { private int i; // Returns the start of the token that ends at offset cursor within text. public int findTokenStart(CharSequence inputText, int cursor) { int idx = cursor; while (idx > 0 && inputText.charAt(idx - 1) != ' ') { idx--; } while (idx < cursor && inputText.charAt(idx) == ' ') { idx++; } return idx; } // Returns the end of the token (minus trailing punctuation) that // begins at offset cursor within text. public int findTokenEnd(CharSequence inputText, int cursor) { int idx = cursor; int length = inputText.length(); while (idx < length) { if (inputText.charAt(i) == ' ') { return idx; } else { idx++; } } return length; } // Returns text, modified, if necessary, to ensure that it ends with a token terminator // (for example a space or comma). public CharSequence terminateToken(CharSequence inputText) { int idx = inputText.length(); while (idx > 0 && inputText.charAt(idx - 1) == ' ') { idx--; } if (idx > 0 && inputText.charAt(idx - 1) == ' ') { return inputText; } else { if (inputText instanceof Spanned) { SpannableString sp = new SpannableString(inputText + " "); TextUtils.copySpansFrom((Spanned) inputText, 0, inputText.length(), Object.class, sp, 0); return sp; } else { return inputText + " "; } } }} In many apps, there are necessities to have MultiAutoCompleteTextView which will help to provide valuable information and makes users’ lives easier to avoid selecting irrelevant information. While collecting requirements, the user has to key in all the necessary text in the java file so that in the dropdown, necessary suggested text can appear. sweetyty android Android-View Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26381, "s": 26353, "text": "\n20 Apr, 2022" }, { "code": null, "e": 27093, "s": 26381, "text": "MultiAutoCompleteTextView is an editable TextView, extending AutoCompleteTextView. In a text view, when the user starts to type a text, MultiAutoCompleteTextView shows completion suggestions for the substring of the text and it is useful for the user to select the option instead of typing. This feature is very much useful in all kinds of apps like educational/commercial/entertainment apps etc., This feature is one way allows the user to select the correct term and since multiple suggestions are allowed, it makes the user’s life very simple. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 27251, "s": 27093, "text": "An AutoCompleteTextView only offers suggestion about the whole text. But MultiAutoCompleteTextView offers multiple suggestions for the substring of the text." }, { "code": null, "e": 27270, "s": 27251, "text": "1. setTokenizer():" }, { "code": null, "e": 27499, "s": 27270, "text": "The Tokenizer is set inside the method setTokenizer(). By default, we have CommaTokenizer. In this example, we are using two MultiAutoCompleteTextView instances. One(multiAutoCompleteTextViewDefault) with default CommaTokenizer." }, { "code": null, "e": 27594, "s": 27499, "text": "multiAutoCompleteTextViewDefault.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());" }, { "code": null, "e": 27928, "s": 27594, "text": "Here when the user finishes typing or selects a substring, a comma is appended at the end of the substring. For second instance(multiAutoCompleteTextViewCustom), we are using SpaceTokenizer. It is nothing but a Java class and in that we need to write the code inside 3 methods namely findTokenStart, findTokenEnd, and terminateToken." }, { "code": null, "e": 27996, "s": 27928, "text": "multiAutoCompleteTextViewCustom.setTokenizer(new SpaceTokenizer());" }, { "code": null, "e": 28102, "s": 27996, "text": "Here when the user finishes typing or selects a substring, space is appended at the end of the substring." }, { "code": null, "e": 28121, "s": 28102, "text": "2. setThreshold():" }, { "code": null, "e": 28334, "s": 28121, "text": "setThreshold() is used to specify the number of characters after which the dropdown with the autocomplete suggestions list would be displayed. It can be 1 or 2 or depends upon your requirement. For this example, " }, { "code": null, "e": 28405, "s": 28334, "text": "// For multiAutoCompleteTextViewDefault, after user types a character," }, { "code": null, "e": 28430, "s": 28405, "text": "// the dropdown is shown" }, { "code": null, "e": 28480, "s": 28430, "text": "multiAutoCompleteTextViewDefault.setThreshold(1);" }, { "code": null, "e": 28551, "s": 28480, "text": "// For multiAutoCompleteTextViewCustom, after user types 2 characters," }, { "code": null, "e": 28576, "s": 28551, "text": "// the dropdown is shown" }, { "code": null, "e": 28625, "s": 28576, "text": "multiAutoCompleteTextViewCustom.setThreshold(2);" }, { "code": null, "e": 28642, "s": 28625, "text": "3. setAdapter():" }, { "code": null, "e": 28744, "s": 28642, "text": "In order to show the substring items in the dropdown, we need to fill string array in “ArrayAdapter”." }, { "code": null, "e": 28762, "s": 28744, "text": "// First instance" }, { "code": null, "e": 28891, "s": 28762, "text": "ArrayAdapter<String> randomArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fewRandomSuggestedText);" }, { "code": null, "e": 28956, "s": 28891, "text": "multiAutoCompleteTextViewDefault.setAdapter(randomArrayAdapter);" }, { "code": null, "e": 28975, "s": 28956, "text": "// second instance" }, { "code": null, "e": 29086, "s": 28975, "text": "ArrayAdapter<String> tagArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fewTags);" }, { "code": null, "e": 29147, "s": 29086, "text": "multiAutoCompleteTextViewCustom.setAdapter(tagArrayAdapter);" }, { "code": null, "e": 29176, "s": 29147, "text": "Step 1: Create a New Project" }, { "code": null, "e": 29338, "s": 29176, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 29386, "s": 29338, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 29620, "s": 29386, "text": "For this example in the activity_main.xml file add two TextViews and two MultiAutoCompleteTextViews. Below is the complete code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 29624, "s": 29620, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--In linearlayout, screen is rendered and hence all the below components come line by line and provide neat layout --><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_gravity=\"center\" android:layout_margin=\"16dp\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!-- To indicate the user that first MultiAutoCompleteTextView is supported with comma separated this textview is introduced. It just displays Text Separated by Commas at the top --> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:text=\"Text Separated by Commas\" android:textSize=\"18sp\" /> <!-- 1st MultiAutoCompleteTextView instance identified with multiAutoCompleteTextViewDefault and here when user starts to type, it will show relevant substrings and after user chooses it, the text is ended with \",\" as comma is the default tokenizer --> <MultiAutoCompleteTextView android:id=\"@+id/multiAutoCompleteTextViewDefault\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:ems=\"10\" android:hint=\"Enter Search Terms here\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:text=\"Text Separated by Custom Token\" android:textSize=\"18sp\" /> <!-- 2nd MultiAutoCompleteTextView instance identified with multiAutoCompleteTextViewCustom and here when user starts to type, it will show relevant substrings and after user chooses it, the text is ended with \" \" as code is done to have space as separator --> <MultiAutoCompleteTextView android:id=\"@+id/multiAutoCompleteTextViewCustom\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:ems=\"10\" android:hint=\"Add your necessary tags here\" /> </LinearLayout>", "e": 31973, "s": 29624, "text": null }, { "code": null, "e": 32006, "s": 31973, "text": "The UI looks like the following:" }, { "code": null, "e": 32042, "s": 32006, "text": "Step 3: Working with the Java files" }, { "code": null, "e": 32175, "s": 32042, "text": "Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 32180, "s": 32175, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.MultiAutoCompleteTextView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // Defining two MultiAutoCompleteTextView // This is to recognize comma separated. MultiAutoCompleteTextView multiAutoCompleteTextViewDefault; // This is the second one and required for custom features MultiAutoCompleteTextView multiAutoCompleteTextViewCustom; // As a sample, few text are given below which can be populated in dropdown, when user starts typing // For example, when user types \"a\", text whichever starting with \"a\" will be displayed in dropdown // As we are using two MultiAutoCompleteTextView components, using two string array separately String[] fewRandomSuggestedText = {\"a\", \"ant\", \"apple\", \"asp\", \"android\", \"animation\", \"adobe\", \"chrome\", \"chromium\", \"firefox\", \"freeware\", \"fedora\"}; String[] fewTags = {\"Java\", \"JavaScript\", \"Spring\", \"Java EE\", \"Java 8\", \"Java 9\", \"Java 10\", \"MongoDB\", \"MarshMallow\", \"NoSQL\", \"NativeApp\", \"SQL\", \"SQLite\"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); multiAutoCompleteTextViewDefault = findViewById(R.id.multiAutoCompleteTextViewDefault); multiAutoCompleteTextViewCustom = findViewById(R.id.multiAutoCompleteTextViewCustom); // In order to show the substring options in a dropdown, we need ArrayAdapter // and here it is using simple_list_item_1 ArrayAdapter<String> randomArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fewRandomSuggestedText); multiAutoCompleteTextViewDefault.setAdapter(randomArrayAdapter); // setThreshold() is used to specify the number of characters after which // the dropdown with the autocomplete suggestions list would be displayed. // For multiAutoCompleteTextViewDefault, after 1 character, the dropdown shows substring multiAutoCompleteTextViewDefault.setThreshold(1); // Default CommaTokenizer is used here multiAutoCompleteTextViewDefault.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); ArrayAdapter<String> tagArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fewTags); multiAutoCompleteTextViewCustom.setAdapter(tagArrayAdapter); // For multiAutoCompleteTextViewCustom, after 2 characters, the dropdown shows substring multiAutoCompleteTextViewCustom.setThreshold(2); // As multiAutoCompleteTextViewCustom is customized , we are using SpaceTokenizer // which is written as a separate java class to handle space // SpaceTokenizer can be customized as per our needs, here for this example, // after user types 2 character // the substring of the text is shown in the dropdown and once selected, // a space is appended at the // end of the substring. So for customized MultiAutoCompleteTextView, // we need to write code like SpaceTokenizer // It has 3 methods namely findTokenStart,findTokenEnd and terminateToken multiAutoCompleteTextViewCustom.setTokenizer(new SpaceTokenizer()); }}", "e": 35502, "s": 32180, "text": null }, { "code": null, "e": 35786, "s": 35502, "text": "For 2nd instance of MultiAutoCompleteTextViewActivity, here used space tokenizer and only comma tokenizer is default and if we are using other tokenizers, need to write the code in java and it should have 3 methods implemented namely findTokenStart, findTokenEnd, and terminateToken." }, { "code": null, "e": 36034, "s": 35786, "text": "Now create another Java file (app > java > your package name > New > Java Class) and named it as SpaceTokenizer. Below is the complete code for the SpaceTokenizer.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 36039, "s": 36034, "text": "Java" }, { "code": "import android.text.SpannableString;import android.text.Spanned;import android.text.TextUtils;import android.widget.MultiAutoCompleteTextView; // As this java class implements MultiAutoCompleteTextView.Tokenizer,// we should write 3 methods i.e. findTokenStart,findTokenEnd and terminateTokenpublic class SpaceTokenizer implements MultiAutoCompleteTextView.Tokenizer { private int i; // Returns the start of the token that ends at offset cursor within text. public int findTokenStart(CharSequence inputText, int cursor) { int idx = cursor; while (idx > 0 && inputText.charAt(idx - 1) != ' ') { idx--; } while (idx < cursor && inputText.charAt(idx) == ' ') { idx++; } return idx; } // Returns the end of the token (minus trailing punctuation) that // begins at offset cursor within text. public int findTokenEnd(CharSequence inputText, int cursor) { int idx = cursor; int length = inputText.length(); while (idx < length) { if (inputText.charAt(i) == ' ') { return idx; } else { idx++; } } return length; } // Returns text, modified, if necessary, to ensure that it ends with a token terminator // (for example a space or comma). public CharSequence terminateToken(CharSequence inputText) { int idx = inputText.length(); while (idx > 0 && inputText.charAt(idx - 1) == ' ') { idx--; } if (idx > 0 && inputText.charAt(idx - 1) == ' ') { return inputText; } else { if (inputText instanceof Spanned) { SpannableString sp = new SpannableString(inputText + \" \"); TextUtils.copySpansFrom((Spanned) inputText, 0, inputText.length(), Object.class, sp, 0); return sp; } else { return inputText + \" \"; } } }}", "e": 38021, "s": 36039, "text": null }, { "code": null, "e": 38368, "s": 38021, "text": "In many apps, there are necessities to have MultiAutoCompleteTextView which will help to provide valuable information and makes users’ lives easier to avoid selecting irrelevant information. While collecting requirements, the user has to key in all the necessary text in the java file so that in the dropdown, necessary suggested text can appear." }, { "code": null, "e": 38377, "s": 38368, "text": "sweetyty" }, { "code": null, "e": 38385, "s": 38377, "text": "android" }, { "code": null, "e": 38398, "s": 38385, "text": "Android-View" }, { "code": null, "e": 38405, "s": 38398, "text": "Picked" }, { "code": null, "e": 38413, "s": 38405, "text": "Android" }, { "code": null, "e": 38418, "s": 38413, "text": "Java" }, { "code": null, "e": 38423, "s": 38418, "text": "Java" }, { "code": null, "e": 38431, "s": 38423, "text": "Android" }, { "code": null, "e": 38529, "s": 38431, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38567, "s": 38529, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 38606, "s": 38567, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 38656, "s": 38606, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 38698, "s": 38656, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 38749, "s": 38698, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 38764, "s": 38749, "text": "Arrays in Java" }, { "code": null, "e": 38808, "s": 38764, "text": "Split() String method in Java with examples" }, { "code": null, "e": 38830, "s": 38808, "text": "For-each loop in Java" }, { "code": null, "e": 38881, "s": 38830, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Most Useful Commands to Manage Apache Web Server in Linux - GeeksforGeeks
24 Feb, 2021 Prerequisite: How do Web Servers work? Apache is one of the most widely used free, open-source Web Server applications in the world, mostly used in Unix-like operating systems but can also be used in windows. As a developer or system administrator, it will be very helpful for you to know about the Apache webserver. It has many notable features among which Virtual hosting is one such notable feature that allows a single Apache Web Server to serve a different number of websites. We will discuss some of the most useful commands to manage Apache webserver (also called httpd on some other Linux-based distros) in Linux that you should know as a developer or system administrator. The commands that are going to be discussed must be executed as a root or sudo user. Install Apache Server: Installing Apache server on Debian/Ubuntu Linux using the following command: sudo apt install apache2 apache 2 already installed on my system Check Apache Version: For checking the installed version of the Apache webserver on the Linux system, use the following command: sudo apache2 -v apache2 version Display Apache compile settings: To find about the Apache compile settings use the following command: apache2 -V Finding Syntax Errors in Apache Configuration File: For checking Apache configuration files for finding any syntax errors on Debian-based systems before restarting the service use the following command:- sudo apache2ctl -t Syntax is Ok Finding Errors in Apache Virtual Host: Errors in Apache virtual host can be found out by using the following command below:- apache2ctl -S All the virtual hosts on the server, their options, and the file names and line numbers that they define, an error message with the line number are displayed that is very useful for troubleshooting the configuration file. All the commands that will be discussed are applicable for Debian and Ubuntu Linux. Start Apache Service: For starting the Apache service, run the following command: sudo service apache2 start Restart Apache Service: For restarting the Apache service, run the following command: sudo systemctl restart apache2 View Apache Service Status: For viewing the Apache service, run the following command: sudo systemctl status apache2 status is active Reload Apache Service: For reloading(if you have made any changes in the configuration file then you can use this )the Apache service, run the following command: sudo systemctl reload apache2 Restart the Apache Service: For reloading the Apache service, run the following command:- systemctl restart apache2 Stop Apache Service: For stopping the Apache service, run the following command:- sudo systemctl stop apache2 Show Apache Command Help: For getting help with the Apache service commands by running the following command:- sudo apache2 -h linux-command Picked Technical Scripter 2020 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n24 Feb, 2021" }, { "code": null, "e": 25690, "s": 25651, "text": "Prerequisite: How do Web Servers work?" }, { "code": null, "e": 26134, "s": 25690, "text": "Apache is one of the most widely used free, open-source Web Server applications in the world, mostly used in Unix-like operating systems but can also be used in windows. As a developer or system administrator, it will be very helpful for you to know about the Apache webserver. It has many notable features among which Virtual hosting is one such notable feature that allows a single Apache Web Server to serve a different number of websites." }, { "code": null, "e": 26420, "s": 26134, "text": "We will discuss some of the most useful commands to manage Apache webserver (also called httpd on some other Linux-based distros) in Linux that you should know as a developer or system administrator. The commands that are going to be discussed must be executed as a root or sudo user. " }, { "code": null, "e": 26443, "s": 26420, "text": "Install Apache Server:" }, { "code": null, "e": 26520, "s": 26443, "text": "Installing Apache server on Debian/Ubuntu Linux using the following command:" }, { "code": null, "e": 26546, "s": 26520, "text": "sudo apt install apache2 " }, { "code": null, "e": 26586, "s": 26546, "text": "apache 2 already installed on my system" }, { "code": null, "e": 26608, "s": 26586, "text": "Check Apache Version:" }, { "code": null, "e": 26715, "s": 26608, "text": "For checking the installed version of the Apache webserver on the Linux system, use the following command:" }, { "code": null, "e": 26732, "s": 26715, "text": " sudo apache2 -v" }, { "code": null, "e": 26748, "s": 26732, "text": "apache2 version" }, { "code": null, "e": 26781, "s": 26748, "text": "Display Apache compile settings:" }, { "code": null, "e": 26850, "s": 26781, "text": "To find about the Apache compile settings use the following command:" }, { "code": null, "e": 26861, "s": 26850, "text": "apache2 -V" }, { "code": null, "e": 26913, "s": 26861, "text": "Finding Syntax Errors in Apache Configuration File:" }, { "code": null, "e": 27066, "s": 26913, "text": " For checking Apache configuration files for finding any syntax errors on Debian-based systems before restarting the service use the following command:-" }, { "code": null, "e": 27086, "s": 27066, "text": " sudo apache2ctl -t" }, { "code": null, "e": 27099, "s": 27086, "text": "Syntax is Ok" }, { "code": null, "e": 27138, "s": 27099, "text": "Finding Errors in Apache Virtual Host:" }, { "code": null, "e": 27224, "s": 27138, "text": "Errors in Apache virtual host can be found out by using the following command below:-" }, { "code": null, "e": 27238, "s": 27224, "text": "apache2ctl -S" }, { "code": null, "e": 27460, "s": 27238, "text": "All the virtual hosts on the server, their options, and the file names and line numbers that they define, an error message with the line number are displayed that is very useful for troubleshooting the configuration file." }, { "code": null, "e": 27544, "s": 27460, "text": "All the commands that will be discussed are applicable for Debian and Ubuntu Linux." }, { "code": null, "e": 27566, "s": 27544, "text": "Start Apache Service:" }, { "code": null, "e": 27626, "s": 27566, "text": "For starting the Apache service, run the following command:" }, { "code": null, "e": 27653, "s": 27626, "text": "sudo service apache2 start" }, { "code": null, "e": 27677, "s": 27653, "text": "Restart Apache Service:" }, { "code": null, "e": 27739, "s": 27677, "text": "For restarting the Apache service, run the following command:" }, { "code": null, "e": 27771, "s": 27739, "text": " sudo systemctl restart apache2" }, { "code": null, "e": 27799, "s": 27771, "text": "View Apache Service Status:" }, { "code": null, "e": 27858, "s": 27799, "text": "For viewing the Apache service, run the following command:" }, { "code": null, "e": 27889, "s": 27858, "text": "sudo systemctl status apache2 " }, { "code": null, "e": 27906, "s": 27889, "text": "status is active" }, { "code": null, "e": 27929, "s": 27906, "text": "Reload Apache Service:" }, { "code": null, "e": 28068, "s": 27929, "text": "For reloading(if you have made any changes in the configuration file then you can use this )the Apache service, run the following command:" }, { "code": null, "e": 28098, "s": 28068, "text": "sudo systemctl reload apache2" }, { "code": null, "e": 28126, "s": 28098, "text": "Restart the Apache Service:" }, { "code": null, "e": 28189, "s": 28126, "text": "For reloading the Apache service, run the following command:- " }, { "code": null, "e": 28216, "s": 28189, "text": "systemctl restart apache2 " }, { "code": null, "e": 28237, "s": 28216, "text": "Stop Apache Service:" }, { "code": null, "e": 28299, "s": 28237, "text": "For stopping the Apache service, run the following command:- " }, { "code": null, "e": 28330, "s": 28299, "text": "sudo systemctl stop apache2 " }, { "code": null, "e": 28356, "s": 28330, "text": "Show Apache Command Help:" }, { "code": null, "e": 28442, "s": 28356, "text": "For getting help with the Apache service commands by running the following command:- " }, { "code": null, "e": 28460, "s": 28442, "text": "sudo apache2 -h " }, { "code": null, "e": 28474, "s": 28460, "text": "linux-command" }, { "code": null, "e": 28481, "s": 28474, "text": "Picked" }, { "code": null, "e": 28505, "s": 28481, "text": "Technical Scripter 2020" }, { "code": null, "e": 28516, "s": 28505, "text": "Linux-Unix" }, { "code": null, "e": 28535, "s": 28516, "text": "Technical Scripter" }, { "code": null, "e": 28633, "s": 28535, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28668, "s": 28633, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28702, "s": 28668, "text": "mv command in Linux with examples" }, { "code": null, "e": 28728, "s": 28702, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28757, "s": 28728, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28794, "s": 28757, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28831, "s": 28794, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28873, "s": 28831, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 28899, "s": 28873, "text": "Thread functions in C/C++" }, { "code": null, "e": 28935, "s": 28899, "text": "uniq Command in LINUX with examples" } ]
How to check if a date has passed in MySQL?
Let us first create a table − mysql> create table DemoTable1340 -> ( -> Deadline date -> ); Query OK, 0 rows affected (0.43 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1340 values('2019-09-18'); Query OK, 1 row affected (0.52 sec) mysql> insert into DemoTable1340 values('2019-09-23'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1340 values('2018-12-24'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1340 values('2016-11-01'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1340 values('2019-09-28'); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement − mysql> select * from DemoTable1340; This will produce the following output − +------------+ | Deadline | +------------+ | 2019-09-18 | | 2019-09-23 | | 2018-12-24 | | 2016-11-01 | | 2019-09-28 | +------------+ 5 rows in set (0.00 sec) We should know the current date as well. The current date is as follows − mysql> select curdate(); +------------+ | curdate() | +------------+ | 2019-09-21 | +------------+ 1 row in set (0.00 sec) Here is the query to check if a date has passed − mysql> select * from DemoTable1340 where Deadline >= curdate(); This will produce the following output − +------------+ | Deadline | +------------+ | 2019-09-23 | | 2019-09-28 | +------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1200, "s": 1092, "text": "mysql> create table DemoTable1340\n -> (\n -> Deadline date\n -> );\nQuery OK, 0 rows affected (0.43 sec)" }, { "code": null, "e": 1256, "s": 1200, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1711, "s": 1256, "text": "mysql> insert into DemoTable1340 values('2019-09-18');\nQuery OK, 1 row affected (0.52 sec)\nmysql> insert into DemoTable1340 values('2019-09-23');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1340 values('2018-12-24');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable1340 values('2016-11-01');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1340 values('2019-09-28');\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 1771, "s": 1711, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1807, "s": 1771, "text": "mysql> select * from DemoTable1340;" }, { "code": null, "e": 1848, "s": 1807, "text": "This will produce the following output −" }, { "code": null, "e": 2008, "s": 1848, "text": "+------------+\n| Deadline |\n+------------+\n| 2019-09-18 |\n| 2019-09-23 |\n| 2018-12-24 |\n| 2016-11-01 |\n| 2019-09-28 |\n+------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2082, "s": 2008, "text": "We should know the current date as well. The current date is as follows −" }, { "code": null, "e": 2206, "s": 2082, "text": "mysql> select curdate();\n+------------+\n| curdate() |\n+------------+\n| 2019-09-21 |\n+------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2256, "s": 2206, "text": "Here is the query to check if a date has passed −" }, { "code": null, "e": 2320, "s": 2256, "text": "mysql> select * from DemoTable1340 where Deadline >= curdate();" }, { "code": null, "e": 2361, "s": 2320, "text": "This will produce the following output −" }, { "code": null, "e": 2476, "s": 2361, "text": "+------------+\n| Deadline |\n+------------+\n| 2019-09-23 |\n| 2019-09-28 |\n+------------+\n2 rows in set (0.00 sec)" } ]
NoOps Machine Learning. A PaaS End-to-End ML Setup with... | by Jacopo Tagliabue | Towards Data Science
“The princess you are looking for is in another castle.” The rapid adoption of Machine Learning, from Big Tech to literally everyone else, resulted in a blooming season for ML tooling and what cool kids now call “MLOps” (see the thoughtful overview by Chip Huyen, if you need to catch up). While my LinkedIn feed obsessively repeats that “80% of machine learning projects don’t make it to production”, I feel that there actually dozens of strategies to deploy your models, but you’re kind of in the dark after you solved that: I am not talking about monitoring, but the general experience of how you develop, experiment, train, iterate in an effective way (i.e. if you still need to solve the production stuff, this post won’t really help). Let’s face it, most ML scripts (well, certainly mine) are pretty messy, especially in the prototype-and-test-live-at-small-scale phase, as they involve stitching together several small tasks: retrieving data, training neural networks, running functional and behavioral tests etc. In other words, ML projects are DAG-like, and they need to be replayable, versioned, scheduled and so on: while we have successfully used Luigi before to orchestrate tasks, we hit some limitations with a growing team and big(ish) neural models. There is an important phase in ML-driven product development where we should be able to trust our code, but retaining the possibility of making corrections as we go, without worrying about the overall production environment: before full-scale engineering, ML needs a phase of good-enough engineering, where developers are somehow empowered end-to-end to ship their work to customers, internal users, etc. This post is our <10 minutes introduction to a better developer life: an end-to-end ML project (from raw data to a working API) built around a simple philosophy — effective iterations means abstracting away all infrastructure from developers. While custom-built solutions may work well for special cases, we show how off-the-shelf tools — Metaflow, SageMaker, Serverless — can be combined for a great PaaS experience, as all computing is managed automatically for us: in other words, from MLOps to NoOps at all. All the code is shared on Github: clone the repo and tag along! DISCLAIMER: this is not a tutorial on Metaflow, but a practical example of how tools can be combined to provide a better experience: while the repo should work with just copy+paste, some things may be unclear if you are not too familiar with Metaflow, SageMaker, etc.. It should be pretty straightforward to fill the gaps, but going through Netflix tutorials is always a good idea. We assume the following setup on your dev machine (see the Medium story replies, for some additional tips): there is already a ton of materials on these steps and we want to focus on the value provided by the system as a whole (which is what justifies going through setup in the first phase!). An AWS account: this is obvious, but please note that the free-tier won’t cut it for Metaflow! Make sure to have a suitable IAM role ready, as your development machine will need permissions to spin-up SageMaker endpoints. Metaflow up and running: go through the AWS-based setup, which is simplified by the CloudFormation template! Please note that if the @batch decorator is commented out, a local setup may work as well with some changes: if you are just curious, you can start local and go to the full AWS-backed configuration after you’re sold on the approach. Serverless up and running: make sure you can deploy code to AWS lambda from your terminal. If you wish to add experiment tracking, we have added some tips at the end: to start, just open a community account for MLFlow or a personal account on Weights & Biases. While not a definitive list, there used to be some frequently-mentioned pain points in our team when it comes to our everyday life as ML engineers: We want to organize the small tasks composing a project into a modular and replayable DAG-like structure: we want Python and data objects to be re-usable across tasks and clearly versioned; We want to assign computational resources effortlessly (i.e. without explicit provisioning/maintenance) per task, as we don’t want to run simple business logic on expensive GPUs, but we also don’t want to wait days for training runs. Since Snowflake allows us to do calculations directly in the data warehouse (a long story for another post!), our modus operandi is eminently non-distributed, and designed to be so: datasets fit comfortably in a laptop, and local development is way more efficient than iterating on Spark. Our bottleneck is mostly training, as we sometimes train big(ish) models on GPUs: however, naively switching context between local and cloud machines is very inefficient and time consuming; We want to work well together, that is, having visibility on all our DAGs, experiments and artifacts, but also making sure we don’t overwrite each other’s runs by mistake; We want a clear “path-to-make-an-impact”: even in a prototyping phase, we want support for deployment and scheduling — the goal is to able to push pretty robust micro-services without involving other teams. Metaflow (+ SageMaker) allows us to satisfy all these desiderata in a unified framework (plus additional perks, like the super-performant s3 client!). The project is a one-file DAG, centered around a regression model in Keras. The code is “toy” in many ways, but it shows how to go from a dataset to an API through a repeatable, modular and scalable process: the code is not particularly terse, but we aim for explanatory power over economy. The DAG is depicted in the picture below, and can be broken down in four major parts: Data loading: this step is achieved through a static file — thanks to Metaflow versioning, the exact dataset that is fed to training is automatically versioned.Model training: training the chosen model by exploring the hyperparameter space and measuring model performance on hold-out data.Model choice: collect all results from model runs, and chose the model for deployment based on some logic.Deployment: deploy the model to a SageMaker endpoint. Since SageMaker endpoints are internal to AWS, we use AWS lambda to make the predictions available through public APIs (see below). Data loading: this step is achieved through a static file — thanks to Metaflow versioning, the exact dataset that is fed to training is automatically versioned. Model training: training the chosen model by exploring the hyperparameter space and measuring model performance on hold-out data. Model choice: collect all results from model runs, and chose the model for deployment based on some logic. Deployment: deploy the model to a SageMaker endpoint. Since SageMaker endpoints are internal to AWS, we use AWS lambda to make the predictions available through public APIs (see below). The entire script is ~200 lines of code and it should be pretty self-explanatory (if not, reach out!). The project showcases many features of Metaflow — such as file and object versioning, parameters, automatic retry, etc. — , but we focus here on two: parallelization and remote computing. Parallelization: the key lines are the following, in which we first define a range of parameters (here, using different learning rates for pedagogical purposes) and then we use the foreach keyword: self.learning_rates = [0.1, 0.2]self.next(self.train_model, foreach='learning_rates') What happens is that the train_model step will be executed in parallel, with Metaflow spinning out new processes, each training a model with a particular learning rate. Remote computing: the key line is the following (you can actually comment it out the first time, to appreciate how your development experience is really the same, with or without cloud-computing): @batch(gpu=1, memory=80000) With this decorator, you tell Metaflow that the ensuing task has some computing requirements (here expressed as GPU and memory capacity, but “number of CPUs” is a popular option): Metaflow automatically creates a job in AWS Batch, then runs the step on a GPU-enabled machine. This shows how to integrate local dataset preparation with remote training, without change in code or explicit resource provisioning: the DAG stays the same, and it is Metaflow job to distribute the computation. Metaflow gets us the comfort and speed of local debugging in data wrangling, and then a pool of unbounded computational resources when horsepower is needed. If you are curious to see a more realistic flow, you can appreciate below the power of parallelization and remote computing: you retrieve product images from the warehouse, speed-up vectorization, get back to your laptop for the final touches (e.g. filtering), and then finally train your deep neural network. “Talk is cheap, show me the code” — L. Torvalds To run the project, cd into the flow directory and type the following command under your Python interpreter (make sure packages in requirements.txt are installed!): python training.py run After some quick checks, the DAG will load the data and then start parallelizing the training steps (if you are running with the batch decorator, AWS Batch console will track the two processes for you): At the end of each training process, the terminal will print the cloud path of the model, as versioned by the built-in s3 client: At the end of the DAG, a new SageMaker endpoint will be deployed: write down its name, as that is the only information we need to start serving predictions through a public API. After a run is concluded, we have to make sure our new model can be accessed through a devoted micro-service. We deploy a PaaS endpoint, leveraging the Infrastructure-as-Code setup in serverless.yml: simply cd into the serverless folder, and run the following command: serverless deploy --sagemaker my-endpoint where my-endpoint is the name of the endpoint created by the DAG. After a minute or so, you should be greeted by a success message: Write down the endpoint URL, paste it in the browser and try to supply one x value: https://my-url.amazonaws.com/dev/predict?x=9.45242 Et voilà — the browser should return our JSON response, with a pretty decent execution time: As far as systematically tracking our experiments, we could exploit Metaflow built-in versioning and its handy client API to retrieve what we stored in: self.hist = history.history and quickly plot loss / epochs in a notebook — but in a truly PaaS spirit of never write code unless you really need to, why don’t we re-use the neat UI of MLflow or W&B? Luckily, we can add tracking to our DAG with a few lines of code. At the very beginning of the train_model step, we inject some small code to make sure that i) the machine (local or remote) running the code has MLflow/W&B installed and ii) credentials are available as environment variables. os.system('pip install mlflow==1.13.1')os.environ["DATABRICKS_HOST"] = 'https://community.cloud.databricks.com' # don't change thisos.environ["DATABRICKS_USERNAME"] = 'my_user_name'os.environ["DATABRICKS_PASSWORD"] = 'my_password' (The same basic idea applies to W&B, but the env variable you need to set is the API KEY). Now that the library is installed, we can just exploit autologging to start tracking: import mlflow# don't change this for Community editionmlflow.set_tracking_uri("databricks")# your experiment name mlflow.set_experiment("/Users/my_user_name/exp_name") mlflow.tensorflow.autolog() The next time the DAG is executed, the Databricks dashboard will record and display the key metrics for all our runs: This is the same output, using W&B instead: As promised, we went from data loading to a model-based API in less than 10 minutes and without any infrastructure work: if you have the same pain points we had, our script gives you a worked-out example of how Metaflow-centric development (plus, some carefully chosen PaaS services) radically simplifies real-life machine learning projects. While the NoOps slogan is certainly a bit too good to be literally true, we do believe that good abstractions will make DevOps operations less and less visible in ML pipelines, allowing us to focus more and more on data and models. Alas, what is the history of software engineering, if not a series of powerful abstractions? Don’t forget to check the additional notes (in the story replies) for more technical details, setup tips and notes for future iterations. If you have questions or feedback, please connect and share your MLOps story (all Medium opinions are my own). Thanks to Christine, Ethan, Luca and Patrick for precious comments to earlier version of this post + repo.
[ { "code": null, "e": 229, "s": 172, "text": "“The princess you are looking for is in another castle.”" }, { "code": null, "e": 913, "s": 229, "text": "The rapid adoption of Machine Learning, from Big Tech to literally everyone else, resulted in a blooming season for ML tooling and what cool kids now call “MLOps” (see the thoughtful overview by Chip Huyen, if you need to catch up). While my LinkedIn feed obsessively repeats that “80% of machine learning projects don’t make it to production”, I feel that there actually dozens of strategies to deploy your models, but you’re kind of in the dark after you solved that: I am not talking about monitoring, but the general experience of how you develop, experiment, train, iterate in an effective way (i.e. if you still need to solve the production stuff, this post won’t really help)." }, { "code": null, "e": 1438, "s": 913, "text": "Let’s face it, most ML scripts (well, certainly mine) are pretty messy, especially in the prototype-and-test-live-at-small-scale phase, as they involve stitching together several small tasks: retrieving data, training neural networks, running functional and behavioral tests etc. In other words, ML projects are DAG-like, and they need to be replayable, versioned, scheduled and so on: while we have successfully used Luigi before to orchestrate tasks, we hit some limitations with a growing team and big(ish) neural models." }, { "code": null, "e": 1663, "s": 1438, "text": "There is an important phase in ML-driven product development where we should be able to trust our code, but retaining the possibility of making corrections as we go, without worrying about the overall production environment:" }, { "code": null, "e": 1843, "s": 1663, "text": "before full-scale engineering, ML needs a phase of good-enough engineering, where developers are somehow empowered end-to-end to ship their work to customers, internal users, etc." }, { "code": null, "e": 2311, "s": 1843, "text": "This post is our <10 minutes introduction to a better developer life: an end-to-end ML project (from raw data to a working API) built around a simple philosophy — effective iterations means abstracting away all infrastructure from developers. While custom-built solutions may work well for special cases, we show how off-the-shelf tools — Metaflow, SageMaker, Serverless — can be combined for a great PaaS experience, as all computing is managed automatically for us:" }, { "code": null, "e": 2355, "s": 2311, "text": "in other words, from MLOps to NoOps at all." }, { "code": null, "e": 2419, "s": 2355, "text": "All the code is shared on Github: clone the repo and tag along!" }, { "code": null, "e": 2801, "s": 2419, "text": "DISCLAIMER: this is not a tutorial on Metaflow, but a practical example of how tools can be combined to provide a better experience: while the repo should work with just copy+paste, some things may be unclear if you are not too familiar with Metaflow, SageMaker, etc.. It should be pretty straightforward to fill the gaps, but going through Netflix tutorials is always a good idea." }, { "code": null, "e": 3095, "s": 2801, "text": "We assume the following setup on your dev machine (see the Medium story replies, for some additional tips): there is already a ton of materials on these steps and we want to focus on the value provided by the system as a whole (which is what justifies going through setup in the first phase!)." }, { "code": null, "e": 3317, "s": 3095, "text": "An AWS account: this is obvious, but please note that the free-tier won’t cut it for Metaflow! Make sure to have a suitable IAM role ready, as your development machine will need permissions to spin-up SageMaker endpoints." }, { "code": null, "e": 3659, "s": 3317, "text": "Metaflow up and running: go through the AWS-based setup, which is simplified by the CloudFormation template! Please note that if the @batch decorator is commented out, a local setup may work as well with some changes: if you are just curious, you can start local and go to the full AWS-backed configuration after you’re sold on the approach." }, { "code": null, "e": 3750, "s": 3659, "text": "Serverless up and running: make sure you can deploy code to AWS lambda from your terminal." }, { "code": null, "e": 3920, "s": 3750, "text": "If you wish to add experiment tracking, we have added some tips at the end: to start, just open a community account for MLFlow or a personal account on Weights & Biases." }, { "code": null, "e": 4068, "s": 3920, "text": "While not a definitive list, there used to be some frequently-mentioned pain points in our team when it comes to our everyday life as ML engineers:" }, { "code": null, "e": 4258, "s": 4068, "text": "We want to organize the small tasks composing a project into a modular and replayable DAG-like structure: we want Python and data objects to be re-usable across tasks and clearly versioned;" }, { "code": null, "e": 4971, "s": 4258, "text": "We want to assign computational resources effortlessly (i.e. without explicit provisioning/maintenance) per task, as we don’t want to run simple business logic on expensive GPUs, but we also don’t want to wait days for training runs. Since Snowflake allows us to do calculations directly in the data warehouse (a long story for another post!), our modus operandi is eminently non-distributed, and designed to be so: datasets fit comfortably in a laptop, and local development is way more efficient than iterating on Spark. Our bottleneck is mostly training, as we sometimes train big(ish) models on GPUs: however, naively switching context between local and cloud machines is very inefficient and time consuming;" }, { "code": null, "e": 5143, "s": 4971, "text": "We want to work well together, that is, having visibility on all our DAGs, experiments and artifacts, but also making sure we don’t overwrite each other’s runs by mistake;" }, { "code": null, "e": 5350, "s": 5143, "text": "We want a clear “path-to-make-an-impact”: even in a prototyping phase, we want support for deployment and scheduling — the goal is to able to push pretty robust micro-services without involving other teams." }, { "code": null, "e": 5501, "s": 5350, "text": "Metaflow (+ SageMaker) allows us to satisfy all these desiderata in a unified framework (plus additional perks, like the super-performant s3 client!)." }, { "code": null, "e": 5792, "s": 5501, "text": "The project is a one-file DAG, centered around a regression model in Keras. The code is “toy” in many ways, but it shows how to go from a dataset to an API through a repeatable, modular and scalable process: the code is not particularly terse, but we aim for explanatory power over economy." }, { "code": null, "e": 5878, "s": 5792, "text": "The DAG is depicted in the picture below, and can be broken down in four major parts:" }, { "code": null, "e": 6459, "s": 5878, "text": "Data loading: this step is achieved through a static file — thanks to Metaflow versioning, the exact dataset that is fed to training is automatically versioned.Model training: training the chosen model by exploring the hyperparameter space and measuring model performance on hold-out data.Model choice: collect all results from model runs, and chose the model for deployment based on some logic.Deployment: deploy the model to a SageMaker endpoint. Since SageMaker endpoints are internal to AWS, we use AWS lambda to make the predictions available through public APIs (see below)." }, { "code": null, "e": 6620, "s": 6459, "text": "Data loading: this step is achieved through a static file — thanks to Metaflow versioning, the exact dataset that is fed to training is automatically versioned." }, { "code": null, "e": 6750, "s": 6620, "text": "Model training: training the chosen model by exploring the hyperparameter space and measuring model performance on hold-out data." }, { "code": null, "e": 6857, "s": 6750, "text": "Model choice: collect all results from model runs, and chose the model for deployment based on some logic." }, { "code": null, "e": 7043, "s": 6857, "text": "Deployment: deploy the model to a SageMaker endpoint. Since SageMaker endpoints are internal to AWS, we use AWS lambda to make the predictions available through public APIs (see below)." }, { "code": null, "e": 7334, "s": 7043, "text": "The entire script is ~200 lines of code and it should be pretty self-explanatory (if not, reach out!). The project showcases many features of Metaflow — such as file and object versioning, parameters, automatic retry, etc. — , but we focus here on two: parallelization and remote computing." }, { "code": null, "e": 7532, "s": 7334, "text": "Parallelization: the key lines are the following, in which we first define a range of parameters (here, using different learning rates for pedagogical purposes) and then we use the foreach keyword:" }, { "code": null, "e": 7618, "s": 7532, "text": "self.learning_rates = [0.1, 0.2]self.next(self.train_model, foreach='learning_rates')" }, { "code": null, "e": 7787, "s": 7618, "text": "What happens is that the train_model step will be executed in parallel, with Metaflow spinning out new processes, each training a model with a particular learning rate." }, { "code": null, "e": 7984, "s": 7787, "text": "Remote computing: the key line is the following (you can actually comment it out the first time, to appreciate how your development experience is really the same, with or without cloud-computing):" }, { "code": null, "e": 8012, "s": 7984, "text": "@batch(gpu=1, memory=80000)" }, { "code": null, "e": 8500, "s": 8012, "text": "With this decorator, you tell Metaflow that the ensuing task has some computing requirements (here expressed as GPU and memory capacity, but “number of CPUs” is a popular option): Metaflow automatically creates a job in AWS Batch, then runs the step on a GPU-enabled machine. This shows how to integrate local dataset preparation with remote training, without change in code or explicit resource provisioning: the DAG stays the same, and it is Metaflow job to distribute the computation." }, { "code": null, "e": 8657, "s": 8500, "text": "Metaflow gets us the comfort and speed of local debugging in data wrangling, and then a pool of unbounded computational resources when horsepower is needed." }, { "code": null, "e": 8967, "s": 8657, "text": "If you are curious to see a more realistic flow, you can appreciate below the power of parallelization and remote computing: you retrieve product images from the warehouse, speed-up vectorization, get back to your laptop for the final touches (e.g. filtering), and then finally train your deep neural network." }, { "code": null, "e": 9015, "s": 8967, "text": "“Talk is cheap, show me the code” — L. Torvalds" }, { "code": null, "e": 9180, "s": 9015, "text": "To run the project, cd into the flow directory and type the following command under your Python interpreter (make sure packages in requirements.txt are installed!):" }, { "code": null, "e": 9203, "s": 9180, "text": "python training.py run" }, { "code": null, "e": 9406, "s": 9203, "text": "After some quick checks, the DAG will load the data and then start parallelizing the training steps (if you are running with the batch decorator, AWS Batch console will track the two processes for you):" }, { "code": null, "e": 9536, "s": 9406, "text": "At the end of each training process, the terminal will print the cloud path of the model, as versioned by the built-in s3 client:" }, { "code": null, "e": 9714, "s": 9536, "text": "At the end of the DAG, a new SageMaker endpoint will be deployed: write down its name, as that is the only information we need to start serving predictions through a public API." }, { "code": null, "e": 9983, "s": 9714, "text": "After a run is concluded, we have to make sure our new model can be accessed through a devoted micro-service. We deploy a PaaS endpoint, leveraging the Infrastructure-as-Code setup in serverless.yml: simply cd into the serverless folder, and run the following command:" }, { "code": null, "e": 10025, "s": 9983, "text": "serverless deploy --sagemaker my-endpoint" }, { "code": null, "e": 10157, "s": 10025, "text": "where my-endpoint is the name of the endpoint created by the DAG. After a minute or so, you should be greeted by a success message:" }, { "code": null, "e": 10241, "s": 10157, "text": "Write down the endpoint URL, paste it in the browser and try to supply one x value:" }, { "code": null, "e": 10292, "s": 10241, "text": "https://my-url.amazonaws.com/dev/predict?x=9.45242" }, { "code": null, "e": 10386, "s": 10292, "text": "Et voilà — the browser should return our JSON response, with a pretty decent execution time:" }, { "code": null, "e": 10539, "s": 10386, "text": "As far as systematically tracking our experiments, we could exploit Metaflow built-in versioning and its handy client API to retrieve what we stored in:" }, { "code": null, "e": 10567, "s": 10539, "text": "self.hist = history.history" }, { "code": null, "e": 10804, "s": 10567, "text": "and quickly plot loss / epochs in a notebook — but in a truly PaaS spirit of never write code unless you really need to, why don’t we re-use the neat UI of MLflow or W&B? Luckily, we can add tracking to our DAG with a few lines of code." }, { "code": null, "e": 11030, "s": 10804, "text": "At the very beginning of the train_model step, we inject some small code to make sure that i) the machine (local or remote) running the code has MLflow/W&B installed and ii) credentials are available as environment variables." }, { "code": null, "e": 11261, "s": 11030, "text": "os.system('pip install mlflow==1.13.1')os.environ[\"DATABRICKS_HOST\"] = 'https://community.cloud.databricks.com' # don't change thisos.environ[\"DATABRICKS_USERNAME\"] = 'my_user_name'os.environ[\"DATABRICKS_PASSWORD\"] = 'my_password'" }, { "code": null, "e": 11438, "s": 11261, "text": "(The same basic idea applies to W&B, but the env variable you need to set is the API KEY). Now that the library is installed, we can just exploit autologging to start tracking:" }, { "code": null, "e": 11634, "s": 11438, "text": "import mlflow# don't change this for Community editionmlflow.set_tracking_uri(\"databricks\")# your experiment name mlflow.set_experiment(\"/Users/my_user_name/exp_name\") mlflow.tensorflow.autolog()" }, { "code": null, "e": 11752, "s": 11634, "text": "The next time the DAG is executed, the Databricks dashboard will record and display the key metrics for all our runs:" }, { "code": null, "e": 11796, "s": 11752, "text": "This is the same output, using W&B instead:" }, { "code": null, "e": 12138, "s": 11796, "text": "As promised, we went from data loading to a model-based API in less than 10 minutes and without any infrastructure work: if you have the same pain points we had, our script gives you a worked-out example of how Metaflow-centric development (plus, some carefully chosen PaaS services) radically simplifies real-life machine learning projects." }, { "code": null, "e": 12370, "s": 12138, "text": "While the NoOps slogan is certainly a bit too good to be literally true, we do believe that good abstractions will make DevOps operations less and less visible in ML pipelines, allowing us to focus more and more on data and models." }, { "code": null, "e": 12463, "s": 12370, "text": "Alas, what is the history of software engineering, if not a series of powerful abstractions?" }, { "code": null, "e": 12712, "s": 12463, "text": "Don’t forget to check the additional notes (in the story replies) for more technical details, setup tips and notes for future iterations. If you have questions or feedback, please connect and share your MLOps story (all Medium opinions are my own)." } ]
Understanding Images with skimage-Python | by Mathanraj Sharma | Towards Data Science
Computer Vision is a buzz word nowadays. Many useful applications and systems are emerging by incorporating Computer Vision techniques with AI and ML Image Processing is an important tool that every professional in Computer Vision should have in their toolbox. Image Processing is the use of algorithms to perform various operations on digital images. Such as, Enhancing an Image Extract useful information Analyzing Images Image processing is used in various fields like Medical image analysis, AI, Image restoration, Geospatial computing, Surveillance, Robotic vision, Automative safety, and many more. I am going to write a series of articles that will give you a practical understanding of some key Operations in Digital Image Processing using skimage in Python. In this first article let us understand how a digital image is captured and represented in a Digital Format. It all begins with the light which passes through the lens of the camera. By the lens, it is focused on the Image plane of the camera. The image plane holds sensors(pixels) usually in a square or rectangle-shape. Sometimes they can be hexagonal or circular sensors based on the make of the camera. What is projected by the light on this plane is a two-dimensional, time-dependent, continuous distribution of light energy. A digital snapshot of this analog signal is captured in three steps, Spatial Sampling-this is the step where the continuous analog signal is converted into its discrete representation.Temporal Sampling- this is the step that measures the amount of light incident on each sensor in a regular interval.Quantization of Pixel Values- The above two samplings is the data which will give our Digital Image. But to store and process it, we need to convert them into a range of integer values. (example 256 = 28) Spatial Sampling-this is the step where the continuous analog signal is converted into its discrete representation. Temporal Sampling- this is the step that measures the amount of light incident on each sensor in a regular interval. Quantization of Pixel Values- The above two samplings is the data which will give our Digital Image. But to store and process it, we need to convert them into a range of integer values. (example 256 = 28) The converted pixel values will later be stored in a format of a two-dimensional, ordered matrix of integers. Let’s assume “I” is the matrix format of our image. The Size of the image is simply the width and height of the I. from skimage import io#replace the path of imageimage = io.imread('~/Desktop/Lenna.png')print(image.shape)print(type(image))Output:(512, 512, 3)<class 'imageio.core.util.Array'> In the above example output (512, 512,3) represents the width, height, and a number of channels in the image. And look that our image is represented in the format of Array. On the other hand, Resolution is the spatial dimension of an image in the real world, and it is usually given as the number of image elements per measurements (example dpi, dots per inch). In image processing, the coordinate system is flipped in the vertical direction. The origin of the axis will be at the left top corner. Each square in the coordinate plane is known as a pixel. Each pixel will hold a quantized value acquired when capturing an image. Pixel values are normally given in binary words of k. (example 28) from skimage import ioimage = io.imread('~/Desktop/Lenna.png')print(image[0][0])Output:[226 137 125] The output has a list of three different integers because here I have loaded a color image. Usually, a color image is represented using three channels (RGB). Here 255, 137, 125 are the intensity values of red, green, blue color channels. Channels are referred to as the number of colors in an image. Based on channels images are normally divided into two categories. Grayscale Images Grayscale images are represented using a Single color channel of black and its variations. Here each pixel will get a value between 0–255 if it is an 8-bit representation. But the range of pixel value may differ based on the k-bit representation. from skimage import ioimage = io.imread('~/Desktop/Lenna_gray.png')print(image.shape)print(type(image))print(image[0][0])Output:(256, 256)<class 'imageio.core.util.Array'>161 As you can see in the above example the first location of our image array only holds a single value of 161. Color Images Usually, Color Images are represented using RGB three color channels. There will be three channels and pixels in each channel will have a value between 0–255 based on the intensity of each red, green, blue. from skimage import ioimage = io.imread('~/Desktop/Lenna.png')print(image.shape)print(type(image))print(image[0][0])Output:(512, 512, 3)<class 'imageio.core.util.Array'>[226 137 125] Note: You can pass any value between your 0 to width-1, 0 to height-1 in image[0][0]. Here it prints a list of three values, R = 256, G=137 and B=125 are the intensity values. I hope you have gained some basic understanding of images and how to load and get properties of images. Let us meet again in the next topic in Image Processing.
[ { "code": null, "e": 322, "s": 172, "text": "Computer Vision is a buzz word nowadays. Many useful applications and systems are emerging by incorporating Computer Vision techniques with AI and ML" }, { "code": null, "e": 533, "s": 322, "text": "Image Processing is an important tool that every professional in Computer Vision should have in their toolbox. Image Processing is the use of algorithms to perform various operations on digital images. Such as," }, { "code": null, "e": 552, "s": 533, "text": "Enhancing an Image" }, { "code": null, "e": 579, "s": 552, "text": "Extract useful information" }, { "code": null, "e": 596, "s": 579, "text": "Analyzing Images" }, { "code": null, "e": 777, "s": 596, "text": "Image processing is used in various fields like Medical image analysis, AI, Image restoration, Geospatial computing, Surveillance, Robotic vision, Automative safety, and many more." }, { "code": null, "e": 1048, "s": 777, "text": "I am going to write a series of articles that will give you a practical understanding of some key Operations in Digital Image Processing using skimage in Python. In this first article let us understand how a digital image is captured and represented in a Digital Format." }, { "code": null, "e": 1539, "s": 1048, "text": "It all begins with the light which passes through the lens of the camera. By the lens, it is focused on the Image plane of the camera. The image plane holds sensors(pixels) usually in a square or rectangle-shape. Sometimes they can be hexagonal or circular sensors based on the make of the camera. What is projected by the light on this plane is a two-dimensional, time-dependent, continuous distribution of light energy. A digital snapshot of this analog signal is captured in three steps," }, { "code": null, "e": 1975, "s": 1539, "text": "Spatial Sampling-this is the step where the continuous analog signal is converted into its discrete representation.Temporal Sampling- this is the step that measures the amount of light incident on each sensor in a regular interval.Quantization of Pixel Values- The above two samplings is the data which will give our Digital Image. But to store and process it, we need to convert them into a range of integer values. (example 256 = 28)" }, { "code": null, "e": 2091, "s": 1975, "text": "Spatial Sampling-this is the step where the continuous analog signal is converted into its discrete representation." }, { "code": null, "e": 2208, "s": 2091, "text": "Temporal Sampling- this is the step that measures the amount of light incident on each sensor in a regular interval." }, { "code": null, "e": 2413, "s": 2208, "text": "Quantization of Pixel Values- The above two samplings is the data which will give our Digital Image. But to store and process it, we need to convert them into a range of integer values. (example 256 = 28)" }, { "code": null, "e": 2523, "s": 2413, "text": "The converted pixel values will later be stored in a format of a two-dimensional, ordered matrix of integers." }, { "code": null, "e": 2638, "s": 2523, "text": "Let’s assume “I” is the matrix format of our image. The Size of the image is simply the width and height of the I." }, { "code": null, "e": 2816, "s": 2638, "text": "from skimage import io#replace the path of imageimage = io.imread('~/Desktop/Lenna.png')print(image.shape)print(type(image))Output:(512, 512, 3)<class 'imageio.core.util.Array'>" }, { "code": null, "e": 2989, "s": 2816, "text": "In the above example output (512, 512,3) represents the width, height, and a number of channels in the image. And look that our image is represented in the format of Array." }, { "code": null, "e": 3178, "s": 2989, "text": "On the other hand, Resolution is the spatial dimension of an image in the real world, and it is usually given as the number of image elements per measurements (example dpi, dots per inch)." }, { "code": null, "e": 3314, "s": 3178, "text": "In image processing, the coordinate system is flipped in the vertical direction. The origin of the axis will be at the left top corner." }, { "code": null, "e": 3511, "s": 3314, "text": "Each square in the coordinate plane is known as a pixel. Each pixel will hold a quantized value acquired when capturing an image. Pixel values are normally given in binary words of k. (example 28)" }, { "code": null, "e": 3612, "s": 3511, "text": "from skimage import ioimage = io.imread('~/Desktop/Lenna.png')print(image[0][0])Output:[226 137 125]" }, { "code": null, "e": 3850, "s": 3612, "text": "The output has a list of three different integers because here I have loaded a color image. Usually, a color image is represented using three channels (RGB). Here 255, 137, 125 are the intensity values of red, green, blue color channels." }, { "code": null, "e": 3979, "s": 3850, "text": "Channels are referred to as the number of colors in an image. Based on channels images are normally divided into two categories." }, { "code": null, "e": 3996, "s": 3979, "text": "Grayscale Images" }, { "code": null, "e": 4243, "s": 3996, "text": "Grayscale images are represented using a Single color channel of black and its variations. Here each pixel will get a value between 0–255 if it is an 8-bit representation. But the range of pixel value may differ based on the k-bit representation." }, { "code": null, "e": 4418, "s": 4243, "text": "from skimage import ioimage = io.imread('~/Desktop/Lenna_gray.png')print(image.shape)print(type(image))print(image[0][0])Output:(256, 256)<class 'imageio.core.util.Array'>161" }, { "code": null, "e": 4526, "s": 4418, "text": "As you can see in the above example the first location of our image array only holds a single value of 161." }, { "code": null, "e": 4539, "s": 4526, "text": "Color Images" }, { "code": null, "e": 4746, "s": 4539, "text": "Usually, Color Images are represented using RGB three color channels. There will be three channels and pixels in each channel will have a value between 0–255 based on the intensity of each red, green, blue." }, { "code": null, "e": 4929, "s": 4746, "text": "from skimage import ioimage = io.imread('~/Desktop/Lenna.png')print(image.shape)print(type(image))print(image[0][0])Output:(512, 512, 3)<class 'imageio.core.util.Array'>[226 137 125]" }, { "code": null, "e": 5015, "s": 4929, "text": "Note: You can pass any value between your 0 to width-1, 0 to height-1 in image[0][0]." }, { "code": null, "e": 5105, "s": 5015, "text": "Here it prints a list of three values, R = 256, G=137 and B=125 are the intensity values." } ]
Ensemble Learning case study: Model Interpretability | by Gabriel Signoretti | Towards Data Science
This is the first of a two-part article where we will be exploring the 1994 census income dataset, which contains information such as age, years of education, marital status, race, and many others. We will be using this dataset to classify if the potential income of people into 2 categories: people who make less or equal to $50K a year (encoded as 0) and people who make more than $50K a year (encoded as 1). In this first part, we will be using this dataset to compare the performance of a simple decision tree to the performance of ensemble methods. Later on, we will also explore some tools to help us interpret why the models made the decisions that they did following some principles of eXplainable Artificial Intelligence (XAI). The first thing we need to do is to take a look at the chosen dataset to get to know it a little better. So, let's get right on to it! We will be working with a pre-processed version of the dataset free of null values. First of all, we load the basic libraries and the dataset itself and take a look at the dataframe info: import as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsplt.style.use('ggplot')# load the datasetincome = pd.read_csv("income.csv")income.info() As we can see, the dataset has 32561 observations and 15 columns, 14 of them being features and one the target variable (high_income). Some of those features are categorical (type object) and some are numeric (type int64) so we will need to perform different preprocessing steps for them. To accomplish this, we will create two Pipelines: one will perform the preprocessing steps on the categorical features and the other on the numerical ones. Then, we will use FeatureUnion to join these two pipelines together to form the final preprocessing pipeline. To do this and the following steps in this article we need to import the necessary modules from the scikit-learn library: from sklearn.base import BaseEstimatorfrom sklearn.base import TransformerMixinfrom sklearn.preprocessing import StandardScalerfrom sklearn.preprocessing import FunctionTransformerfrom sklearn.pipeline import Pipelinefrom sklearn.pipeline import FeatureUnionfrom sklearn.model_selection import train_test_splitfrom sklearn.model_selection import cross_val_scorefrom sklearn.model_selection import KFoldfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.model_selection import RandomizedSearchCVfrom sklearn.metrics import make_scorerfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_reportfrom sklearn.metrics import confusion_matrixfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.ensemble import BaggingClassifier Using the BaseEstimator and the TranformerMixin classes we can create two custom transformers to put on our pipeline: one to split the data into categorical and numerical features and another to preprocess the categorical features. Both theses transformer can be seen below: # Custom Transformer that extracts columns passed as argumentclass FeatureSelector(BaseEstimator, TransformerMixin): #Class Constructor def __init__(self, feature_names): self.feature_names = feature_names #Return self nothing else to do here def fit(self, X, y = None): return self #Method that describes what we need this transformer to do def transform(self, X, y = None): return X[self.feature_names]# converts certain features to categoricalclass CategoricalTransformer( BaseEstimator, TransformerMixin ): #Class constructor method that takes a boolean as its argument def __init__(self, new_features=True): self.new_features = new_features #Return self nothing else to do here def fit( self, X, y = None ): return self #Transformer method we wrote for this transformer def transform(self, X , y = None ): df = X.copy() if self.new_features: # Treat ? workclass as unknown df['workclass']= df['workclass'].replace('?','Unknown') # Two many category level, convert just US and Non-US df.loc[df['native_country']!=' United-States','native_country'] = 'non_usa' df.loc[df['native_country']==' United-States','native_country'] = 'usa' # convert columns to categorical for name in df.columns.to_list(): col = pd.Categorical(df[name]) df[name] = col.codes # returns numpy array return df With these custom transformers at hand, we can build the preprocessing pipeline. The first thing we need to do is create the X feature matrix and the y target vector: # Create the X feature matrix and the y target vectorX = income.drop(labels="high_income", axis=1)y = income["high_income"]# the only step necessary to be done outside of pipeline# convert the target column to categoricalcol = pd.Categorical(y)y = pd.Series(col.codes)# global variablesseed = 108 After that, we extract the categorical and numerical feature names and create the 2 pipelines after defining the steps to be used in each of them. For the categorical pipeline, we use the FeatureSelector to select only the categorical columns followed by the CategoricalTransformer to transform the data to the desired format; as for the numerical pipeline, we will also use the FestureSelector, this time to select only the numerical features, followed by as StandardScaler to normalize the data. The code can be seen below: # get the categorical feature namescategorical_features = X.select_dtypes("object").columns.to_list()# get the numerical feature namesnumerical_features = X.select_dtypes("int64").columns.to_list()# create the steps for the categorical pipelinecategorical_steps = [ ('cat_selector', FeatureSelector(categorical_features)), ('cat_transformer', CategoricalTransformer())]# create the steps for the numerical pipelinenumerical_steps = [ ('num_selector', FeatureSelector(numerical_features)), ('std_scaler', StandardScaler()),]# create the 2 pipelines with the respective stepscategorical_pipeline = Pipeline(categorical_steps)numerical_pipeline = Pipeline(numerical_steps) Now we can use the FeatureUnion class to join the two pipeline horizontally, that way we end up with only one final preprocessing pipeline: pipeline_list = [ ('categorical_pipeline', categorical_pipeline), ('numerical_pipeline', numerical_pipeline)]# Combining the 2 pieplines horizontally into one full pipeline preprocessing_pipeline =FeatureUnion(transformer_list=pipeline_list) And that's it, now all you have to do to perform all the preprocessing steps on your data is to call the fit_transform method of the preprocessing_pipeline object passing the X matrix as an argument! simple and concise. Before training any machine learning model we have to split the data into a train and a test set. To do this we use the train_test_split function: # split-out train/validation and test datasetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=seed, shuffle=True, stratify=y) The first model we will use is a simple DecisionTreeClassifier. To finish leveraging the full power of Pipelines, we can create a full pipeline passing the preprocessing pipeline as the first step and the desired classification model as the second step: # we pass the preprocessing pipeline as a step to the full pipelinefull_pipeline_steps = [ ('preprocessing_pipeline', preprocessing_pipeline), ('model', DecisionTreeClassifier(random_state=seed))]# create the full pipeline objectfull_pipeline = Pipeline(steps=full_pipeline_steps) This way, if we want to try different models (as we will later on), all we have to do is update the 'model' step of this pipeline! The next step is to use RandomizedSearchCV to perform the model hyperparameter tunning. Randomized search is not as thorough as a regular grid search, as it does not test every possible combination of hyperparameters. On the other hand, it is more computationally cheap, enabling us to achieve 'good enough' results in lower-end hardware while tuning multiple hyperparameters. With the n_iter parameter, we limit the number of iterations to 50. We will also use StratifiedKFold to perform cross-validation. Unlike the regular KFold, it preserves the sample's distribution across folds, potentially leading to better results. The final step is to build a param_grid dictionary with the hyperparameters that we need to tune. The full code can be seen below. Notice how we pass the full_pipeline object as the RandomizedSearchCV estimator and then we call the fit method on the resulting object as we would any other sklearn model. This way, when we want to ty other models, all we have to do is change the model on the pipeline and create a new parameter grid to pass, simple as that! # Create the grid search parameter grid and scoring funcitonsparam_grid = { "model": [DecisionTreeClassifier(random_state=seed)], "model__criterion": ["gini","entropy"], "model__splitter": ["best","random"], "model__max_leaf_nodes": [16, 64, 128, 256], "model__max_depth": np.linspace(1, 32, 32)}scoring = { 'AUC': 'roc_auc', 'Accuracy': make_scorer(accuracy_score)}# create the Kfold objectnum_folds = 10kfold = StratifiedKFold(n_splits=num_folds, random_state=seed)# create the grid search object with the full pipeline as estimatorn_iter=50grid = RandomizedSearchCV( estimator=full_pipeline, param_distributions=param_grid, cv=kfold, scoring=scoring, n_jobs=-1, n_iter=n_iter, refit="AUC")# fit grid searchbest_model = grid.fit(X_train,y_train) For the DecisionTreeClassifier we are tunning the following parameters: criterion: defines the function to measure the quality of the splits on the tree nodes; splitter: defines the strategy used to choose the split at each tree node; max_leaf_nodes: limits the maximum number of leaf nodes in the tree; max_depth: limits the maximum depth that the tree can grow; After the randomized search finishes and the best model is fitted to our data, we can make predictions and measure the model's performance: # final Decision Tree modelpred_test = best_model.predict(X_test)pred_train = best_model.predict(X_train)print('Train Accuracy: ', accuracy_score(y_train, pred_train))print('Test Accuraccy: ', accuracy_score(y_test, pred_test))print('\nConfusion Matrix:')print(confusion_matrix(y_test,pred_test))print('\nClassification Report:')print(classification_report(y_test,pred_test)) Ensemble methods are models that combine several base models in order to produce one optimal predictive model. The RandomForestClassifier is a classical example of this, as it combines several simpler DecisionTrees to generate the output. With this, is possible to overcome several limitations of the decision tree model, such as it's tendency to overfit. The first ensemble method that we are going to work with is the BaggingClassifier. The name bagging comes from bootstrap aggregating and it works by splitting the data into several random subsamples that are then used to train each individual base estimator. This strategy can be performed in one of two ways: with replacement, meaning that the samples can be used several times for the same estimator; and without replacement, meaning that each individual sample can be used only one time (this approach is called Pasting). Bagging generally yields better results than Pasting and it also has a neat trick up its sleeve: Out-of-Bag evaluation. Since the samples are drawn with replacement and the same sample can be used multiple times randomly, some samples on the training set may never be used to train any of the base estimators! This means that we can use these samples for further model evaluation! So, with all that in mind, we are going to update our previous pipeline to work with the BaggingClassifier with a DecisionTree as the base estimator. To do that, all we have to do is change the ‘model’ step in the pipeline definition and redefine the RandomizedSearchCV parameter search space, as it can be seen in the code snippet below: # we pass the preprocessing pipeline as a step to the full pipelinefull_pipeline_steps = [ ('preprocessing_pipeline', preprocessing_pipeline), ('model', BaggingClassifier( DecisionTreeClassifier(max_features="auto", splitter="random", max_leaf_nodes=128, random_state=seed), random_state=seed ))]# create the full pipeline objectfull_pipeline = Pipeline(steps=full_pipeline_steps)# Create the grid search parameter gridparam_grid = { "model": [BaggingClassifier( DecisionTreeClassifier(max_features="auto", splitter="random", max_leaf_nodes=128, random_state=seed), random_state=seed )], "model__n_estimators": np.arange(100, 1000, 100), "model__max_samples":[0.8, 1.0], "model__max_features": [0.8, 1.0], "model__bootstrap": [True], "model__oob_score": [True],}scoring = { 'AUC': 'roc_auc', 'Accuracy': make_scorer(accuracy_score)}# create the Kfold objectnum_folds = 10kfold = StratifiedKFold(n_splits=num_folds, random_state=seed)# create the grid search object with the full pipeline as estimatorn_iter=25grid = RandomizedSearchCV( estimator=full_pipeline, param_distributions=param_grid, cv=kfold, scoring=scoring, n_jobs=-1, n_iter=n_iter, refit="AUC") # fit grid searchbest_bag = grid.fit(X_train,y_train) For the BaggingClassifier we are tunning the following parameters: n_estimators: defines the total number of estimators (in this case decision trees) to use; max_samples: The maximum percentage of samples to draw from X to train each base estimator; max_features: The maximum percentage of features to draw from X to train each base estimator; bootstrap: When set to False, draw samples without replacement (Pasting). When set to True, draw samples with replacement (bagging). Since we are going to use the out-of-bag score, we have to set this parameter to True; oob_score: When set to True, return the out-of-bag score of the best model; After the randomized search finishes and the best model is fitted to our data, we can check the tunned model hyperparameters, make predictions and measure the model’s performance: print(f'Best score: {best_bag.best_score_}')print(f'Best model: {best_bag.best_params_}') pred_test = best_bag.predict(X_test)pred_train = best_bag.predict(X_train)print('Train Accuracy: ', accuracy_score(y_train, pred_train))print('Test Accuraccy: ', accuracy_score(y_test, pred_test))print("Out-of-Bag Accuracy: ", best_bag.best_params_['model'].oob_score_)print('\nConfusion Matrix:')print(confusion_matrix(y_test,pred_test))print('\nClassification Report:')print(classification_report(y_test,pred_test)) As we can see, all 3 accuracies achieved by the model are very close to each other, indicating that the model generalized well for new data and thus may not be overfitted. The last model we will be training is the RandomForestClassifier. The process to use it is the same as the one presented above and can be seen in the code snippet below: # we pass the preprocessing pipeline as a step to the full pipelinefull_pipeline_steps = [ ('preprocessing_pipeline', preprocessing_pipeline), ('model', RandomForestClassifier(random_state=seed))]# create the full pipeline objectfull_pipeline = Pipeline(steps=full_pipeline_steps)# Create the grid search parameter grid and scoring funcitonsparam_grid = { "model": [RandomForestClassifier(random_state=seed)], "model__max_depth": np.linspace(1, 32, 32), "model__n_estimators": np.arange(100, 1000, 100), "model__criterion": ["gini","entropy"], "model__max_leaf_nodes": [16, 64, 128, 256], "model__oob_score": [True],}scoring = { 'AUC': 'roc_auc', 'Accuracy': make_scorer(accuracy_score)}# create the Kfold objectnum_folds = 10kfold = StratifiedKFold(n_splits=num_folds, random_state=seed)# create the grid search object with the full pipeline as estimatorn_iter=50grid = RandomizedSearchCV( estimator=full_pipeline, param_distributions=param_grid, cv=kfold, scoring=scoring, n_jobs=-1, n_iter=n_iter, refit="AUC")# fit grid searchbest_rf = grid.fit(X_train,y_train) For the RandomForestClassifier we are tunning the following parameters: criterion: defines the function to measure the quality of the splits on the tree nodes; max_leaf_nodes: limits the maximum number of leaf nodes in the trees; max_depth: limits the maximum depth that the trees can grow; n_estimators: defines the total number of trees to use in the forest oob_score: When set to True, return the out-of-bag score of the best model; As we did before, after the randomized search finishes and the best model is fitted to our data, we can make predictions and measure the model’s performance: print(f'Best score: {best_rf.best_score_}')print(f'Best model: {best_rf.best_params_}') pred_test = best_rf.predict(X_test)pred_train = best_rf.predict(X_train)print('Train Accuracy: ', accuracy_score(y_train, pred_train))print('Test Accuraccy: ', accuracy_score(y_test, pred_test))print("Out-of-Bag Accuracy: ", best_rf.best_params_['model'].oob_score_)print('\nConfusion Matrix:')print(confusion_matrix(y_test,pred_test))print('\nClassification Report:')print(classification_report(y_test,pred_test)) Similar to the BaggingClassifier, the accuracies are very close to each other, indicating good generalization for unseen data and thus, no overfitting. As this was the best performing model we have found, we will use it as an example for the rest of the article. In some cases, getting good predictions from your model is arguably as important as to understand why it is giving the answers that it does. In those cases is where we can leverage the concepts of eXplainable Artificial Intelligence (XAI) and try to make the models more human interpretable. One way to do this is by analyzing the importance of each feature in the model outcome. Luckily for us, the random forest has a built-in attribute that can tell us just that, its called feature_importances_. The steps performed to access and plot this information is presented in the code below: # lets get the random forest model configuration and feature namesrf_model = best_rf.best_params_['model']features = np.array(X_train.columns)# Transforming the test data.new_X_test = preprocessing_pipeline.fit_transform(X_test)new_X_test = pd.DataFrame(new_X_test, columns=X_test.columns)# get the predicitons from the random forest objecty_pred = rf_model.predict(new_X_test)# get the feature importancesimportances = rf_model.feature_importances_# sort the indexessorted_index = np.argsort(importances)sorted_importances = importances[sorted_index]sorted_features = features[sorted_index]# plot the explained variance using a barplotfig, ax = plt.subplots()ax.barh(sorted_features , sorted_importances)ax.set_xlabel('Importances')ax.set_ylabel('Features') This is an example of a simple, and yet effective, way to gain more insight both on your data and on your model's reasoning. With the plot, we can see that the most important features were education_num, capital_loss, fnlwgt, capital_gain, and race. To go even further, we will briefly explore two third party libraries that enable us to get different visualizations: ELI5 and SHAP. ELI5 is a Python package that helps to debug machine learning classifiers and explain their predictions. It provides support for some machine learning libraries, including scikit-learn and XGBoost. With it, we are able to look at a classification model in two main ways: the first is to inspect the model parameters and analyze how the model works globally (similarly to the default feature importance attribute); the second is to inspect individual predictions to figure out why the model makes the decisions that it does. For the first use case we use the show_weights() function as shown in the code snippet below: import eli5# lets get the random forest model configuration and feature namesrf_model = best_rf.best_params_['model']features = np.array(X_train.columns)eli5.show_weights(rf_model, feature_names=features) As we can see in the image above, the results are pretty similar to the one we obtained from the tree feature importances. As for the second use case, we can use the explain_prediction() function to inspect and analyze individual predictions of the model. To test this out, we checked a true negative prediction (actual value was 0 and the predicted value was also 0) and a true positive prediction (actual value was 1 and the predicted value was also 1): # predicting a person earns less than 50k/year (true negative)index = 4print('Actual Label:', y_test.iloc[index])print('Predicted Label:', y_pred[index])eli5.explain_prediction(rf_model, new_X_test.iloc[index], feature_names=features)# predicting a person earns more than 50k/year (true positive)index = 7print('Actual Label:', y_test.iloc[index])print('Predicted Label:', y_pred[index])eli5.explain_prediction(rf_model, new_X_test.iloc[index], feature_names=features) So, the most influential features that contributed for the model to predict that these particular observations were respectively race and education_num. The SHAP (SHapley Additive exPlanations) library is a unified approach to explain the output of any machine learning model. Similarly to the ELI5, it also has support for several machine learning libraries, including scikit-learn and XGBoost. To use its functionality for our Random Forest model we first need to create a TreeExplainer object and obtain the so-called shap_values for the model. This process is shown in the code below: import shapshap.initjs()# Create the explainer objectexplainer = shap.TreeExplainer(rf_model)print('Expected Value:', explainer.expected_value)# get the shap values from the explainershap_values = explainer.shap_values(new_X_test) As we did with the ELI5, we can also use the SHAP library to explain individual model predictions, as shown below for the same data points that we worked with previously: # predicting a person earns less than 50k/year (true negative)shap.force_plot(explainer.expected_value[0], shap_values[0][4], X_test.iloc[4])# predicting a person earns more than 50k/year (true positive)shap.force_plot(explainer.expected_value[1], shap_values[1][7], X_test.iloc[7]) In addition, it is also possible to visualize multiple predictions at once, as it is shown below for the first 1000 samples of the dataset: shap.force_plot(explainer.expected_value[0], shap_values[0][:1000,:], X_test.iloc[:1000,:]) In the same plot, it is also possible to analyze the impact of different features in the final model prediction. To test this, we configured the plot to show the importance of the education_num feature on the same samples: Finally, we can use the summary_plot function to plot the feature importances divided by class: shap.summary_plot(shap_values, X_test) We can see that the obtained result is very similar to the ones obtained both by the tree built-in feature importances and the ELI5 library. We barely scratched the surface of several important topics in the machine learning landscape, such as Pipelines, hyperparameter tuning, ensemble methods, and model interpretability. There is much more to cover! In the next part of this series, we are going to take a look at the new 'cool kid on the block' of ensemble methods: Gradient Boosting. We will take a look at the implementation provided by the XGBoost library, so stay tuned!
[ { "code": null, "e": 583, "s": 172, "text": "This is the first of a two-part article where we will be exploring the 1994 census income dataset, which contains information such as age, years of education, marital status, race, and many others. We will be using this dataset to classify if the potential income of people into 2 categories: people who make less or equal to $50K a year (encoded as 0) and people who make more than $50K a year (encoded as 1)." }, { "code": null, "e": 909, "s": 583, "text": "In this first part, we will be using this dataset to compare the performance of a simple decision tree to the performance of ensemble methods. Later on, we will also explore some tools to help us interpret why the models made the decisions that they did following some principles of eXplainable Artificial Intelligence (XAI)." }, { "code": null, "e": 1044, "s": 909, "text": "The first thing we need to do is to take a look at the chosen dataset to get to know it a little better. So, let's get right on to it!" }, { "code": null, "e": 1232, "s": 1044, "text": "We will be working with a pre-processed version of the dataset free of null values. First of all, we load the basic libraries and the dataset itself and take a look at the dataframe info:" }, { "code": null, "e": 1406, "s": 1232, "text": "import as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsplt.style.use('ggplot')# load the datasetincome = pd.read_csv(\"income.csv\")income.info()" }, { "code": null, "e": 1695, "s": 1406, "text": "As we can see, the dataset has 32561 observations and 15 columns, 14 of them being features and one the target variable (high_income). Some of those features are categorical (type object) and some are numeric (type int64) so we will need to perform different preprocessing steps for them." }, { "code": null, "e": 2083, "s": 1695, "text": "To accomplish this, we will create two Pipelines: one will perform the preprocessing steps on the categorical features and the other on the numerical ones. Then, we will use FeatureUnion to join these two pipelines together to form the final preprocessing pipeline. To do this and the following steps in this article we need to import the necessary modules from the scikit-learn library:" }, { "code": null, "e": 2909, "s": 2083, "text": "from sklearn.base import BaseEstimatorfrom sklearn.base import TransformerMixinfrom sklearn.preprocessing import StandardScalerfrom sklearn.preprocessing import FunctionTransformerfrom sklearn.pipeline import Pipelinefrom sklearn.pipeline import FeatureUnionfrom sklearn.model_selection import train_test_splitfrom sklearn.model_selection import cross_val_scorefrom sklearn.model_selection import KFoldfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.model_selection import RandomizedSearchCVfrom sklearn.metrics import make_scorerfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_reportfrom sklearn.metrics import confusion_matrixfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.ensemble import BaggingClassifier" }, { "code": null, "e": 3184, "s": 2909, "text": "Using the BaseEstimator and the TranformerMixin classes we can create two custom transformers to put on our pipeline: one to split the data into categorical and numerical features and another to preprocess the categorical features. Both theses transformer can be seen below:" }, { "code": null, "e": 4672, "s": 3184, "text": "# Custom Transformer that extracts columns passed as argumentclass FeatureSelector(BaseEstimator, TransformerMixin): #Class Constructor def __init__(self, feature_names): self.feature_names = feature_names #Return self nothing else to do here def fit(self, X, y = None): return self #Method that describes what we need this transformer to do def transform(self, X, y = None): return X[self.feature_names]# converts certain features to categoricalclass CategoricalTransformer( BaseEstimator, TransformerMixin ): #Class constructor method that takes a boolean as its argument def __init__(self, new_features=True): self.new_features = new_features #Return self nothing else to do here def fit( self, X, y = None ): return self #Transformer method we wrote for this transformer def transform(self, X , y = None ): df = X.copy() if self.new_features: # Treat ? workclass as unknown df['workclass']= df['workclass'].replace('?','Unknown') # Two many category level, convert just US and Non-US df.loc[df['native_country']!=' United-States','native_country'] = 'non_usa' df.loc[df['native_country']==' United-States','native_country'] = 'usa' # convert columns to categorical for name in df.columns.to_list(): col = pd.Categorical(df[name]) df[name] = col.codes # returns numpy array return df" }, { "code": null, "e": 4839, "s": 4672, "text": "With these custom transformers at hand, we can build the preprocessing pipeline. The first thing we need to do is create the X feature matrix and the y target vector:" }, { "code": null, "e": 5136, "s": 4839, "text": "# Create the X feature matrix and the y target vectorX = income.drop(labels=\"high_income\", axis=1)y = income[\"high_income\"]# the only step necessary to be done outside of pipeline# convert the target column to categoricalcol = pd.Categorical(y)y = pd.Series(col.codes)# global variablesseed = 108" }, { "code": null, "e": 5662, "s": 5136, "text": "After that, we extract the categorical and numerical feature names and create the 2 pipelines after defining the steps to be used in each of them. For the categorical pipeline, we use the FeatureSelector to select only the categorical columns followed by the CategoricalTransformer to transform the data to the desired format; as for the numerical pipeline, we will also use the FestureSelector, this time to select only the numerical features, followed by as StandardScaler to normalize the data. The code can be seen below:" }, { "code": null, "e": 6344, "s": 5662, "text": "# get the categorical feature namescategorical_features = X.select_dtypes(\"object\").columns.to_list()# get the numerical feature namesnumerical_features = X.select_dtypes(\"int64\").columns.to_list()# create the steps for the categorical pipelinecategorical_steps = [ ('cat_selector', FeatureSelector(categorical_features)), ('cat_transformer', CategoricalTransformer())]# create the steps for the numerical pipelinenumerical_steps = [ ('num_selector', FeatureSelector(numerical_features)), ('std_scaler', StandardScaler()),]# create the 2 pipelines with the respective stepscategorical_pipeline = Pipeline(categorical_steps)numerical_pipeline = Pipeline(numerical_steps)" }, { "code": null, "e": 6484, "s": 6344, "text": "Now we can use the FeatureUnion class to join the two pipeline horizontally, that way we end up with only one final preprocessing pipeline:" }, { "code": null, "e": 6732, "s": 6484, "text": "pipeline_list = [ ('categorical_pipeline', categorical_pipeline), ('numerical_pipeline', numerical_pipeline)]# Combining the 2 pieplines horizontally into one full pipeline preprocessing_pipeline =FeatureUnion(transformer_list=pipeline_list)" }, { "code": null, "e": 6952, "s": 6732, "text": "And that's it, now all you have to do to perform all the preprocessing steps on your data is to call the fit_transform method of the preprocessing_pipeline object passing the X matrix as an argument! simple and concise." }, { "code": null, "e": 7099, "s": 6952, "text": "Before training any machine learning model we have to split the data into a train and a test set. To do this we use the train_test_split function:" }, { "code": null, "e": 7263, "s": 7099, "text": "# split-out train/validation and test datasetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=seed, shuffle=True, stratify=y)" }, { "code": null, "e": 7517, "s": 7263, "text": "The first model we will use is a simple DecisionTreeClassifier. To finish leveraging the full power of Pipelines, we can create a full pipeline passing the preprocessing pipeline as the first step and the desired classification model as the second step:" }, { "code": null, "e": 7804, "s": 7517, "text": "# we pass the preprocessing pipeline as a step to the full pipelinefull_pipeline_steps = [ ('preprocessing_pipeline', preprocessing_pipeline), ('model', DecisionTreeClassifier(random_state=seed))]# create the full pipeline objectfull_pipeline = Pipeline(steps=full_pipeline_steps)" }, { "code": null, "e": 7935, "s": 7804, "text": "This way, if we want to try different models (as we will later on), all we have to do is update the 'model' step of this pipeline!" }, { "code": null, "e": 8380, "s": 7935, "text": "The next step is to use RandomizedSearchCV to perform the model hyperparameter tunning. Randomized search is not as thorough as a regular grid search, as it does not test every possible combination of hyperparameters. On the other hand, it is more computationally cheap, enabling us to achieve 'good enough' results in lower-end hardware while tuning multiple hyperparameters. With the n_iter parameter, we limit the number of iterations to 50." }, { "code": null, "e": 8560, "s": 8380, "text": "We will also use StratifiedKFold to perform cross-validation. Unlike the regular KFold, it preserves the sample's distribution across folds, potentially leading to better results." }, { "code": null, "e": 9018, "s": 8560, "text": "The final step is to build a param_grid dictionary with the hyperparameters that we need to tune. The full code can be seen below. Notice how we pass the full_pipeline object as the RandomizedSearchCV estimator and then we call the fit method on the resulting object as we would any other sklearn model. This way, when we want to ty other models, all we have to do is change the model on the pipeline and create a new parameter grid to pass, simple as that!" }, { "code": null, "e": 9810, "s": 9018, "text": "# Create the grid search parameter grid and scoring funcitonsparam_grid = { \"model\": [DecisionTreeClassifier(random_state=seed)], \"model__criterion\": [\"gini\",\"entropy\"], \"model__splitter\": [\"best\",\"random\"], \"model__max_leaf_nodes\": [16, 64, 128, 256], \"model__max_depth\": np.linspace(1, 32, 32)}scoring = { 'AUC': 'roc_auc', 'Accuracy': make_scorer(accuracy_score)}# create the Kfold objectnum_folds = 10kfold = StratifiedKFold(n_splits=num_folds, random_state=seed)# create the grid search object with the full pipeline as estimatorn_iter=50grid = RandomizedSearchCV( estimator=full_pipeline, param_distributions=param_grid, cv=kfold, scoring=scoring, n_jobs=-1, n_iter=n_iter, refit=\"AUC\")# fit grid searchbest_model = grid.fit(X_train,y_train)" }, { "code": null, "e": 9882, "s": 9810, "text": "For the DecisionTreeClassifier we are tunning the following parameters:" }, { "code": null, "e": 9970, "s": 9882, "text": "criterion: defines the function to measure the quality of the splits on the tree nodes;" }, { "code": null, "e": 10045, "s": 9970, "text": "splitter: defines the strategy used to choose the split at each tree node;" }, { "code": null, "e": 10114, "s": 10045, "text": "max_leaf_nodes: limits the maximum number of leaf nodes in the tree;" }, { "code": null, "e": 10174, "s": 10114, "text": "max_depth: limits the maximum depth that the tree can grow;" }, { "code": null, "e": 10314, "s": 10174, "text": "After the randomized search finishes and the best model is fitted to our data, we can make predictions and measure the model's performance:" }, { "code": null, "e": 10690, "s": 10314, "text": "# final Decision Tree modelpred_test = best_model.predict(X_test)pred_train = best_model.predict(X_train)print('Train Accuracy: ', accuracy_score(y_train, pred_train))print('Test Accuraccy: ', accuracy_score(y_test, pred_test))print('\\nConfusion Matrix:')print(confusion_matrix(y_test,pred_test))print('\\nClassification Report:')print(classification_report(y_test,pred_test))" }, { "code": null, "e": 11046, "s": 10690, "text": "Ensemble methods are models that combine several base models in order to produce one optimal predictive model. The RandomForestClassifier is a classical example of this, as it combines several simpler DecisionTrees to generate the output. With this, is possible to overcome several limitations of the decision tree model, such as it's tendency to overfit." }, { "code": null, "e": 11571, "s": 11046, "text": "The first ensemble method that we are going to work with is the BaggingClassifier. The name bagging comes from bootstrap aggregating and it works by splitting the data into several random subsamples that are then used to train each individual base estimator. This strategy can be performed in one of two ways: with replacement, meaning that the samples can be used several times for the same estimator; and without replacement, meaning that each individual sample can be used only one time (this approach is called Pasting)." }, { "code": null, "e": 11952, "s": 11571, "text": "Bagging generally yields better results than Pasting and it also has a neat trick up its sleeve: Out-of-Bag evaluation. Since the samples are drawn with replacement and the same sample can be used multiple times randomly, some samples on the training set may never be used to train any of the base estimators! This means that we can use these samples for further model evaluation!" }, { "code": null, "e": 12291, "s": 11952, "text": "So, with all that in mind, we are going to update our previous pipeline to work with the BaggingClassifier with a DecisionTree as the base estimator. To do that, all we have to do is change the ‘model’ step in the pipeline definition and redefine the RandomizedSearchCV parameter search space, as it can be seen in the code snippet below:" }, { "code": null, "e": 13630, "s": 12291, "text": "# we pass the preprocessing pipeline as a step to the full pipelinefull_pipeline_steps = [ ('preprocessing_pipeline', preprocessing_pipeline), ('model', BaggingClassifier( DecisionTreeClassifier(max_features=\"auto\", splitter=\"random\", max_leaf_nodes=128, random_state=seed), random_state=seed ))]# create the full pipeline objectfull_pipeline = Pipeline(steps=full_pipeline_steps)# Create the grid search parameter gridparam_grid = { \"model\": [BaggingClassifier( DecisionTreeClassifier(max_features=\"auto\", splitter=\"random\", max_leaf_nodes=128, random_state=seed), random_state=seed )], \"model__n_estimators\": np.arange(100, 1000, 100), \"model__max_samples\":[0.8, 1.0], \"model__max_features\": [0.8, 1.0], \"model__bootstrap\": [True], \"model__oob_score\": [True],}scoring = { 'AUC': 'roc_auc', 'Accuracy': make_scorer(accuracy_score)}# create the Kfold objectnum_folds = 10kfold = StratifiedKFold(n_splits=num_folds, random_state=seed)# create the grid search object with the full pipeline as estimatorn_iter=25grid = RandomizedSearchCV( estimator=full_pipeline, param_distributions=param_grid, cv=kfold, scoring=scoring, n_jobs=-1, n_iter=n_iter, refit=\"AUC\") # fit grid searchbest_bag = grid.fit(X_train,y_train)" }, { "code": null, "e": 13697, "s": 13630, "text": "For the BaggingClassifier we are tunning the following parameters:" }, { "code": null, "e": 13788, "s": 13697, "text": "n_estimators: defines the total number of estimators (in this case decision trees) to use;" }, { "code": null, "e": 13880, "s": 13788, "text": "max_samples: The maximum percentage of samples to draw from X to train each base estimator;" }, { "code": null, "e": 13974, "s": 13880, "text": "max_features: The maximum percentage of features to draw from X to train each base estimator;" }, { "code": null, "e": 14194, "s": 13974, "text": "bootstrap: When set to False, draw samples without replacement (Pasting). When set to True, draw samples with replacement (bagging). Since we are going to use the out-of-bag score, we have to set this parameter to True;" }, { "code": null, "e": 14270, "s": 14194, "text": "oob_score: When set to True, return the out-of-bag score of the best model;" }, { "code": null, "e": 14450, "s": 14270, "text": "After the randomized search finishes and the best model is fitted to our data, we can check the tunned model hyperparameters, make predictions and measure the model’s performance:" }, { "code": null, "e": 14540, "s": 14450, "text": "print(f'Best score: {best_bag.best_score_}')print(f'Best model: {best_bag.best_params_}')" }, { "code": null, "e": 14958, "s": 14540, "text": "pred_test = best_bag.predict(X_test)pred_train = best_bag.predict(X_train)print('Train Accuracy: ', accuracy_score(y_train, pred_train))print('Test Accuraccy: ', accuracy_score(y_test, pred_test))print(\"Out-of-Bag Accuracy: \", best_bag.best_params_['model'].oob_score_)print('\\nConfusion Matrix:')print(confusion_matrix(y_test,pred_test))print('\\nClassification Report:')print(classification_report(y_test,pred_test))" }, { "code": null, "e": 15130, "s": 14958, "text": "As we can see, all 3 accuracies achieved by the model are very close to each other, indicating that the model generalized well for new data and thus may not be overfitted." }, { "code": null, "e": 15300, "s": 15130, "text": "The last model we will be training is the RandomForestClassifier. The process to use it is the same as the one presented above and can be seen in the code snippet below:" }, { "code": null, "e": 16419, "s": 15300, "text": "# we pass the preprocessing pipeline as a step to the full pipelinefull_pipeline_steps = [ ('preprocessing_pipeline', preprocessing_pipeline), ('model', RandomForestClassifier(random_state=seed))]# create the full pipeline objectfull_pipeline = Pipeline(steps=full_pipeline_steps)# Create the grid search parameter grid and scoring funcitonsparam_grid = { \"model\": [RandomForestClassifier(random_state=seed)], \"model__max_depth\": np.linspace(1, 32, 32), \"model__n_estimators\": np.arange(100, 1000, 100), \"model__criterion\": [\"gini\",\"entropy\"], \"model__max_leaf_nodes\": [16, 64, 128, 256], \"model__oob_score\": [True],}scoring = { 'AUC': 'roc_auc', 'Accuracy': make_scorer(accuracy_score)}# create the Kfold objectnum_folds = 10kfold = StratifiedKFold(n_splits=num_folds, random_state=seed)# create the grid search object with the full pipeline as estimatorn_iter=50grid = RandomizedSearchCV( estimator=full_pipeline, param_distributions=param_grid, cv=kfold, scoring=scoring, n_jobs=-1, n_iter=n_iter, refit=\"AUC\")# fit grid searchbest_rf = grid.fit(X_train,y_train)" }, { "code": null, "e": 16491, "s": 16419, "text": "For the RandomForestClassifier we are tunning the following parameters:" }, { "code": null, "e": 16579, "s": 16491, "text": "criterion: defines the function to measure the quality of the splits on the tree nodes;" }, { "code": null, "e": 16649, "s": 16579, "text": "max_leaf_nodes: limits the maximum number of leaf nodes in the trees;" }, { "code": null, "e": 16710, "s": 16649, "text": "max_depth: limits the maximum depth that the trees can grow;" }, { "code": null, "e": 16779, "s": 16710, "text": "n_estimators: defines the total number of trees to use in the forest" }, { "code": null, "e": 16855, "s": 16779, "text": "oob_score: When set to True, return the out-of-bag score of the best model;" }, { "code": null, "e": 17013, "s": 16855, "text": "As we did before, after the randomized search finishes and the best model is fitted to our data, we can make predictions and measure the model’s performance:" }, { "code": null, "e": 17101, "s": 17013, "text": "print(f'Best score: {best_rf.best_score_}')print(f'Best model: {best_rf.best_params_}')" }, { "code": null, "e": 17516, "s": 17101, "text": "pred_test = best_rf.predict(X_test)pred_train = best_rf.predict(X_train)print('Train Accuracy: ', accuracy_score(y_train, pred_train))print('Test Accuraccy: ', accuracy_score(y_test, pred_test))print(\"Out-of-Bag Accuracy: \", best_rf.best_params_['model'].oob_score_)print('\\nConfusion Matrix:')print(confusion_matrix(y_test,pred_test))print('\\nClassification Report:')print(classification_report(y_test,pred_test))" }, { "code": null, "e": 17779, "s": 17516, "text": "Similar to the BaggingClassifier, the accuracies are very close to each other, indicating good generalization for unseen data and thus, no overfitting. As this was the best performing model we have found, we will use it as an example for the rest of the article." }, { "code": null, "e": 18071, "s": 17779, "text": "In some cases, getting good predictions from your model is arguably as important as to understand why it is giving the answers that it does. In those cases is where we can leverage the concepts of eXplainable Artificial Intelligence (XAI) and try to make the models more human interpretable." }, { "code": null, "e": 18367, "s": 18071, "text": "One way to do this is by analyzing the importance of each feature in the model outcome. Luckily for us, the random forest has a built-in attribute that can tell us just that, its called feature_importances_. The steps performed to access and plot this information is presented in the code below:" }, { "code": null, "e": 19126, "s": 18367, "text": "# lets get the random forest model configuration and feature namesrf_model = best_rf.best_params_['model']features = np.array(X_train.columns)# Transforming the test data.new_X_test = preprocessing_pipeline.fit_transform(X_test)new_X_test = pd.DataFrame(new_X_test, columns=X_test.columns)# get the predicitons from the random forest objecty_pred = rf_model.predict(new_X_test)# get the feature importancesimportances = rf_model.feature_importances_# sort the indexessorted_index = np.argsort(importances)sorted_importances = importances[sorted_index]sorted_features = features[sorted_index]# plot the explained variance using a barplotfig, ax = plt.subplots()ax.barh(sorted_features , sorted_importances)ax.set_xlabel('Importances')ax.set_ylabel('Features')" }, { "code": null, "e": 19376, "s": 19126, "text": "This is an example of a simple, and yet effective, way to gain more insight both on your data and on your model's reasoning. With the plot, we can see that the most important features were education_num, capital_loss, fnlwgt, capital_gain, and race." }, { "code": null, "e": 19509, "s": 19376, "text": "To go even further, we will briefly explore two third party libraries that enable us to get different visualizations: ELI5 and SHAP." }, { "code": null, "e": 19707, "s": 19509, "text": "ELI5 is a Python package that helps to debug machine learning classifiers and explain their predictions. It provides support for some machine learning libraries, including scikit-learn and XGBoost." }, { "code": null, "e": 20033, "s": 19707, "text": "With it, we are able to look at a classification model in two main ways: the first is to inspect the model parameters and analyze how the model works globally (similarly to the default feature importance attribute); the second is to inspect individual predictions to figure out why the model makes the decisions that it does." }, { "code": null, "e": 20127, "s": 20033, "text": "For the first use case we use the show_weights() function as shown in the code snippet below:" }, { "code": null, "e": 20332, "s": 20127, "text": "import eli5# lets get the random forest model configuration and feature namesrf_model = best_rf.best_params_['model']features = np.array(X_train.columns)eli5.show_weights(rf_model, feature_names=features)" }, { "code": null, "e": 20455, "s": 20332, "text": "As we can see in the image above, the results are pretty similar to the one we obtained from the tree feature importances." }, { "code": null, "e": 20788, "s": 20455, "text": "As for the second use case, we can use the explain_prediction() function to inspect and analyze individual predictions of the model. To test this out, we checked a true negative prediction (actual value was 0 and the predicted value was also 0) and a true positive prediction (actual value was 1 and the predicted value was also 1):" }, { "code": null, "e": 21257, "s": 20788, "text": "# predicting a person earns less than 50k/year (true negative)index = 4print('Actual Label:', y_test.iloc[index])print('Predicted Label:', y_pred[index])eli5.explain_prediction(rf_model, new_X_test.iloc[index], feature_names=features)# predicting a person earns more than 50k/year (true positive)index = 7print('Actual Label:', y_test.iloc[index])print('Predicted Label:', y_pred[index])eli5.explain_prediction(rf_model, new_X_test.iloc[index], feature_names=features)" }, { "code": null, "e": 21410, "s": 21257, "text": "So, the most influential features that contributed for the model to predict that these particular observations were respectively race and education_num." }, { "code": null, "e": 21653, "s": 21410, "text": "The SHAP (SHapley Additive exPlanations) library is a unified approach to explain the output of any machine learning model. Similarly to the ELI5, it also has support for several machine learning libraries, including scikit-learn and XGBoost." }, { "code": null, "e": 21846, "s": 21653, "text": "To use its functionality for our Random Forest model we first need to create a TreeExplainer object and obtain the so-called shap_values for the model. This process is shown in the code below:" }, { "code": null, "e": 22077, "s": 21846, "text": "import shapshap.initjs()# Create the explainer objectexplainer = shap.TreeExplainer(rf_model)print('Expected Value:', explainer.expected_value)# get the shap values from the explainershap_values = explainer.shap_values(new_X_test)" }, { "code": null, "e": 22248, "s": 22077, "text": "As we did with the ELI5, we can also use the SHAP library to explain individual model predictions, as shown below for the same data points that we worked with previously:" }, { "code": null, "e": 22561, "s": 22248, "text": "# predicting a person earns less than 50k/year (true negative)shap.force_plot(explainer.expected_value[0], shap_values[0][4], X_test.iloc[4])# predicting a person earns more than 50k/year (true positive)shap.force_plot(explainer.expected_value[1], shap_values[1][7], X_test.iloc[7])" }, { "code": null, "e": 22701, "s": 22561, "text": "In addition, it is also possible to visualize multiple predictions at once, as it is shown below for the first 1000 samples of the dataset:" }, { "code": null, "e": 22808, "s": 22701, "text": "shap.force_plot(explainer.expected_value[0], shap_values[0][:1000,:], X_test.iloc[:1000,:])" }, { "code": null, "e": 23031, "s": 22808, "text": "In the same plot, it is also possible to analyze the impact of different features in the final model prediction. To test this, we configured the plot to show the importance of the education_num feature on the same samples:" }, { "code": null, "e": 23127, "s": 23031, "text": "Finally, we can use the summary_plot function to plot the feature importances divided by class:" }, { "code": null, "e": 23166, "s": 23127, "text": "shap.summary_plot(shap_values, X_test)" }, { "code": null, "e": 23307, "s": 23166, "text": "We can see that the obtained result is very similar to the ones obtained both by the tree built-in feature importances and the ELI5 library." }, { "code": null, "e": 23519, "s": 23307, "text": "We barely scratched the surface of several important topics in the machine learning landscape, such as Pipelines, hyperparameter tuning, ensemble methods, and model interpretability. There is much more to cover!" } ]
Customers Subscription Analysis and Prediction Based on App Behavior Analysis (Logistic Regression) | by Shekhar Koirala | Towards Data Science
We will do the customers churn analysis based on the customers behavior on the website or app. We will classify what kind of customers are likely to sign up for the paid subscription of a website. After analyzing and classifying the dataset, we will be able to do the targeting based marketing or recommendation to the customers who are likely to sign up for the paid subscription plan. For this problem we will use Logistic Regression algorithm from scikit-learn library. The dataset for this problem has been optimized with necessary feature engineering that has already been done. If you wanna find out how I cleaned the data and how the feature engineering was done, please stay tuned as i will be writing another post soon about the data cleaning process on this particular dataset. Let’s start the process by first importing the necessary libraries and the dataset. import numpy as np import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom dateutil import parser %matplotlib qt5 Here %matplotlib qt5 makes the visualization pop up in a new window. If you want the visualization to appear in the same notebook or console, then you can use %matplotlib inline dataset = pd.read_csv(“appdata10.csv”) Let’s look at the dataset: Now let’s separate the dataset into the features and the target variables. The target column name is “enrolled”. X = dataset.drop(columns = 'enrolled')y = dataset['enrolled'] Now let’s split the dataset into training set and testing set. We need to do this so that we can only use the training set data in our model training. Splitting the dataset into training set and testing set is important in supervised machine learning as it prevents overfitting. To do this I will use train_test_split() function from sklearn. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 4) You can use any random state, it just ensures that results in different environment are same. Let’s remove the user column for now because we don’t need it and its not a required feature. But we need it for the purpose of identifying the user that subscribed or not. For this we are going to save the user column as identifier. train_identifier = X_train['user']X_train = X_train.drop(columns='user')test_identifier = X_test['user']X_test = X_test.drop(columns='user') The next step is to do feature scaling. Feature scaling is done to normalize the values of different features in the dataset. Feature scaling helps us to achieve the gradient decent more quickly. If the data is more spread out, that means if it has a higher standard deviation, it will relatively take more time to calculate the gradient decent compared to the situation when we scale our data via feature scaling. So we are making all the values within a certain range. This treats all the columns equally. In the above dataset, we can see that the values of age, days of week, enrolled are not in similar range. To do this we can use sklearn’s StandardScaler function. from sklearn.preprocessing import StandardScalersc_X = StandardScaler()X_train2 = pd.DataFrame(sc_X.fit_transform(X_train))X_test2 = pd.DataFrame(sc_X.fit_transform(X_test))X_train2.columns = X_train.columns.valuesX_test2.columns = X_test.columns.valuesX_train.index = X_train.index.valuesX_test.index = X_test.index.valuesX_train = X_train2X_test = X_test2 Now let’s get into the exciting part; training the dataset. For this we will use LogisticRegression from sklearn library. Logistic Regression is used for classification problem. It is the appropriate regression analysis to conduct when the dependent variable is dichotomous (binary). Like all regression analyses, the logistic regression is a predictive analysis. Logistic regression is used to describe data and to explain the relationship between one dependent binary variable and one or more nominal, ordinal, interval or ratio-level independent variables. from sklearn.linear_model import LogisticRegression logreg = LogisticRegression(random_state=0, penalty=’l1')logreg.fit(X_train, y_train) Here I am using penalty parameter to prevent one feature being very highly correlated to the target variable in this particular dataset, especially for the last screen variable. Now that the model has been trained, we can do the prediction on the test set. y_pred = logreg.predict(X_test) After doing the prediction, we can do the model evaluation to see how our model performed. For this we will use five evaluation metrics, confusion matrix, accuracy score, f1 score, precision score and recall score. All these evaluation metrices are available in scikit learn. from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_scorecm = confusion_matrix(y_test, y_pred)accuracy = accuracy_score(y_test, y_pred)accuracy 0.7679 So we achieved the accuracy of 79%. The model has done a descent job with that accuracy. Now let’s plot the heat map of the confusion matrix to visualize the confusion matrix. We can see that the correctly predicted values are around 3 times more than the false positive and false negative in the confusion matrix. We can further use cross validation to evaluate the model and make sure our model is doing the right job. from sklearn.model_selection import cross_val_scoreaccuracies = cross_val_score(estimator=logreg, X=X_train, y= y_train, cv=10)print("Logistic accuracy: %0.3f (+/- %0.3f)(accuracies.mean(),accuracies.std()*2))Output: Logistic accuracy: 0.767 (+/- 0.010) So we can say that our model is doing the right job and a descent job with LogisticRegression. We can further optimize our model using different parameter tuning methods. But for now I am not going to optimize this model. If you want to learn about parameter/hyper parameter tuning, you can search GridSearch, Randomized search, Backward elimination. I’ll leave those for next post. This is my first medium post, so please feel free to give me suggestions and constructive criticism on this post and also about the method Iused to do this classification. Thank you.
[ { "code": null, "e": 558, "s": 171, "text": "We will do the customers churn analysis based on the customers behavior on the website or app. We will classify what kind of customers are likely to sign up for the paid subscription of a website. After analyzing and classifying the dataset, we will be able to do the targeting based marketing or recommendation to the customers who are likely to sign up for the paid subscription plan." }, { "code": null, "e": 959, "s": 558, "text": "For this problem we will use Logistic Regression algorithm from scikit-learn library. The dataset for this problem has been optimized with necessary feature engineering that has already been done. If you wanna find out how I cleaned the data and how the feature engineering was done, please stay tuned as i will be writing another post soon about the data cleaning process on this particular dataset." }, { "code": null, "e": 1043, "s": 959, "text": "Let’s start the process by first importing the necessary libraries and the dataset." }, { "code": null, "e": 1178, "s": 1043, "text": "import numpy as np import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom dateutil import parser %matplotlib qt5 " }, { "code": null, "e": 1356, "s": 1178, "text": "Here %matplotlib qt5 makes the visualization pop up in a new window. If you want the visualization to appear in the same notebook or console, then you can use %matplotlib inline" }, { "code": null, "e": 1396, "s": 1356, "text": "dataset = pd.read_csv(“appdata10.csv”) " }, { "code": null, "e": 1423, "s": 1396, "text": "Let’s look at the dataset:" }, { "code": null, "e": 1536, "s": 1423, "text": "Now let’s separate the dataset into the features and the target variables. The target column name is “enrolled”." }, { "code": null, "e": 1599, "s": 1536, "text": "X = dataset.drop(columns = 'enrolled')y = dataset['enrolled'] " }, { "code": null, "e": 1878, "s": 1599, "text": "Now let’s split the dataset into training set and testing set. We need to do this so that we can only use the training set data in our model training. Splitting the dataset into training set and testing set is important in supervised machine learning as it prevents overfitting." }, { "code": null, "e": 1942, "s": 1878, "text": "To do this I will use train_test_split() function from sklearn." }, { "code": null, "e": 2088, "s": 1942, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 4) " }, { "code": null, "e": 2182, "s": 2088, "text": "You can use any random state, it just ensures that results in different environment are same." }, { "code": null, "e": 2416, "s": 2182, "text": "Let’s remove the user column for now because we don’t need it and its not a required feature. But we need it for the purpose of identifying the user that subscribed or not. For this we are going to save the user column as identifier." }, { "code": null, "e": 2557, "s": 2416, "text": "train_identifier = X_train['user']X_train = X_train.drop(columns='user')test_identifier = X_test['user']X_test = X_test.drop(columns='user')" }, { "code": null, "e": 3171, "s": 2557, "text": "The next step is to do feature scaling. Feature scaling is done to normalize the values of different features in the dataset. Feature scaling helps us to achieve the gradient decent more quickly. If the data is more spread out, that means if it has a higher standard deviation, it will relatively take more time to calculate the gradient decent compared to the situation when we scale our data via feature scaling. So we are making all the values within a certain range. This treats all the columns equally. In the above dataset, we can see that the values of age, days of week, enrolled are not in similar range." }, { "code": null, "e": 3228, "s": 3171, "text": "To do this we can use sklearn’s StandardScaler function." }, { "code": null, "e": 3586, "s": 3228, "text": "from sklearn.preprocessing import StandardScalersc_X = StandardScaler()X_train2 = pd.DataFrame(sc_X.fit_transform(X_train))X_test2 = pd.DataFrame(sc_X.fit_transform(X_test))X_train2.columns = X_train.columns.valuesX_test2.columns = X_test.columns.valuesX_train.index = X_train.index.valuesX_test.index = X_test.index.valuesX_train = X_train2X_test = X_test2" }, { "code": null, "e": 3708, "s": 3586, "text": "Now let’s get into the exciting part; training the dataset. For this we will use LogisticRegression from sklearn library." }, { "code": null, "e": 4146, "s": 3708, "text": "Logistic Regression is used for classification problem. It is the appropriate regression analysis to conduct when the dependent variable is dichotomous (binary). Like all regression analyses, the logistic regression is a predictive analysis. Logistic regression is used to describe data and to explain the relationship between one dependent binary variable and one or more nominal, ordinal, interval or ratio-level independent variables." }, { "code": null, "e": 4284, "s": 4146, "text": "from sklearn.linear_model import LogisticRegression logreg = LogisticRegression(random_state=0, penalty=’l1')logreg.fit(X_train, y_train)" }, { "code": null, "e": 4462, "s": 4284, "text": "Here I am using penalty parameter to prevent one feature being very highly correlated to the target variable in this particular dataset, especially for the last screen variable." }, { "code": null, "e": 4541, "s": 4462, "text": "Now that the model has been trained, we can do the prediction on the test set." }, { "code": null, "e": 4573, "s": 4541, "text": "y_pred = logreg.predict(X_test)" }, { "code": null, "e": 4849, "s": 4573, "text": "After doing the prediction, we can do the model evaluation to see how our model performed. For this we will use five evaluation metrics, confusion matrix, accuracy score, f1 score, precision score and recall score. All these evaluation metrices are available in scikit learn." }, { "code": null, "e": 5044, "s": 4849, "text": "from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_scorecm = confusion_matrix(y_test, y_pred)accuracy = accuracy_score(y_test, y_pred)accuracy 0.7679" }, { "code": null, "e": 5133, "s": 5044, "text": "So we achieved the accuracy of 79%. The model has done a descent job with that accuracy." }, { "code": null, "e": 5220, "s": 5133, "text": "Now let’s plot the heat map of the confusion matrix to visualize the confusion matrix." }, { "code": null, "e": 5465, "s": 5220, "text": "We can see that the correctly predicted values are around 3 times more than the false positive and false negative in the confusion matrix. We can further use cross validation to evaluate the model and make sure our model is doing the right job." }, { "code": null, "e": 5719, "s": 5465, "text": "from sklearn.model_selection import cross_val_scoreaccuracies = cross_val_score(estimator=logreg, X=X_train, y= y_train, cv=10)print(\"Logistic accuracy: %0.3f (+/- %0.3f)(accuracies.mean(),accuracies.std()*2))Output: Logistic accuracy: 0.767 (+/- 0.010)" }, { "code": null, "e": 5814, "s": 5719, "text": "So we can say that our model is doing the right job and a descent job with LogisticRegression." }, { "code": null, "e": 6102, "s": 5814, "text": "We can further optimize our model using different parameter tuning methods. But for now I am not going to optimize this model. If you want to learn about parameter/hyper parameter tuning, you can search GridSearch, Randomized search, Backward elimination. I’ll leave those for next post." } ]
Array algorithms in C++ STL
Since C++11 there are different functions added into the STL. These functions are present at algorithm header file. Here we will see some functions of this. The all_of() function is used to check one condition, that is true for all elements of a container. Let us see the code to get the idea The all_of() function is used to check one condition, that is true for all elements of a container. Let us see the code to get the idea #include <iostream> #include <algorithm> using namespace std; main() { int arr[] = {2, 4, 6, 8, 10}; int n = sizeof(arr)/sizeof(arr[0]); if(all_of(arr, arr + n, [](int x){return x%2 == 0;})) { cout << "All are even"; } else { cout << "All are not even"; } } All are even The any_of() function is used to check one condition, that is true for at least one element of a container. Let us see the code to get the idea. The any_of() function is used to check one condition, that is true for at least one element of a container. Let us see the code to get the idea. #include <iostream> #include <algorithm> using namespace std; main() { int arr[] = {2, 4, 6, 8, 10, 5, 62}; int n = sizeof(arr)/sizeof(arr[0]); if(any_of(arr, arr + n, [](int x){return x%2 == 1;})) { cout << "At least one element is odd"; } else { cout << "No odd elements are found"; } } At least one element is odd The none_of() function is used to check whether no element of a container is satisfies the given condition. Let us see the code to get the idea. The none_of() function is used to check whether no element of a container is satisfies the given condition. Let us see the code to get the idea. #include <iostream> #include <algorithm> using namespace std; main() { int arr[] = {2, 4, 6, 8, 10, 5, 62}; int n = sizeof(arr)/sizeof(arr[0]); if(none_of(arr, arr + n, [](int x){return x < 0 == 1;})) { cout << "All elements are positive"; } else { cout << "Some elements are negative"; } } All elements are positive The copy_n() function is used to copy elements of one array into another array. Let us see the code to get better idea. The copy_n() function is used to copy elements of one array into another array. Let us see the code to get better idea. #include <iostream> #include <algorithm> using namespace std; main() { int arr[] = {2, 4, 6, 8, 10, 5, 62}; int n = sizeof(arr)/sizeof(arr[0]); int arr2[n]; copy_n(arr, n, arr2); for(int i = 0; i < n; i++) { cout << arr2[i] << " "; } } 2 4 6 8 10 5 62 The itoa() function is used assign continuous values into array. This function is present under numeric header file. It takes three arguments. The array name, size and the starting value. The itoa() function is used assign continuous values into array. This function is present under numeric header file. It takes three arguments. The array name, size and the starting value. #include <iostream> #include <numeric> using namespace std; main() { int n = 10; int arr[n]; iota(arr, arr+n, 10); for(int i = 0; i < n; i++) { cout << arr[i] << " "; } } 10 11 12 13 14 15 16 17 18 19
[ { "code": null, "e": 1219, "s": 1062, "text": "Since C++11 there are different functions added into the STL. These functions are present at algorithm header file. Here we will see some functions of this." }, { "code": null, "e": 1355, "s": 1219, "text": "The all_of() function is used to check one condition, that is true for all elements of a container. Let us see the code to get the idea" }, { "code": null, "e": 1491, "s": 1355, "text": "The all_of() function is used to check one condition, that is true for all elements of a container. Let us see the code to get the idea" }, { "code": null, "e": 1776, "s": 1491, "text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nmain() {\n int arr[] = {2, 4, 6, 8, 10};\n int n = sizeof(arr)/sizeof(arr[0]);\n if(all_of(arr, arr + n, [](int x){return x%2 == 0;})) {\n cout << \"All are even\";\n } else {\n cout << \"All are not even\";\n }\n}" }, { "code": null, "e": 1789, "s": 1776, "text": "All are even" }, { "code": null, "e": 1934, "s": 1789, "text": "The any_of() function is used to check one condition, that is true for at least one element of a container. Let us see the code to get the idea." }, { "code": null, "e": 2079, "s": 1934, "text": "The any_of() function is used to check one condition, that is true for at least one element of a container. Let us see the code to get the idea." }, { "code": null, "e": 2395, "s": 2079, "text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nmain() {\n int arr[] = {2, 4, 6, 8, 10, 5, 62};\n int n = sizeof(arr)/sizeof(arr[0]);\n if(any_of(arr, arr + n, [](int x){return x%2 == 1;})) {\n cout << \"At least one element is odd\";\n } else {\n cout << \"No odd elements are found\";\n }\n}" }, { "code": null, "e": 2423, "s": 2395, "text": "At least one element is odd" }, { "code": null, "e": 2568, "s": 2423, "text": "The none_of() function is used to check whether no element of a container is satisfies the given condition. Let us see the code to get the idea." }, { "code": null, "e": 2713, "s": 2568, "text": "The none_of() function is used to check whether no element of a container is satisfies the given condition. Let us see the code to get the idea." }, { "code": null, "e": 3031, "s": 2713, "text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nmain() {\n int arr[] = {2, 4, 6, 8, 10, 5, 62};\n int n = sizeof(arr)/sizeof(arr[0]);\n if(none_of(arr, arr + n, [](int x){return x < 0 == 1;})) {\n cout << \"All elements are positive\";\n } else {\n cout << \"Some elements are negative\";\n }\n}" }, { "code": null, "e": 3057, "s": 3031, "text": "All elements are positive" }, { "code": null, "e": 3177, "s": 3057, "text": "The copy_n() function is used to copy elements of one array into another array. Let us see the code to get better idea." }, { "code": null, "e": 3297, "s": 3177, "text": "The copy_n() function is used to copy elements of one array into another array. Let us see the code to get better idea." }, { "code": null, "e": 3557, "s": 3297, "text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nmain() {\n int arr[] = {2, 4, 6, 8, 10, 5, 62};\n int n = sizeof(arr)/sizeof(arr[0]);\n int arr2[n];\n copy_n(arr, n, arr2);\n for(int i = 0; i < n; i++) {\n cout << arr2[i] << \" \";\n }\n}" }, { "code": null, "e": 3573, "s": 3557, "text": "2 4 6 8 10 5 62" }, { "code": null, "e": 3761, "s": 3573, "text": "The itoa() function is used assign continuous values into array. This function is present under numeric header file. It takes three arguments. The array name, size and the starting value." }, { "code": null, "e": 3949, "s": 3761, "text": "The itoa() function is used assign continuous values into array. This function is present under numeric header file. It takes three arguments. The array name, size and the starting value." }, { "code": null, "e": 4141, "s": 3949, "text": "#include <iostream>\n#include <numeric>\nusing namespace std;\nmain() {\n int n = 10;\n int arr[n];\n iota(arr, arr+n, 10);\n for(int i = 0; i < n; i++) {\n cout << arr[i] << \" \";\n }\n}" }, { "code": null, "e": 4171, "s": 4141, "text": "10 11 12 13 14 15 16 17 18 19" } ]
Sort vector of Numeric Strings in ascending order - GeeksforGeeks
21 Mar, 2022 Given a vector of numeric strings arr[], the task is to sort the given vector of numeric strings in ascending order. Examples: Input: arr[] = {“120000”, “2”, “33”}Output: {“2”, “33”, “120000”} Input: arr[] = {“120”, “2”, “3”}Output: {“2”, “3”, “120”} Approach: The sort() function in C++ STL is able to sort vector of strings if and only if it contains single numeric character for example, { ‘1’, ‘ ‘} but to sort numeric vector of string with multiple character for example, {’12’, ’56’, ’14’ } one should write own comparator inside sort() function. The comparator function to sort in ascending order logic goes as: Let’s build a comparator function considering the two cases given below: Case 1: If the length of the string is not the same then place a smaller length string in first place for example, {’12’, ‘2’} place ‘2’ before ’12’ as ‘2’ is smaller than ’12’. Case 2: If length is the same then place the string which is numerically smaller for example, ‘1’, ‘2’ place ‘1’ before ‘2’. Below is the C++ program to implement the above approach: C++ Java Python3 Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Comparator Functionbool myCmp(string s1, string s2){ // If size of numeric strings // are same the put lowest value // first if (s1.size() == s2.size()) { return s1 < s2; } // If size is not same put the // numeric string with less // number of digits first else { return s1.size() < s2.size(); }} // Driver Codeint main(){ vector<string> v = { "12", "2", "10", "6", "4", "99", "12" }; // Calling sort function with // custom comparator sort(v.begin(), v.end(), myCmp); // Print the vector values after // sorting for (auto it : v) { cout << it << " "; } cout << "\n";} // Java program for the above approachimport java.util.*;class GFG{ // Comparator Functionstatic List<String> sort(List<String> list){ Comparator<String> cmp = (o1, o2) -> { // If size of numeric Strings // are same the put lowest value // first if (o1.length() == o2.length()) { return Integer.valueOf(o1)-Integer.valueOf(o2); } // If size is not same put the // numeric String with less // number of digits first else { return o1.length()-o2.length(); } }; Collections.sort(list, cmp); return list;} // Driver Codepublic static void main(String[] args){ List<String> v = Arrays.asList( "12", "2", "10", "6", "4", "99", "12" ); // Calling sort function with // custom comparator v = sort(v); // Print the vector values after // sorting for (String it : v) { System.out.print(it+ " "); } }} // This code is contributed by 29AjayKumar # Python3 Program to implement# the above approach # Comparator Functionfrom functools import cmp_to_key def myCmp(s1, s2): # If size of numeric strings # are same the put lowest value # first if (len(s1) == len(s2)): return int(s1) - int(s2) # If size is not same put the # numeric string with less # number of digits first else: return len(s1) - len(s2) # Driver Codev = ["12", "2", "10", "6", "4", "99", "12"] # Calling sort function with# custom comparatorv.sort(key = cmp_to_key(myCmp)) # Print the vector values after# sortingfor i in range(len(v)) : print(v[i],end=" ") # This code is contributed by shinjanpatra <script> // JavaScript Program to implement // the above approach // Comparator Function function myCmp(s1, s2) { // If size of numeric strings // are same the put lowest value // first if (s1.length == s2.length) { return parseInt(s1) - parseInt(s2); } // If size is not same put the // numeric string with less // number of digits first else { return s1.length - s2.length; } } // Driver Code let v = ["12", "2", "10", "6", "4", "99", "12"]; // Calling sort function with // custom comparator v.sort(myCmp) // Print the vector values after // sorting for (let i = 0; i < v.length; i++) { document.write(v[i] + " ") } // This code is contributed by Potta Lokesh </script> 2 4 6 10 12 12 99 Time Complexity: O(N*log N)Auxiliary Space: O(1) lokeshpotta20 29AjayKumar shinjanpatra Arrays Sorting Strings Arrays Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Trapping Rain Water Move all negative numbers to beginning and positive to end with constant extra space
[ { "code": null, "e": 24822, "s": 24794, "text": "\n21 Mar, 2022" }, { "code": null, "e": 24939, "s": 24822, "text": "Given a vector of numeric strings arr[], the task is to sort the given vector of numeric strings in ascending order." }, { "code": null, "e": 24949, "s": 24939, "text": "Examples:" }, { "code": null, "e": 25015, "s": 24949, "text": "Input: arr[] = {“120000”, “2”, “33”}Output: {“2”, “33”, “120000”}" }, { "code": null, "e": 25073, "s": 25015, "text": "Input: arr[] = {“120”, “2”, “3”}Output: {“2”, “3”, “120”}" }, { "code": null, "e": 25443, "s": 25073, "text": "Approach: The sort() function in C++ STL is able to sort vector of strings if and only if it contains single numeric character for example, { ‘1’, ‘ ‘} but to sort numeric vector of string with multiple character for example, {’12’, ’56’, ’14’ } one should write own comparator inside sort() function. The comparator function to sort in ascending order logic goes as:" }, { "code": null, "e": 25516, "s": 25443, "text": "Let’s build a comparator function considering the two cases given below:" }, { "code": null, "e": 25695, "s": 25516, "text": "Case 1: If the length of the string is not the same then place a smaller length string in first place for example, {’12’, ‘2’} place ‘2’ before ’12’ as ‘2’ is smaller than ’12’." }, { "code": null, "e": 25820, "s": 25695, "text": "Case 2: If length is the same then place the string which is numerically smaller for example, ‘1’, ‘2’ place ‘1’ before ‘2’." }, { "code": null, "e": 25878, "s": 25820, "text": "Below is the C++ program to implement the above approach:" }, { "code": null, "e": 25882, "s": 25878, "text": "C++" }, { "code": null, "e": 25887, "s": 25882, "text": "Java" }, { "code": null, "e": 25895, "s": 25887, "text": "Python3" }, { "code": null, "e": 25906, "s": 25895, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Comparator Functionbool myCmp(string s1, string s2){ // If size of numeric strings // are same the put lowest value // first if (s1.size() == s2.size()) { return s1 < s2; } // If size is not same put the // numeric string with less // number of digits first else { return s1.size() < s2.size(); }} // Driver Codeint main(){ vector<string> v = { \"12\", \"2\", \"10\", \"6\", \"4\", \"99\", \"12\" }; // Calling sort function with // custom comparator sort(v.begin(), v.end(), myCmp); // Print the vector values after // sorting for (auto it : v) { cout << it << \" \"; } cout << \"\\n\";}", "e": 26651, "s": 25906, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Comparator Functionstatic List<String> sort(List<String> list){ Comparator<String> cmp = (o1, o2) -> { // If size of numeric Strings // are same the put lowest value // first if (o1.length() == o2.length()) { return Integer.valueOf(o1)-Integer.valueOf(o2); } // If size is not same put the // numeric String with less // number of digits first else { return o1.length()-o2.length(); } }; Collections.sort(list, cmp); return list;} // Driver Codepublic static void main(String[] args){ List<String> v = Arrays.asList( \"12\", \"2\", \"10\", \"6\", \"4\", \"99\", \"12\" ); // Calling sort function with // custom comparator v = sort(v); // Print the vector values after // sorting for (String it : v) { System.out.print(it+ \" \"); } }} // This code is contributed by 29AjayKumar", "e": 27636, "s": 26651, "text": null }, { "code": "# Python3 Program to implement# the above approach # Comparator Functionfrom functools import cmp_to_key def myCmp(s1, s2): # If size of numeric strings # are same the put lowest value # first if (len(s1) == len(s2)): return int(s1) - int(s2) # If size is not same put the # numeric string with less # number of digits first else: return len(s1) - len(s2) # Driver Codev = [\"12\", \"2\", \"10\", \"6\", \"4\", \"99\", \"12\"] # Calling sort function with# custom comparatorv.sort(key = cmp_to_key(myCmp)) # Print the vector values after# sortingfor i in range(len(v)) : print(v[i],end=\" \") # This code is contributed by shinjanpatra", "e": 28298, "s": 27636, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Comparator Function function myCmp(s1, s2) { // If size of numeric strings // are same the put lowest value // first if (s1.length == s2.length) { return parseInt(s1) - parseInt(s2); } // If size is not same put the // numeric string with less // number of digits first else { return s1.length - s2.length; } } // Driver Code let v = [\"12\", \"2\", \"10\", \"6\", \"4\", \"99\", \"12\"]; // Calling sort function with // custom comparator v.sort(myCmp) // Print the vector values after // sorting for (let i = 0; i < v.length; i++) { document.write(v[i] + \" \") } // This code is contributed by Potta Lokesh </script>", "e": 29241, "s": 28298, "text": null }, { "code": null, "e": 29262, "s": 29244, "text": "2 4 6 10 12 12 99" }, { "code": null, "e": 29315, "s": 29266, "text": "Time Complexity: O(N*log N)Auxiliary Space: O(1)" }, { "code": null, "e": 29331, "s": 29317, "text": "lokeshpotta20" }, { "code": null, "e": 29343, "s": 29331, "text": "29AjayKumar" }, { "code": null, "e": 29356, "s": 29343, "text": "shinjanpatra" }, { "code": null, "e": 29363, "s": 29356, "text": "Arrays" }, { "code": null, "e": 29371, "s": 29363, "text": "Sorting" }, { "code": null, "e": 29379, "s": 29371, "text": "Strings" }, { "code": null, "e": 29386, "s": 29379, "text": "Arrays" }, { "code": null, "e": 29394, "s": 29386, "text": "Strings" }, { "code": null, "e": 29402, "s": 29394, "text": "Sorting" }, { "code": null, "e": 29500, "s": 29402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29509, "s": 29500, "text": "Comments" }, { "code": null, "e": 29522, "s": 29509, "text": "Old Comments" }, { "code": null, "e": 29547, "s": 29522, "text": "Window Sliding Technique" }, { "code": null, "e": 29596, "s": 29547, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 29634, "s": 29596, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 29654, "s": 29634, "text": "Trapping Rain Water" } ]
private access modifier in Java
Methods, variables, and constructors that are declared private can only be accessed within the declared class itself. Private access modifier is the most restrictive access level. Class and interfaces cannot be private. Variables that are declared private can be accessed outside the class, if public getter methods are present in the class. Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world. The following class uses private access control - public class Logger { private String format; public String getFormat() { return this.format; } public void setFormat(String format) { this.format = format; } } Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly. So, to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value.
[ { "code": null, "e": 1180, "s": 1062, "text": "Methods, variables, and constructors that are declared private can only be accessed within the declared class itself." }, { "code": null, "e": 1282, "s": 1180, "text": "Private access modifier is the most restrictive access level. Class and interfaces cannot be private." }, { "code": null, "e": 1404, "s": 1282, "text": "Variables that are declared private can be accessed outside the class, if public getter methods are present in the class." }, { "code": null, "e": 1521, "s": 1404, "text": "Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world." }, { "code": null, "e": 1758, "s": 1521, "text": "The following class uses private access control -\npublic class Logger {\n private String format;\n public String getFormat() {\n return this.format;\n }\n public void setFormat(String format) {\n this.format = format;\n }\n}" }, { "code": null, "e": 1891, "s": 1758, "text": "Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly." }, { "code": null, "e": 2073, "s": 1891, "text": "So, to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value." } ]
OpenGL in Java: how to use hardware acceleration | by Mario Emmanuel | Towards Data Science
Hardware acceleration is often seen as a niche solution for game development, but there are many other graphical applications that can benefit from this technology, especially those involving data visualisation such as specialised data science tools or software displaying real time data. Conventional charting tools and libraries are not fast enough for this task and hence custom graphics programming is needed. Hardware acceleration was once a high-end feature of specialised computers, such as Silicon Graphics UNIX workstations that were widely used in the film and TV industry during the 90s, but now it is a common feature present in every computer built during the last 15 or 20 years. While some graphics cards present more power and functionalities than others, a basic set of 2D and 3D acceleration is present in almost every modern device. This is achieved by means of a specialised CPU (which is called GPU — graphics processing unit — ). A GPU is a specific purpose CPU which provides the floating-point and matrices processing capabilities which are commonly used in 2D and 3D rendering. It basically allows the software to draw complex graphics dealing with user coordinates, scaling, panning, zooming, rotations and texture rendering, both in 2D and 3D. By providing such functionality close to the actual rastering output device, there is a reduction on both CPU usage and I/O bus bandwidth, which effectively enables to do complex renderings and animation, both in 2D and 3D. Relying on the main CPU for such tasks would imply that only less complex renderings could be done and that a lot of CPU time would be wasted to cope with the graphic routines. In this post, I will briefly cover OpenGL and its usage in Java, including an introductory but completely useful tutorial. The tutorial covers 2D, but it is actually a good introduction to OpenGL in general, so if you are interested in 3D, it is still good introductory material, as concepts are really similar for both 2D and 3D. There are two major competing standards in 2D and 3D acceleration: DirectX and OpenGL. It is important to understand that OpenGL and DirectX are hardware acceleration standards which define which APIs shall be exposed by graphics cards. In that sense, it is exactly the same as any other computing standard such as POSIX or the C++11 standard. Beyond the standards, there will be libraries implementing them, for DirectX libraries are provided directly by Microsoft and in the case of OpenGL, there are many open source solutions. Major graphics cards manufacturers decide if their hardware devices will support one technology or the other or both (which is the usual case). DirectX and OpenGL are not the only standards/APIs that provide 2D and 3D rendering capabilities. There are others, being the main ones Vulkan and Metal. However, both DirectX and OpenGL are basically the most widely used ones. Metal is focused on Apple devices and Vulkan intends to be an improvement over OpenGL. I have not evaluated those ones as I do not consider them interesting for my needs. DirectX (Direct2D and Direct3D) is a set of APIs created by Microsoft which are implemented in Windows. DirectX does not only cover graphics but also audio and input. While they are standards and could be theoretically implemented in any OS architecture, the reality is that DirectX is used only for Microsoft Windows (and XBOX, in case someone finds that information relevant). So basically DirectX is the standard solution for the Microsoft ecosystem. OpenGL, on the contrary, is intended to be a cross-platform language which can be used in every major OS released. It is actually the direct descendant of the old Silicon Graphics platforms which as early as 1991 defined IrisGL as a hardware API providing professional 2D and 3D rendering capabilities. Almost every modern graphics card (and by modern I mean latest 15 years) will provide compatibility with a given release of both DirectX and/or OpenGL, so its usage is no longer an oddity and chances are that you are no longer operating any computer without hardware acceleration capabilities. It is important to understand that these APIs are intended to provide rendering capabilities and not user interfaces. Some widgets/frameworks have been built on top of OpenGL and Direct2D to fulfil this need, although they are not as widely used as the regular frameworks operating without explicit hardware acceleration usage. The reason behind this is that hardware acceleration is usually linked to game development (which requires no standard user interfaces) and specialised graphical applications. I have evaluated a few combinations regarding hardware acceleration. Main ones have been Direct2D and C++ and OpenGL with either C++ or Java. In my opinion, there is no clear answer about which combination is better. If you do not need cross-platform (so you are basically developing for Windows) and you do not need to develop complex user interfaces either, I would say that Direct2D is the way to go. It is easier, it is well supported in Windows and it will fulfil all needs. However, if you are interested in covering other OSs then OpenGL is definitively the way to go. Out of the box, it will support all major OSs. Regarding using Java or C++, I personally chose Java because it allows easier integration with existing user interface frameworks (specifically, Java Swing). My needs involve both graphics acceleration and user interface, so my approach to OpenGL might be slightly different to most of the material you can find on Internet, which is usually focused on games development. This explains why it is so relevant to me how each language and user interface framework interacts with OpenGL. For C++ under Windows and Direct2D, there is no straightforward answer on how to implement user interfaces on top of C++. If you are willing to use .NET there are things like Win2D which enables programming in the .NET framework (and hence accessing all the user interface frameworks seamlessly) and at the same time benefit from Direct2D hardware acceleration. However, this is not a widely used solution so it implies that you are not using a mainstream technology/library, which in my opinion is always a risky proposition in terms of support, documentation and future maintenance. As mentioned, C++ user interfaces development is not as straightforward as it would be using the .NET framework. You can mix C++ and the .NET framework by using C++/CLI to gain access to WinForms (which is not a mainstream solution) or you could rely on the legacy ATL/MFC classes, which are still properly maintained despite they are considered legacy technology. MFC also forces you to deal with a lot of boilerplate, including a lot of Microsoft specific verbose classes that are now superseded by the C++ standard template libraries. You end up writing code which is so tightly coupled to Microsoft than it can no longer be considered portable C++. On top of that, there is the possibility of using other cross-platform widget frameworks (such as wxWidgets or Qt), I personally dislike that approach as I think that if you need cross-platform Java is the simplest path, and if you want to focus on Windows using Microsoft mainstream tools is the safest way. In any case, all those solutions involve a certain degree of boilerplate (sometimes they are actually quite complex to implement). Windows APIs never shined in terms of usability and simplicity. While .NET changed this paradigm and it is now pretty easy to build applications in C# or VB, it is still more focused on productivity applications where performance is not an issue. In my opinion, if you need hardware acceleration, a medium complex user interface and a cross-platform solution there is nothing easier than Java with Swing and OpenGL. Java Swing is considered obsolete by many people, but the fact is that it still brings reasonably modern interfaces for desktop applications, it is quite lightweight and it powerful enough to provide a good user interface experience. Unless you are looking for a cutting-edge UI design, Java Swing will do the job. This is especially true for niche applications where usability and functionality are more relevant than interface look and feel. I have reviewed all Java alternatives for OpenGL, and I finally chose JOGL. The reason is that JOGL is a general-purpose OpenGL implementation, not only focused on games as other libraries (such as LWJGL). It can be integrated with both AWT and Swing so you can have both of both worlds: custom hardware-accelerated graphics and easy to develop and implement user interfaces through Swing. Using this combination of Java/Swing/OpenGL has the side benefit that your software shall run without any change in both Linux/UNIX and Windows systems. As a trade-off, if your software requires low-level data processing, Java fits sometimes a bit worse than C++ and it might be slightly slower too. There are also alternative frameworks built on top of OpenGL. Those do not require anything else to have your user interfaces running, but according to my research, none of those interfaces is mature enough to be considered a safe alternative. They tend also to work only for specific OpenGL implementations and they also rely on other libraries so at the end there are still some external dependencies. The bindings for these frameworks are usually provided only for C++. Without further delay, let’s code our first OpenGL program. I will be using Netbeans 8.2 and Oracle JDK 8. JOGL can be downloaded from its main website https://jogamp.org and you will need to incorporate gluegen and jogl libraries to your IDE. Specific instructions on how to do this can be easily found so I will not repeat them here, especially because they will depend on the specific version you are installing and on the IDE you are using. Just suffice to say that you can download the Jars from the main JOGL website under Build/Downloads — Zip. Download “all platforms” .ZIP and the JavaDoc and install them in your project. You will end up with something like this: First we will implement a class which extends JFrame so it will basically define a Window where we can draw using OpenGL. This class: Extends JFrame, because we want a stand-alone window where we can draw. This is not OpenGL related but just a way to have a Window in Java Swing.Implements GLEventListener interface, which is a requirement of JOGL to implement OpenGL. This interface requires implementing four methods: display, reshape, init and dispose.In this example, only display method is actually implemented. Here we will perform the actual drawing (more on this later).We need a GLProfile and a GLCapabilities objects which define which specific OpenGL version and which capabilities are being implemented.We need a GLCanvas object, which is basically a Canvas object that implements OpenGL. This will be added to a class which implements the GLEventListener interface, which in our case is our JFrame class. This is probably better understood by simply checking the three lines which create the GLCanvas object in the source code. Extends JFrame, because we want a stand-alone window where we can draw. This is not OpenGL related but just a way to have a Window in Java Swing. Implements GLEventListener interface, which is a requirement of JOGL to implement OpenGL. This interface requires implementing four methods: display, reshape, init and dispose. In this example, only display method is actually implemented. Here we will perform the actual drawing (more on this later). We need a GLProfile and a GLCapabilities objects which define which specific OpenGL version and which capabilities are being implemented. We need a GLCanvas object, which is basically a Canvas object that implements OpenGL. This will be added to a class which implements the GLEventListener interface, which in our case is our JFrame class. This is probably better understood by simply checking the three lines which create the GLCanvas object in the source code. To recap, we are basically creating a JFrame class which implements GLEventListener interface and incorporates a GLCanvas object. This allows us to use OpenGL over the GLCanvas object. With all these steps we are ready to draw, which is achieved by implementing the display method. The display method, in this case, is pretty simple. It receives a GLDrawable object as a parameter. From this object, we can get a GL2 object which is the one we use to draw. To draw a line we just do: gl.glBegin(GL2.GL_LINES);gl.glVertex3f(-0.50f, -0.50f, 0);gl.glVertex3f(0.50f, -0.50f, 0);gl.glEnd(); We enclose our drawing between glBegin and glEnd definitions. As glBegin parameter we provide GL2.GL_LINES which basically tells OpenGL that we are drawing a line. Because we are drawing a line we know that we need to provide two points (and OpenGL expects so). Therefore, we define two vertexes (points) which in this case are defined in 3D. These two points are the ones defining the line. The basic idea is that we begin a drawing and provide the necessary information (in this case, two points to draw a line) that the GPU requires to draw it onto the Canvas object. Other drawing primitives would require other information between glBegin and glEnd. To complete our triangle we just draw three segments. Finally and in order to display the window, the JFrame needs to be invoked as any JFrame would be in Java Swing. Our main class would be as simple as this one: This completes our first OpenGL program in Java. Comparatively, it is much easier to get a working example in Java than in C++, as Java Swing is easier to code than Microsoft existing APIs. In the next series we will continue programming OpenGL.
[ { "code": null, "e": 585, "s": 171, "text": "Hardware acceleration is often seen as a niche solution for game development, but there are many other graphical applications that can benefit from this technology, especially those involving data visualisation such as specialised data science tools or software displaying real time data. Conventional charting tools and libraries are not fast enough for this task and hence custom graphics programming is needed." }, { "code": null, "e": 1023, "s": 585, "text": "Hardware acceleration was once a high-end feature of specialised computers, such as Silicon Graphics UNIX workstations that were widely used in the film and TV industry during the 90s, but now it is a common feature present in every computer built during the last 15 or 20 years. While some graphics cards present more power and functionalities than others, a basic set of 2D and 3D acceleration is present in almost every modern device." }, { "code": null, "e": 1442, "s": 1023, "text": "This is achieved by means of a specialised CPU (which is called GPU — graphics processing unit — ). A GPU is a specific purpose CPU which provides the floating-point and matrices processing capabilities which are commonly used in 2D and 3D rendering. It basically allows the software to draw complex graphics dealing with user coordinates, scaling, panning, zooming, rotations and texture rendering, both in 2D and 3D." }, { "code": null, "e": 1843, "s": 1442, "text": "By providing such functionality close to the actual rastering output device, there is a reduction on both CPU usage and I/O bus bandwidth, which effectively enables to do complex renderings and animation, both in 2D and 3D. Relying on the main CPU for such tasks would imply that only less complex renderings could be done and that a lot of CPU time would be wasted to cope with the graphic routines." }, { "code": null, "e": 2174, "s": 1843, "text": "In this post, I will briefly cover OpenGL and its usage in Java, including an introductory but completely useful tutorial. The tutorial covers 2D, but it is actually a good introduction to OpenGL in general, so if you are interested in 3D, it is still good introductory material, as concepts are really similar for both 2D and 3D." }, { "code": null, "e": 2705, "s": 2174, "text": "There are two major competing standards in 2D and 3D acceleration: DirectX and OpenGL. It is important to understand that OpenGL and DirectX are hardware acceleration standards which define which APIs shall be exposed by graphics cards. In that sense, it is exactly the same as any other computing standard such as POSIX or the C++11 standard. Beyond the standards, there will be libraries implementing them, for DirectX libraries are provided directly by Microsoft and in the case of OpenGL, there are many open source solutions." }, { "code": null, "e": 2849, "s": 2705, "text": "Major graphics cards manufacturers decide if their hardware devices will support one technology or the other or both (which is the usual case)." }, { "code": null, "e": 3248, "s": 2849, "text": "DirectX and OpenGL are not the only standards/APIs that provide 2D and 3D rendering capabilities. There are others, being the main ones Vulkan and Metal. However, both DirectX and OpenGL are basically the most widely used ones. Metal is focused on Apple devices and Vulkan intends to be an improvement over OpenGL. I have not evaluated those ones as I do not consider them interesting for my needs." }, { "code": null, "e": 3702, "s": 3248, "text": "DirectX (Direct2D and Direct3D) is a set of APIs created by Microsoft which are implemented in Windows. DirectX does not only cover graphics but also audio and input. While they are standards and could be theoretically implemented in any OS architecture, the reality is that DirectX is used only for Microsoft Windows (and XBOX, in case someone finds that information relevant). So basically DirectX is the standard solution for the Microsoft ecosystem." }, { "code": null, "e": 4005, "s": 3702, "text": "OpenGL, on the contrary, is intended to be a cross-platform language which can be used in every major OS released. It is actually the direct descendant of the old Silicon Graphics platforms which as early as 1991 defined IrisGL as a hardware API providing professional 2D and 3D rendering capabilities." }, { "code": null, "e": 4299, "s": 4005, "text": "Almost every modern graphics card (and by modern I mean latest 15 years) will provide compatibility with a given release of both DirectX and/or OpenGL, so its usage is no longer an oddity and chances are that you are no longer operating any computer without hardware acceleration capabilities." }, { "code": null, "e": 4803, "s": 4299, "text": "It is important to understand that these APIs are intended to provide rendering capabilities and not user interfaces. Some widgets/frameworks have been built on top of OpenGL and Direct2D to fulfil this need, although they are not as widely used as the regular frameworks operating without explicit hardware acceleration usage. The reason behind this is that hardware acceleration is usually linked to game development (which requires no standard user interfaces) and specialised graphical applications." }, { "code": null, "e": 5020, "s": 4803, "text": "I have evaluated a few combinations regarding hardware acceleration. Main ones have been Direct2D and C++ and OpenGL with either C++ or Java. In my opinion, there is no clear answer about which combination is better." }, { "code": null, "e": 5283, "s": 5020, "text": "If you do not need cross-platform (so you are basically developing for Windows) and you do not need to develop complex user interfaces either, I would say that Direct2D is the way to go. It is easier, it is well supported in Windows and it will fulfil all needs." }, { "code": null, "e": 5426, "s": 5283, "text": "However, if you are interested in covering other OSs then OpenGL is definitively the way to go. Out of the box, it will support all major OSs." }, { "code": null, "e": 5910, "s": 5426, "text": "Regarding using Java or C++, I personally chose Java because it allows easier integration with existing user interface frameworks (specifically, Java Swing). My needs involve both graphics acceleration and user interface, so my approach to OpenGL might be slightly different to most of the material you can find on Internet, which is usually focused on games development. This explains why it is so relevant to me how each language and user interface framework interacts with OpenGL." }, { "code": null, "e": 6495, "s": 5910, "text": "For C++ under Windows and Direct2D, there is no straightforward answer on how to implement user interfaces on top of C++. If you are willing to use .NET there are things like Win2D which enables programming in the .NET framework (and hence accessing all the user interface frameworks seamlessly) and at the same time benefit from Direct2D hardware acceleration. However, this is not a widely used solution so it implies that you are not using a mainstream technology/library, which in my opinion is always a risky proposition in terms of support, documentation and future maintenance." }, { "code": null, "e": 7148, "s": 6495, "text": "As mentioned, C++ user interfaces development is not as straightforward as it would be using the .NET framework. You can mix C++ and the .NET framework by using C++/CLI to gain access to WinForms (which is not a mainstream solution) or you could rely on the legacy ATL/MFC classes, which are still properly maintained despite they are considered legacy technology. MFC also forces you to deal with a lot of boilerplate, including a lot of Microsoft specific verbose classes that are now superseded by the C++ standard template libraries. You end up writing code which is so tightly coupled to Microsoft than it can no longer be considered portable C++." }, { "code": null, "e": 7457, "s": 7148, "text": "On top of that, there is the possibility of using other cross-platform widget frameworks (such as wxWidgets or Qt), I personally dislike that approach as I think that if you need cross-platform Java is the simplest path, and if you want to focus on Windows using Microsoft mainstream tools is the safest way." }, { "code": null, "e": 7835, "s": 7457, "text": "In any case, all those solutions involve a certain degree of boilerplate (sometimes they are actually quite complex to implement). Windows APIs never shined in terms of usability and simplicity. While .NET changed this paradigm and it is now pretty easy to build applications in C# or VB, it is still more focused on productivity applications where performance is not an issue." }, { "code": null, "e": 8448, "s": 7835, "text": "In my opinion, if you need hardware acceleration, a medium complex user interface and a cross-platform solution there is nothing easier than Java with Swing and OpenGL. Java Swing is considered obsolete by many people, but the fact is that it still brings reasonably modern interfaces for desktop applications, it is quite lightweight and it powerful enough to provide a good user interface experience. Unless you are looking for a cutting-edge UI design, Java Swing will do the job. This is especially true for niche applications where usability and functionality are more relevant than interface look and feel." }, { "code": null, "e": 8838, "s": 8448, "text": "I have reviewed all Java alternatives for OpenGL, and I finally chose JOGL. The reason is that JOGL is a general-purpose OpenGL implementation, not only focused on games as other libraries (such as LWJGL). It can be integrated with both AWT and Swing so you can have both of both worlds: custom hardware-accelerated graphics and easy to develop and implement user interfaces through Swing." }, { "code": null, "e": 9138, "s": 8838, "text": "Using this combination of Java/Swing/OpenGL has the side benefit that your software shall run without any change in both Linux/UNIX and Windows systems. As a trade-off, if your software requires low-level data processing, Java fits sometimes a bit worse than C++ and it might be slightly slower too." }, { "code": null, "e": 9611, "s": 9138, "text": "There are also alternative frameworks built on top of OpenGL. Those do not require anything else to have your user interfaces running, but according to my research, none of those interfaces is mature enough to be considered a safe alternative. They tend also to work only for specific OpenGL implementations and they also rely on other libraries so at the end there are still some external dependencies. The bindings for these frameworks are usually provided only for C++." }, { "code": null, "e": 9718, "s": 9611, "text": "Without further delay, let’s code our first OpenGL program. I will be using Netbeans 8.2 and Oracle JDK 8." }, { "code": null, "e": 10285, "s": 9718, "text": "JOGL can be downloaded from its main website https://jogamp.org and you will need to incorporate gluegen and jogl libraries to your IDE. Specific instructions on how to do this can be easily found so I will not repeat them here, especially because they will depend on the specific version you are installing and on the IDE you are using. Just suffice to say that you can download the Jars from the main JOGL website under Build/Downloads — Zip. Download “all platforms” .ZIP and the JavaDoc and install them in your project. You will end up with something like this:" }, { "code": null, "e": 10407, "s": 10285, "text": "First we will implement a class which extends JFrame so it will basically define a Window where we can draw using OpenGL." }, { "code": null, "e": 10419, "s": 10407, "text": "This class:" }, { "code": null, "e": 11326, "s": 10419, "text": "Extends JFrame, because we want a stand-alone window where we can draw. This is not OpenGL related but just a way to have a Window in Java Swing.Implements GLEventListener interface, which is a requirement of JOGL to implement OpenGL. This interface requires implementing four methods: display, reshape, init and dispose.In this example, only display method is actually implemented. Here we will perform the actual drawing (more on this later).We need a GLProfile and a GLCapabilities objects which define which specific OpenGL version and which capabilities are being implemented.We need a GLCanvas object, which is basically a Canvas object that implements OpenGL. This will be added to a class which implements the GLEventListener interface, which in our case is our JFrame class. This is probably better understood by simply checking the three lines which create the GLCanvas object in the source code." }, { "code": null, "e": 11472, "s": 11326, "text": "Extends JFrame, because we want a stand-alone window where we can draw. This is not OpenGL related but just a way to have a Window in Java Swing." }, { "code": null, "e": 11649, "s": 11472, "text": "Implements GLEventListener interface, which is a requirement of JOGL to implement OpenGL. This interface requires implementing four methods: display, reshape, init and dispose." }, { "code": null, "e": 11773, "s": 11649, "text": "In this example, only display method is actually implemented. Here we will perform the actual drawing (more on this later)." }, { "code": null, "e": 11911, "s": 11773, "text": "We need a GLProfile and a GLCapabilities objects which define which specific OpenGL version and which capabilities are being implemented." }, { "code": null, "e": 12237, "s": 11911, "text": "We need a GLCanvas object, which is basically a Canvas object that implements OpenGL. This will be added to a class which implements the GLEventListener interface, which in our case is our JFrame class. This is probably better understood by simply checking the three lines which create the GLCanvas object in the source code." }, { "code": null, "e": 12422, "s": 12237, "text": "To recap, we are basically creating a JFrame class which implements GLEventListener interface and incorporates a GLCanvas object. This allows us to use OpenGL over the GLCanvas object." }, { "code": null, "e": 12519, "s": 12422, "text": "With all these steps we are ready to draw, which is achieved by implementing the display method." }, { "code": null, "e": 12694, "s": 12519, "text": "The display method, in this case, is pretty simple. It receives a GLDrawable object as a parameter. From this object, we can get a GL2 object which is the one we use to draw." }, { "code": null, "e": 12721, "s": 12694, "text": "To draw a line we just do:" }, { "code": null, "e": 12823, "s": 12721, "text": "gl.glBegin(GL2.GL_LINES);gl.glVertex3f(-0.50f, -0.50f, 0);gl.glVertex3f(0.50f, -0.50f, 0);gl.glEnd();" }, { "code": null, "e": 13215, "s": 12823, "text": "We enclose our drawing between glBegin and glEnd definitions. As glBegin parameter we provide GL2.GL_LINES which basically tells OpenGL that we are drawing a line. Because we are drawing a line we know that we need to provide two points (and OpenGL expects so). Therefore, we define two vertexes (points) which in this case are defined in 3D. These two points are the ones defining the line." }, { "code": null, "e": 13478, "s": 13215, "text": "The basic idea is that we begin a drawing and provide the necessary information (in this case, two points to draw a line) that the GPU requires to draw it onto the Canvas object. Other drawing primitives would require other information between glBegin and glEnd." }, { "code": null, "e": 13532, "s": 13478, "text": "To complete our triangle we just draw three segments." }, { "code": null, "e": 13692, "s": 13532, "text": "Finally and in order to display the window, the JFrame needs to be invoked as any JFrame would be in Java Swing. Our main class would be as simple as this one:" } ]
Print all unique words of a String - GeeksforGeeks
27 Jan, 2022 Write a function that takes a String as an argument and prints all unique words in it. Examples: Input : Java is great. Grails is also great Output : Java Grails also Approach:The idea is to use map to keep track of words already occurred. But first, we have to extract all words from a String, as a string may contain many sentences with punctuation marks.For extracting words from a String, refer Extracting each word from a String. Python: The idea is to use a Dictionary for calculating the count of each word. But first, we have to extract all words from a String because a string may contain punctuation marks. This is done using regex or regular expression. The word which has count 1 in the dictionary is a unique word. Java Python3 // Java program to print unique words// from a string import java.util.HashMap;import java.util.Iterator;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern; public class Test{ // Prints unique words in a string static void printUniquedWords(String str) { // Extracting words from string Pattern p = Pattern.compile("[a-zA-Z]+"); Matcher m = p.matcher(str); // Map to store count of a word HashMap<String, Integer> hm = new HashMap<>(); // if a word found while (m.find()) { String word = m.group(); // If this is first occurrence of word if(!hm.containsKey(word)) hm.put(word, 1); else // increment counter of word hm.put(word, hm.get(word) + 1); } // Traverse map and print all words whose count // is 1 Set<String> s = hm.keySet(); Iterator<String> itr = s.iterator(); while(itr.hasNext()) { String w = itr.next(); if (hm.get(w) == 1) System.out.println(w); } } // Driver Method public static void main(String[] args) { String str = "Java is great. Grails is also great"; printUniquedWords(str); }} # Python program to print unique word# in a string.# Using re (Regular Expression module)# It is used here to match a pattern# in the given stringimport re # Declare a dictionarydict = {} # Method to check whether the word# exists in dictionary or notdef uniqueWord(Word): if Word in dict: # If the word exists in dictionary then # simply increase its count dict[words] += 1 else: # If the word does not exists in # dictionary update the dictionary # and make its count 1 dict.update({words: 1}) # Driver codeif __name__ == '__main__': string = "Java is great. Grails is also great" # re.split() method is used to split # all the words in a string separated # by non-alphanumeric characters (\W) ListOfWords = re.split("[\W]+", string) # Extract each word from ListOfWords # and pass it to the method uniqueWord() for words in ListOfWords: uniqueWord(words) # Iterate over dictionary if the value # of the key is 1, then print the element for elements in dict: if dict[elements] == 1: print(elements) Java Grails also This article is contributed by Gaurav Ahirwar and Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Method 2:using set() Approach: In this approach, we store the string in the form of a set of individual words and print the words. To solve this problem in this method, first we need to know about https://www.geeksforgeeks.org/sets-in-python/ Below is the implementation of the above approach: Python3 # python program to print all# the unique words in a string# in python using set() method# function to print unique words def printWords(l): # for loop for iterating for i in l: print(i) # Driver codestr = "geeks for geeks" # storing string in the form of list of wordss = set(str.split(" ")) # passing list to print words functionprintWords(s) geeks for Ronit_shrivastava skate1512 vikkycirus gabaa406 amartyaghoshgfg Java-String-Programs Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Stream In Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Internal Working of HashMap in Java Checked vs Unchecked Exceptions in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23893, "s": 23865, "text": "\n27 Jan, 2022" }, { "code": null, "e": 23980, "s": 23893, "text": "Write a function that takes a String as an argument and prints all unique words in it." }, { "code": null, "e": 23990, "s": 23980, "text": "Examples:" }, { "code": null, "e": 24078, "s": 23990, "text": "Input : Java is great. Grails is also great\nOutput : Java\n Grails\n also" }, { "code": null, "e": 24346, "s": 24078, "text": "Approach:The idea is to use map to keep track of words already occurred. But first, we have to extract all words from a String, as a string may contain many sentences with punctuation marks.For extracting words from a String, refer Extracting each word from a String." }, { "code": null, "e": 24639, "s": 24346, "text": "Python: The idea is to use a Dictionary for calculating the count of each word. But first, we have to extract all words from a String because a string may contain punctuation marks. This is done using regex or regular expression. The word which has count 1 in the dictionary is a unique word." }, { "code": null, "e": 24644, "s": 24639, "text": "Java" }, { "code": null, "e": 24652, "s": 24644, "text": "Python3" }, { "code": "// Java program to print unique words// from a string import java.util.HashMap;import java.util.Iterator;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern; public class Test{ // Prints unique words in a string static void printUniquedWords(String str) { // Extracting words from string Pattern p = Pattern.compile(\"[a-zA-Z]+\"); Matcher m = p.matcher(str); // Map to store count of a word HashMap<String, Integer> hm = new HashMap<>(); // if a word found while (m.find()) { String word = m.group(); // If this is first occurrence of word if(!hm.containsKey(word)) hm.put(word, 1); else // increment counter of word hm.put(word, hm.get(word) + 1); } // Traverse map and print all words whose count // is 1 Set<String> s = hm.keySet(); Iterator<String> itr = s.iterator(); while(itr.hasNext()) { String w = itr.next(); if (hm.get(w) == 1) System.out.println(w); } } // Driver Method public static void main(String[] args) { String str = \"Java is great. Grails is also great\"; printUniquedWords(str); }}", "e": 26037, "s": 24652, "text": null }, { "code": "# Python program to print unique word# in a string.# Using re (Regular Expression module)# It is used here to match a pattern# in the given stringimport re # Declare a dictionarydict = {} # Method to check whether the word# exists in dictionary or notdef uniqueWord(Word): if Word in dict: # If the word exists in dictionary then # simply increase its count dict[words] += 1 else: # If the word does not exists in # dictionary update the dictionary # and make its count 1 dict.update({words: 1}) # Driver codeif __name__ == '__main__': string = \"Java is great. Grails is also great\" # re.split() method is used to split # all the words in a string separated # by non-alphanumeric characters (\\W) ListOfWords = re.split(\"[\\W]+\", string) # Extract each word from ListOfWords # and pass it to the method uniqueWord() for words in ListOfWords: uniqueWord(words) # Iterate over dictionary if the value # of the key is 1, then print the element for elements in dict: if dict[elements] == 1: print(elements)", "e": 27167, "s": 26037, "text": null }, { "code": null, "e": 27184, "s": 27167, "text": "Java\nGrails\nalso" }, { "code": null, "e": 27626, "s": 27184, "text": "This article is contributed by Gaurav Ahirwar and Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 27647, "s": 27626, "text": "Method 2:using set()" }, { "code": null, "e": 27657, "s": 27647, "text": "Approach:" }, { "code": null, "e": 27869, "s": 27657, "text": "In this approach, we store the string in the form of a set of individual words and print the words. To solve this problem in this method, first we need to know about https://www.geeksforgeeks.org/sets-in-python/" }, { "code": null, "e": 27920, "s": 27869, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27928, "s": 27920, "text": "Python3" }, { "code": "# python program to print all# the unique words in a string# in python using set() method# function to print unique words def printWords(l): # for loop for iterating for i in l: print(i) # Driver codestr = \"geeks for geeks\" # storing string in the form of list of wordss = set(str.split(\" \")) # passing list to print words functionprintWords(s)", "e": 28293, "s": 27928, "text": null }, { "code": null, "e": 28303, "s": 28293, "text": "geeks\nfor" }, { "code": null, "e": 28321, "s": 28303, "text": "Ronit_shrivastava" }, { "code": null, "e": 28331, "s": 28321, "text": "skate1512" }, { "code": null, "e": 28342, "s": 28331, "text": "vikkycirus" }, { "code": null, "e": 28351, "s": 28342, "text": "gabaa406" }, { "code": null, "e": 28367, "s": 28351, "text": "amartyaghoshgfg" }, { "code": null, "e": 28388, "s": 28367, "text": "Java-String-Programs" }, { "code": null, "e": 28401, "s": 28388, "text": "Java-Strings" }, { "code": null, "e": 28406, "s": 28401, "text": "Java" }, { "code": null, "e": 28419, "s": 28406, "text": "Java-Strings" }, { "code": null, "e": 28424, "s": 28419, "text": "Java" }, { "code": null, "e": 28522, "s": 28424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28531, "s": 28522, "text": "Comments" }, { "code": null, "e": 28544, "s": 28531, "text": "Old Comments" }, { "code": null, "e": 28565, "s": 28544, "text": "Constructors in Java" }, { "code": null, "e": 28580, "s": 28565, "text": "Stream In Java" }, { "code": null, "e": 28599, "s": 28580, "text": "Exceptions in Java" }, { "code": null, "e": 28629, "s": 28599, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28675, "s": 28629, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28701, "s": 28675, "text": "Java Programming Examples" }, { "code": null, "e": 28737, "s": 28701, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 28777, "s": 28737, "text": "Checked vs Unchecked Exceptions in Java" }, { "code": null, "e": 28793, "s": 28777, "text": "Strings in Java" } ]
How to Add a New Disk Drive to a Linux Machine
This article helps you to configure and add a new disk to the Linux box. This is one of the most common problems encountered by system administrators these days since the servers are tending to run out of disk space to store excess data. Fortunately, disk space is now one of the cheapest. We shall look at the steps necessary to configure on Red Hat Enterprise Linux 6. x to add more space by installing the disk. Mounted Filesystems or Logical Volumes Getting Started Finding the New Hard Drive in RHEL 6 Creating Linux Partitions Creating a Filesystem on an RHEL 6 Disk Partition Mounting a Filesystem Configuring RHEL 6 to Automatically Mount a Filesystem One very simplest method is to create a Linux partition on the new disk. Create a Linux file system on those partitions and then mount the disk at a specific mount point so that they can be accessed. This article assumes that the new physical hard drive has been installed on the system and is visible to the operating system. Assuming the drive as visible to the BIOS, it should automatically be detected by the operating system. Typically, the disk drives in a system are assigned to a device name beginning with hd or sd followed by a letter to indicate the device number. For example, the first device might be /dev/sda, the second /dev/sdb and so on. The following is the output from a system with only one physical disk drive – # ls /dev/sd* /dev/sda /dev/sda1 /dev/sda2 This shows that the disk drive is represented by /dev/sda itself divided into 2 partitions, represented by /dev/sda1 and /dev/sda2. The following would be the output for the same system if we attach second hard disk drive. # ls /dev/sd* /dev/sda /dev/sda1 /dev/sda2 /dev/sdb As shown above, the new hard drive has been assigned to the device file /dev/sdb. Currently, the drive has no partitions shown (because we have yet to create any). At this point, we have a choice of creating partitions and file systems on the new drive and mounting them for access or adding the disk as a physical volume as part of a volume group. The next step is to create one or more Linux partitions on the new disk drive. This is achieved using the fdisk utility which takes as a command-line argument on the device to be partitioned. # fdisk /dev/sdb The Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel Building a new DOS disklabel with disk identifier 0xd1082b01. Changes will remain in memory only, until you decide to write them. After that, of course, the previous content won't be recoverable. Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite) WARNING: DOS-compatible mode is deprecated. It's strongly recommended to switch off the mode (command 'c') and change display units to sectors (command 'u'). Command (m for help): As instructed, switch off DOS compatible mode and change the units to sectors by entering the c and u commands: Command (m for help): c DOS Compatibility flag is not set Command (m for help): u Changing display/entry units to sectors In order to view the current partitions on the disk enter the p command: Command (m for help): p Disk /dev/sdb: 34.4 GB, 34359738368 bytes 255 heads, 63 sectors/track, 4177 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0xd1082b01 Device Boot Start End Blocks Id System As we can see from the above, the fdisk output of the disk currently has no partitions because it is a previously unused disk. The next step is to create a new partition on the disk, a task which is performed by entering “n” (for new partition) and “p” (for primary partition) Command (m for help): n Command action e extended p primary partition (1-4) p Partition number (1-4): In this example, we only plan to create one partition which will be partition 1. Next, we need to specify where the partition will begin and end. Since, this is the first partition, we need to start at the first available sector and as we want to use the entire disk to specify the last sector at the end. Note that, if you wish to create multiple partitions, you can specify the size of each partition by sectors, bytes, kilobytes or megabytes. Partition number (1-4): 1 First sector (2048-67108863, default 2048): Using default value 2048 Last sector, +sectors or +size{K,M,G} (2048-67108863, default 67108863): Using default value 67108863 Now that we have specified the partition we need to write it to the disk using the w command: Command (m for help): w The partition table has been altered! Calling ioctl() to re-read partition table. Syncing disks. If we now look at the devices again we will see that the new partition is visible as /dev/sdb1: # ls /dev/sd* /dev/sda /dev/sda1 /dev/sda2 /dev/sdb /dev/sdb1 The next step is to create a filesystem on our new partition. We now have a new disk installed, it is visible to RHEL 6 and we have configured a Linux partition on the disk. The next step is to create a Linux file system on the partition so that the operating system can use it to store files and data. The easiest way to create a file system on a partition is to use the mkfs.ext4 utility which takes as arguments the label and the partition device # /sbin/mkfs.ext4 -L /backup /dev/sdb1 mke2fs 1.41.12 (17-May-2010) Filesystem label=/backup OS type: Linux Block size=4096 (log=2) Fragment size=4096 (log=2) Stride=0 blocks, Stripe width=0 blocks 2097152 inodes, 8388352 blocks 419417 blocks (5.00%) reserved for the super user First data block=0 Maximum filesystem blocks=4294967296 256 block groups 32768 blocks per group, 32768 fragments per group 8192 inodes per group Superblock backups stored on blocks: 32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,4096000, 7962624 Writing inode tables: done Creating journal (32768 blocks): done Writing superblocks and filesystem accounting information: done This filesystem checks automatically after 36 mounts or 180 days, whichever comes first. Use tune2fs -c or -i to override. Now that we have created a new filesystem on the Linux partition of our new disk drive, we need to mount it so that it is accessible. In order to do this we need to create a mount point. A mount point is simply a directory or folder into which the filesystem will be mounted. For the purposes of this example, we will create a /backup directory to match our filesystem label (although it is not necessary that these values match) # mkdir /backup The file system may then be manually mounted using the mount command # mount /dev/sdb1 /backup Running the mount command with no arguments shows us all currently mounted filesystems (including our new filesystem): # mount /dev/mapper/vg_rhel6-lv_root on / type ext4 (rw) proc on /proc type proc (rw) sysfs on /sys type sysfs (rw) devpts on /dev/pts type devpts (rw,gid=5,mode=620) tmpfs on /dev/shm type tmpfs (rw,rootcontext="system_u:object_r:tmpfs_t:s0") /dev/sda1 on /boot type ext4 (rw) none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw) sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw) /dev/sr0 on /media/RHEL_6.0 x86_64 Disc 1 type iso9660 (ro,nosuid,nodev,uhelper=udisks,uid=500,gid=500,iocharset=utf8,mode=0400,dmode=0500) /dev/sdb1 on /backup type ext4 (rw) In order to configure the system so that the new disk is automatically mounted at the time boot we need an entry to be added to the /etc/fstab file. The below is the sample configuration file which shows an fstab file configured to auto mount our /backup partition /dev/mapper/vg_rhel6-lv_root / ext4 defaults 1 1 UUID=4a9886f5-9545-406a-a694-04a60b24df84 /boot ext4 defaults 1 2 /dev/mapper/vg_rhel6-lv_swap swap swap defaults 0 0 tmpfs /dev/shm tmpfs defaults 0 0 devpts /dev/pts devpts gid=5,mode=620 0 0 sysfs /sys sysfs defaults 0 0 proc /proc proc defaults 0 0 LABEL=/backup /backup ext4 defaults 1 2 After this configuration and demo, we can add new disks to the existing Linux machine without any issues and extends the space for storing the backups with another drive with easy steps. Hope this information helps!
[ { "code": null, "e": 1477, "s": 1062, "text": "This article helps you to configure and add a new disk to the Linux box. This is one of the most common problems encountered by system administrators these days since the servers are tending to run out of disk space to store excess data. Fortunately, disk space is now one of the cheapest. We shall look at the steps necessary to configure on Red Hat Enterprise Linux 6. x to add more space by installing the disk." }, { "code": null, "e": 1516, "s": 1477, "text": "Mounted Filesystems or Logical Volumes" }, { "code": null, "e": 1532, "s": 1516, "text": "Getting Started" }, { "code": null, "e": 1569, "s": 1532, "text": "Finding the New Hard Drive in RHEL 6" }, { "code": null, "e": 1595, "s": 1569, "text": "Creating Linux Partitions" }, { "code": null, "e": 1645, "s": 1595, "text": "Creating a Filesystem on an RHEL 6 Disk Partition" }, { "code": null, "e": 1667, "s": 1645, "text": "Mounting a Filesystem" }, { "code": null, "e": 1722, "s": 1667, "text": "Configuring RHEL 6 to Automatically Mount a Filesystem" }, { "code": null, "e": 1922, "s": 1722, "text": "One very simplest method is to create a Linux partition on the new disk. Create a Linux file system on those partitions and then mount the disk at a specific mount point so that they can be accessed." }, { "code": null, "e": 2049, "s": 1922, "text": "This article assumes that the new physical hard drive has been installed on the system and is visible to the operating system." }, { "code": null, "e": 2378, "s": 2049, "text": "Assuming the drive as visible to the BIOS, it should automatically be detected by the operating system. Typically, the disk drives in a system are assigned to a device name beginning with hd or sd followed by a letter to indicate the device number. For example, the first device might be /dev/sda, the second /dev/sdb and so on." }, { "code": null, "e": 2456, "s": 2378, "text": "The following is the output from a system with only one physical disk drive –" }, { "code": null, "e": 2499, "s": 2456, "text": "# ls /dev/sd*\n/dev/sda /dev/sda1 /dev/sda2" }, { "code": null, "e": 2722, "s": 2499, "text": "This shows that the disk drive is represented by /dev/sda itself divided into 2 partitions, represented by /dev/sda1 and /dev/sda2. The following would be the output for the same system if we attach second hard disk drive." }, { "code": null, "e": 2774, "s": 2722, "text": "# ls /dev/sd*\n/dev/sda /dev/sda1 /dev/sda2 /dev/sdb" }, { "code": null, "e": 2938, "s": 2774, "text": "As shown above, the new hard drive has been assigned to the device file /dev/sdb. Currently, the drive has no partitions shown (because we have yet to create any)." }, { "code": null, "e": 3123, "s": 2938, "text": "At this point, we have a choice of creating partitions and file systems on the new drive and mounting them for access or adding the disk as a physical volume as part of a volume group." }, { "code": null, "e": 3315, "s": 3123, "text": "The next step is to create one or more Linux partitions on the new disk drive. This is achieved using the fdisk utility which takes as a command-line argument on the device to be partitioned." }, { "code": null, "e": 4511, "s": 3315, "text": "# fdisk /dev/sdb\nThe Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel Building a new DOS disklabel with disk identifier 0xd1082b01.\nChanges will remain in memory only, until you decide to write them.\nAfter that, of course, the previous content won't be recoverable.\nWarning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)\nWARNING: DOS-compatible mode is deprecated. It's\nstrongly recommended to switch off the mode (command 'c') and change display units to\nsectors (command 'u').\nCommand (m for help):\nAs instructed, switch off DOS compatible mode and change the units to sectors by entering the c and u commands:\nCommand (m for help): c\nDOS Compatibility flag is not set\nCommand (m for help): u\nChanging display/entry units to sectors\nIn order to view the current partitions on the disk enter the p command:\nCommand (m for help): p\nDisk /dev/sdb: 34.4 GB, 34359738368 bytes\n255 heads, 63 sectors/track, 4177 cylinders\nUnits = cylinders of 16065 * 512 = 8225280 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisk identifier: 0xd1082b01\nDevice Boot Start End Blocks Id System" }, { "code": null, "e": 4788, "s": 4511, "text": "As we can see from the above, the fdisk output of the disk currently has no partitions because it is a previously unused disk. The next step is to create a new partition on the disk, a task which is performed by entering “n” (for new partition) and “p” (for primary partition)" }, { "code": null, "e": 4907, "s": 4788, "text": "Command (m for help): n\nCommand action\n e extended\n p primary partition (1-4)\n p \nPartition number (1-4):" }, { "code": null, "e": 5353, "s": 4907, "text": "In this example, we only plan to create one partition which will be partition 1. Next, we need to specify where the partition will begin and end. Since, this is the first partition, we need to start at the first available sector and as we want to use the entire disk to specify the last sector at the end. Note that, if you wish to create multiple partitions, you can specify the size of each partition by sectors, bytes, kilobytes or megabytes." }, { "code": null, "e": 5765, "s": 5353, "text": "Partition number (1-4): 1\nFirst sector (2048-67108863, default 2048):\nUsing default value 2048\nLast sector, +sectors or +size{K,M,G} (2048-67108863, default 67108863):\nUsing default value 67108863\nNow that we have specified the partition we need to write it to the disk using the w command:\nCommand (m for help): w\nThe partition table has been altered!\nCalling ioctl() to re-read partition table.\nSyncing disks." }, { "code": null, "e": 5861, "s": 5765, "text": "If we now look at the devices again we will see that the new partition is visible as /dev/sdb1:" }, { "code": null, "e": 5923, "s": 5861, "text": "# ls /dev/sd*\n/dev/sda /dev/sda1 /dev/sda2 /dev/sdb /dev/sdb1" }, { "code": null, "e": 5985, "s": 5923, "text": "The next step is to create a filesystem on our new partition." }, { "code": null, "e": 6373, "s": 5985, "text": "We now have a new disk installed, it is visible to RHEL 6 and we have configured a Linux partition on the disk. The next step is to create a Linux file system on the partition so that the operating system can use it to store files and data. The easiest way to create a file system on a partition is to use the mkfs.ext4 utility which takes as arguments the label and the partition device" }, { "code": null, "e": 7051, "s": 6373, "text": "# /sbin/mkfs.ext4 -L /backup /dev/sdb1\nmke2fs 1.41.12 (17-May-2010)\nFilesystem label=/backup\nOS type: Linux\nBlock size=4096 (log=2)\nFragment size=4096 (log=2)\nStride=0 blocks, Stripe width=0 blocks\n2097152 inodes, 8388352 blocks\n419417 blocks (5.00%) reserved for the super user\nFirst data block=0\nMaximum filesystem blocks=4294967296\n256 block groups\n32768 blocks per group, 32768 fragments per group\n8192 inodes per group\nSuperblock backups stored on blocks:\n32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,4096000, 7962624\nWriting inode tables: done\nCreating journal (32768 blocks): done\nWriting superblocks and filesystem accounting information: done" }, { "code": null, "e": 7174, "s": 7051, "text": "This filesystem checks automatically after 36 mounts or 180 days, whichever comes first. Use tune2fs -c or -i to override." }, { "code": null, "e": 7604, "s": 7174, "text": "Now that we have created a new filesystem on the Linux partition of our new disk drive, we need to mount it so that it is accessible. In order to do this we need to create a mount point. A mount point is simply a directory or folder into which the filesystem will be mounted. For the purposes of this example, we will create a /backup directory to match our filesystem label (although it is not necessary that these values match)" }, { "code": null, "e": 7620, "s": 7604, "text": "# mkdir /backup" }, { "code": null, "e": 7689, "s": 7620, "text": "The file system may then be manually mounted using the mount command" }, { "code": null, "e": 7715, "s": 7689, "text": "# mount /dev/sdb1 /backup" }, { "code": null, "e": 7834, "s": 7715, "text": "Running the mount command with no arguments shows us all currently mounted filesystems (including our new filesystem):" }, { "code": null, "e": 8399, "s": 7834, "text": "# mount\n/dev/mapper/vg_rhel6-lv_root on / type ext4 (rw)\nproc on /proc type proc (rw)\nsysfs on /sys type sysfs (rw)\ndevpts on /dev/pts type devpts (rw,gid=5,mode=620)\ntmpfs on /dev/shm type tmpfs (rw,rootcontext=\"system_u:object_r:tmpfs_t:s0\")\n/dev/sda1 on /boot type ext4 (rw)\nnone on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)\nsunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)\n/dev/sr0 on /media/RHEL_6.0 x86_64 Disc 1 type iso9660 (ro,nosuid,nodev,uhelper=udisks,uid=500,gid=500,iocharset=utf8,mode=0400,dmode=0500)\n/dev/sdb1 on /backup type ext4 (rw) " }, { "code": null, "e": 8548, "s": 8399, "text": "In order to configure the system so that the new disk is automatically mounted at the time boot we need an entry to be added to the /etc/fstab file." }, { "code": null, "e": 8664, "s": 8548, "text": "The below is the sample configuration file which shows an fstab file configured to auto mount our /backup partition" }, { "code": null, "e": 9352, "s": 8664, "text": "/dev/mapper/vg_rhel6-lv_root / ext4 defaults 1 1\nUUID=4a9886f5-9545-406a-a694-04a60b24df84 /boot ext4 defaults 1 2\n/dev/mapper/vg_rhel6-lv_swap swap swap defaults 0 0\ntmpfs /dev/shm tmpfs defaults 0 0\ndevpts /dev/pts devpts gid=5,mode=620 0 0\nsysfs /sys sysfs defaults 0 0\nproc /proc proc defaults 0 0\nLABEL=/backup /backup ext4 defaults 1 2" }, { "code": null, "e": 9568, "s": 9352, "text": "After this configuration and demo, we can add new disks to the existing Linux machine without any issues and extends the space for storing the backups with another drive with easy steps. Hope this information helps!" } ]
Bugzilla - Quick Guide
Bugzilla is an open-source tool used to track bugs and issues of a project or a software. It helps the developers and other stakeholders to keep track of outstanding problems with the product. It was written by Terry Weissman in TCL programming language in 1998. It was written by Terry Weissman in TCL programming language in 1998. Later, Bugzilla was written in PERL and it uses the MYSQL database. Later, Bugzilla was written in PERL and it uses the MYSQL database. Bugzilla can be used as a Test Management tool since it can be easily linked with other test case management tools like Quality Centre, ALM, Testlink, etc. Bugzilla can be used as a Test Management tool since it can be easily linked with other test case management tools like Quality Centre, ALM, Testlink, etc. Bugzilla provides a powerful, easy to use solution to configuration management and replication problems. Bugzilla provides a powerful, easy to use solution to configuration management and replication problems. It can dramatically increase the productivity and accountability of an individual by providing a documented workflow and positive feedback for good performance. It can dramatically increase the productivity and accountability of an individual by providing a documented workflow and positive feedback for good performance. Most commercial and defect-tracking software vendors charged enormous licensing fees in the starting days of Bugzilla. As a result, Bugzilla quickly became a favorite among the open-source users, due to its genesis in the open-source browser project with Mozilla. It is now the most precious defect-tracking system against which all the others are measured. Bugzilla puts the power in an individual’s hand to improve the value of business while providing a usable framework for natural attention to detail and knowledge store to flourish. Bugzilla has many keys as well as advanced features, which makes it unique. Following is a list of some of Bugzilla’s most significant features − Bugzilla is powerful and it has advanced searching capabilities. Bugzilla is powerful and it has advanced searching capabilities. Bugzilla supports user configurable email notifications whenever the bug status changes. Bugzilla supports user configurable email notifications whenever the bug status changes. Bugzilla displays the complete bug change history. Bugzilla displays the complete bug change history. Bugzilla provides inter bug dependency track and graphic representation. Bugzilla provides inter bug dependency track and graphic representation. Bugzilla allows users to attach Bug supportive files and manage it. Bugzilla allows users to attach Bug supportive files and manage it. Bugzilla has integrated, product-based, granular security schema that makes it more secure. Bugzilla has integrated, product-based, granular security schema that makes it more secure. It has complete security audit and runs under the Perl’s taint mode. It has complete security audit and runs under the Perl’s taint mode. Bugzilla supports a robust, stable RDBMS (Rational Data Base Management System) back end. Bugzilla supports a robust, stable RDBMS (Rational Data Base Management System) back end. It supports Web, XML, E-Mail and console interfaces. It supports Web, XML, E-Mail and console interfaces. Bugzilla has a wide range of customized, user preferences features. Bugzilla has a wide range of customized, user preferences features. It supports localized web user interface. It supports localized web user interface. Extensive configurability as it allows to be configured with other test management tools for a better user experience. Extensive configurability as it allows to be configured with other test management tools for a better user experience. Bugzilla has a smooth upgrade pathway among different versions. Bugzilla has a smooth upgrade pathway among different versions. In the next chapter, we will discuss the prerequisites for installing Bugzilla. To install and run Bugzilla on the server, the core requirement is to have Perl installed. This means that Bugzilla can be installed on any platform, where Perl can be installed; including Windows, Linux and Mac OS X. It is recommended to have a 4 GB RAM or more. It is recommended to have a 4 GB RAM or more. Should have a Fast Processor, for instance, at least 3GHz or more. Should have a Fast Processor, for instance, at least 3GHz or more. The hard disk space depends on the size of the team and the number of defects. A 50GB hard disk memory is a quite enough. The hard disk space depends on the size of the team and the number of defects. A 50GB hard disk memory is a quite enough. Bugzilla requires a database server, a web server and Perl. In all the cases, (the newer, the better) the newer releases have more bug fixes, but they are still supported and they still get security fixes from time to time. Perl − Bugzilla 4.4 and older requires Perl 5.8.1 or newer, but Bugzilla 5.0 and newer will require Perl 5.10.1 or newer. It is not recommend installing Perl 5.8.x at this stage. Instead, install Perl 5.12 or newer, as these newer versions have some useful improvements, which will give better user experience. Perl − Bugzilla 4.4 and older requires Perl 5.8.1 or newer, but Bugzilla 5.0 and newer will require Perl 5.10.1 or newer. It is not recommend installing Perl 5.8.x at this stage. Instead, install Perl 5.12 or newer, as these newer versions have some useful improvements, which will give better user experience. Database Server − Bugzilla supports MySQL, PostgreSQL, Oracle and SQLite. MySQL and PostgreSQL are highly recommended, as they have the best support from Bugzilla and are used daily by the Bugzilla developers. Oracle has several known issues and is a 2nd-class citizen. It should work decently in most cases, but may fail miserably in some cases too. SQLite is recommended for testing purposes only for small teams. If MySQL is used, version 5.0.15 is required by Bugzilla 4.x, but highly recommended version 5.5 or newer. For PostgreSQL installation, version 8.3 is required. Database Server − Bugzilla supports MySQL, PostgreSQL, Oracle and SQLite. MySQL and PostgreSQL are highly recommended, as they have the best support from Bugzilla and are used daily by the Bugzilla developers. Oracle has several known issues and is a 2nd-class citizen. It should work decently in most cases, but may fail miserably in some cases too. SQLite is recommended for testing purposes only for small teams. If MySQL is used, version 5.0.15 is required by Bugzilla 4.x, but highly recommended version 5.5 or newer. For PostgreSQL installation, version 8.3 is required. Web Server − Bugzilla has no minimum requirements for its web server. It is recommended to install Apache 2.2, although Bugzilla works fine with IIS too (IIS 7 or higher recommended). To improve performances in Apache, recommend to enable its mod_perl module. Web Server − Bugzilla has no minimum requirements for its web server. It is recommended to install Apache 2.2, although Bugzilla works fine with IIS too (IIS 7 or higher recommended). To improve performances in Apache, recommend to enable its mod_perl module. The Bugzilla GIT website is the best way to get Bugzilla. Download and install GIT from the website − https://git-scm.com/download and Run it. git clone --branch release-X.X-stable https://github.com/bugzilla/bugzilla C:\bugzilla Where, "X.X" is the 2-digit version number of the stable release of Bugzilla (e.g. 5.0) The another way to download Bugzilla is from the following link − https://www.bugzilla.org/download/ and move down to the Stable Release section and select the latest one from the list as shown in the following screenshot. Click on Download Bugzilla 5.0.3. Bugzilla comes as a 'tarball' (.tar.gz extension), which any competent Windows archiving tool should be able to open. Bugzilla requires a number of Perl modules to be installed. Some of them are mandatory, and some others, which enable additional features, are optional. In ActivePerl, these modules are available in the ActiveState repository, and are installed with the ppm tool. Either it can use it on the command line or just type ppm and the user will get a GUI. Install the following mandatory modules with the following command. ppm install <modulename> Some of the most important PERL modules have been described below. CGI.pm − It is an extensively used Perl module for programming the CGI (Common Gateway Interface) web applications. It helps to provide a consistent API for receiving and processing user inputs. CGI.pm − It is an extensively used Perl module for programming the CGI (Common Gateway Interface) web applications. It helps to provide a consistent API for receiving and processing user inputs. Digest-SHA − The Digest-SHA1 module allows you to use the NIST SHA-1 message digest algorithm from within the Perl programs. The algorithm takes as input a message of arbitrary length and produces as output a 160-bit "fingerprint" or "message digest" of the input. Digest-SHA − The Digest-SHA1 module allows you to use the NIST SHA-1 message digest algorithm from within the Perl programs. The algorithm takes as input a message of arbitrary length and produces as output a 160-bit "fingerprint" or "message digest" of the input. TimeDate − TimeDate is a class for the representation of time/date combinations, and is part of the Perl TimeDate project. TimeDate − TimeDate is a class for the representation of time/date combinations, and is part of the Perl TimeDate project. DateTime − DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project. DateTime − DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project. DateTime-TimeZone − This class is the base class for all time zone objects. A time zone is represented internally as a set of observances, each of which describes the offset from GMT for a given time period. DateTime-TimeZone − This class is the base class for all time zone objects. A time zone is represented internally as a set of observances, each of which describes the offset from GMT for a given time period. DBI − It is the standard database interface module for Perl. It defines a set of methods, variables and conventions that provide a consistent database interface independent of the actual database being used. DBI − It is the standard database interface module for Perl. It defines a set of methods, variables and conventions that provide a consistent database interface independent of the actual database being used. Template-Toolkit − The Template Toolkit is a collection of Perl modules, which implement a fast, flexible, powerful and extensible template processing system. It can be used for processing any kind of text documents and is input-agnostic. Template-Toolkit − The Template Toolkit is a collection of Perl modules, which implement a fast, flexible, powerful and extensible template processing system. It can be used for processing any kind of text documents and is input-agnostic. Email-Sender − The Email-Sender replaces the old and problematic email send library, which did a decent job at handling the simple email sending tasks, but it was not suitable for serious use for a several reasons. Email-Sender − The Email-Sender replaces the old and problematic email send library, which did a decent job at handling the simple email sending tasks, but it was not suitable for serious use for a several reasons. Email-MIME − This is an extension of the Email-Simple module. It is majorly used to handle MIME encoded messages. It takes a message as a string, splits it into its constituent parts and allows you to access the different parts of the message. Email-MIME − This is an extension of the Email-Simple module. It is majorly used to handle MIME encoded messages. It takes a message as a string, splits it into its constituent parts and allows you to access the different parts of the message. URI − A Uniform Resource Identifier is a compact string of characters that identifies an abstract or physical resource. A URI can be further classified as either a Uniform Resource Locator (URL) or a Uniform Resource Name (URN). URI − A Uniform Resource Identifier is a compact string of characters that identifies an abstract or physical resource. A URI can be further classified as either a Uniform Resource Locator (URL) or a Uniform Resource Name (URN). List-MoreUtils − It provides some trivial but commonly needed functionality on lists, which is not going to go into the List-Util module. List-MoreUtils − It provides some trivial but commonly needed functionality on lists, which is not going to go into the List-Util module. Math-Random-ISAAC − The ISAAC (Indirection, Shift, Accumulate, Add, and Count) algorithm is designed to take some seed information and produce seemingly random results as the output. Math-Random-ISAAC − The ISAAC (Indirection, Shift, Accumulate, Add, and Count) algorithm is designed to take some seed information and produce seemingly random results as the output. File-Slurp − This module provides subs that allow you to read or write files with one simple call. They are designed to be simple, have flexible ways to pass in or get the file content and are very efficient. File-Slurp − This module provides subs that allow you to read or write files with one simple call. They are designed to be simple, have flexible ways to pass in or get the file content and are very efficient. JSON-XS − This module converts the Perl data structures to JSON and vice versa. The primary goal of JSON-XS is to be correct and its secondary goal is to be fast. JSON-XS − This module converts the Perl data structures to JSON and vice versa. The primary goal of JSON-XS is to be correct and its secondary goal is to be fast. Win32 − The Win32 module contains functions to access Win32 APIs. Win32 − The Win32 module contains functions to access Win32 APIs. Win32-API − With this module, you can import and call arbitrary functions from the Win32's Dynamic Link Libraries (DLL), without having to write an XS extension. Win32-API − With this module, you can import and call arbitrary functions from the Win32's Dynamic Link Libraries (DLL), without having to write an XS extension. DateTime-TimeZone-Local-Win32 − This module provides methods for determining the local time zone on a Windows platform. DateTime-TimeZone-Local-Win32 − This module provides methods for determining the local time zone on a Windows platform. The following modules enable various optional Bugzilla features; try to install these based on your requirements − GD − The GD module is only required if you want graphical reports. GD − The GD module is only required if you want graphical reports. Chart − This module is only required if you would want graphical reports as the GD module. Chart − This module is only required if you would want graphical reports as the GD module. Template-GD − This module has the template toolkit for the template plugins. Template-GD − This module has the template toolkit for the template plugins. GDTextUtil − This module has the text utilities for use with the GD. GDTextUtil − This module has the text utilities for use with the GD. GDGraph − It is a Perl5 module to create charts using the GD module. GDGraph − It is a Perl5 module to create charts using the GD module. MIME-tools − MIME-tools is a collection of Perl5 MIME modules for parsing, decoding and generating single or multipart (even nested multipart) MIME messages. MIME-tools − MIME-tools is a collection of Perl5 MIME modules for parsing, decoding and generating single or multipart (even nested multipart) MIME messages. libwww-perl − The World Wide Web library for Perl is also called as the libwww-perl. It is a set of Perl modules, which give Perl programming an easy access to send requests to the World Wide Web. libwww-perl − The World Wide Web library for Perl is also called as the libwww-perl. It is a set of Perl modules, which give Perl programming an easy access to send requests to the World Wide Web. XML-Twig − It is a Perl module used to process XML documents efficiently. This module offers a tree-oriented interface to a document while still allowing the processing of documents of any size. XML-Twig − It is a Perl module used to process XML documents efficiently. This module offers a tree-oriented interface to a document while still allowing the processing of documents of any size. PatchReader − This module has various utilities to read and manipulate patches and CVS. PatchReader − This module has various utilities to read and manipulate patches and CVS. perl-ldap − It is a collection of modules that implements LDAP services API for Perl programs. This module may be used to search directories or perform maintenance functions such as adding, deleting or modifying entries. perl-ldap − It is a collection of modules that implements LDAP services API for Perl programs. This module may be used to search directories or perform maintenance functions such as adding, deleting or modifying entries. Authen-SASL − This module provides an implementation framework that all protocols should be able to share. Authen-SASL − This module provides an implementation framework that all protocols should be able to share. Net-SMTP-SSL − This module provides the SSL support for Net-SMTP 1.04 Net-SMTP-SSL − This module provides the SSL support for Net-SMTP 1.04 RadiusPerl − This module provides simple Radius client facilities. RadiusPerl − This module provides simple Radius client facilities. SOAP-Lite − This module is a collection of Perl modules, which provide a simple and lightweight interface to the Simple Object Access Protocol (SOAP) on both the client and the server side. SOAP-Lite − This module is a collection of Perl modules, which provide a simple and lightweight interface to the Simple Object Access Protocol (SOAP) on both the client and the server side. XMLRPC-Lite − This Perl module provides a simple interface to the XML-RPC protocol both on client and server side. XMLRPC-Lite − This Perl module provides a simple interface to the XML-RPC protocol both on client and server side. JSON-RPC − A set of modules that implement the JSON RPC 2.0 protocols. JSON-RPC − A set of modules that implement the JSON RPC 2.0 protocols. Test-Taint − This module has Tools to test taintedness. Test-Taint − This module has Tools to test taintedness. HTML-Parser − This module defines a class HTMLParser, which serves as the basis for parsing text files formatted in HTML and XHTML. HTML-Parser − This module defines a class HTMLParser, which serves as the basis for parsing text files formatted in HTML and XHTML. HTML-Scrubber − This module helps to sanitize of scrub the html input in a reliable and flexible fashion. HTML-Scrubber − This module helps to sanitize of scrub the html input in a reliable and flexible fashion. Encode − This module provides an interface between Perl's strings and the rest of the system. Encode − This module provides an interface between Perl's strings and the rest of the system. Encode-Detect − This module is an Encode-Encoding subclass that detects the encoding of data. Encode-Detect − This module is an Encode-Encoding subclass that detects the encoding of data. Email-Reply − This module helps in replying to an email or a message. Email-Reply − This module helps in replying to an email or a message. HTML-FormatText-WithLinks − This module takes HTML and turns it into plain text, but prints all the links in the HTML as footnotes. HTML-FormatText-WithLinks − This module takes HTML and turns it into plain text, but prints all the links in the HTML as footnotes. TheSchwartz − This module is a reliable job queue system. TheSchwartz − This module is a reliable job queue system. Daemon-Generic − This module provides a framework for starting, stopping, reconfiguring daemon-like programs. Daemon-Generic − This module provides a framework for starting, stopping, reconfiguring daemon-like programs. mod_perl − This module helps in embedding a Perl interpreter into the Apache server. mod_perl − This module helps in embedding a Perl interpreter into the Apache server. Apache-SizeLimit − This module allows you to kill the Apache httpd processes, if they grow too large. Apache-SizeLimit − This module allows you to kill the Apache httpd processes, if they grow too large. File-MimeInfo − This module is used to determine the mime type of a file. File-MimeInfo − This module is used to determine the mime type of a file. IO-stringy − This toolkit mainly provides modules for performing both traditional and object-oriented (i/o) on things other than normal filehandles. IO-stringy − This toolkit mainly provides modules for performing both traditional and object-oriented (i/o) on things other than normal filehandles. Cache-Memcached − This module is a client library for the memory cache daemon (memcached). Cache-Memcached − This module is a client library for the memory cache daemon (memcached). Text-Markdown − This module is a text-to-HTML filter; it translates an easy-to-read / easy-to-write structured text format into HTML. Text-Markdown − This module is a text-to-HTML filter; it translates an easy-to-read / easy-to-write structured text format into HTML. File-Copy-Recursive − This module is a Perl extension for recursively copying files and directories. File-Copy-Recursive − This module is a Perl extension for recursively copying files and directories. In Strawberry Perl, use the cpanm script to install modules. Some of the most important modules are already installed by default. The remaining ones can be installed using the following command − cpanm -l local <modulename> The list of modules to install will be displayed by using the checksetup.pl command. The Bugzilla installation requires several technical aspects to start with. A few websites provide the Bugzilla web application – Landfill: The Bugzilla Test Server is one of these. https://landfill.bugzilla.org/bugzilla-2.16.11/ this is the testing and demonstration website. Note − Landfill is a home for test installations of the Bugzilla bug-tracking system. If you are evaluating Bugzilla, you can use them to try it. They are also useful if you are a developer and want to try to reproduce a bug that somebody has reported. Once you navigate to the above-mentioned URL, the Bugzilla home page will display as shown below − The process of creating an account is similar to any other web based application like Facebook, Gmail, etc. Following are the steps to create an account − Step 1 − Go to https://landfill.bugzilla.org/bugzilla-5.0-branch/ Step 2 − On the Bugzilla home page, click the New Account link placed on the header as shown in the following screenshot. Step 3 − Enter the email address and click on Send. Step 4 − Within moments, the user will receive an email to the given address. This Email should have a login name and a URL to confirm the registration. Step 5 − Once the registration is confirmed, Bugzilla will ask the real name (optional, but recommended) and ask the user to type their password and confirm their password. Depending on how Bugzilla is configured, there may be minimum complexity requirements for the password. Step 6 − Once the details are filled, click on Create, a successful message of account creation displays on the screen, else it will display an error message. Correct the error and then click on Create. To login into Bugzilla, we have to follow the steps given below. Step 1 − Click on the Log In link on the header of the homepage. Step 2 − Enter the Email Address, Password and click on Log In Step 3 − The user will be logged in successfully; the users can see their user id in the header section. Step 4 − The user can see open bugs assigned to him, reported by him and requests addressed to him at the left bottom section. The procedure of filling a new bug is quite simple and has been explained below. Step 1 − Click on the ‘New’ link, present on the header or the footer or Click on the File a Bug button on the home page as shown in the following screenshot. Step 2 − Now, select the product group in which the bug is noticed. Step 3 − After selecting the Product, a form will appear where the user should enter the following details related to the bug − Enter Product Enter Component Give Component description Select version Select severity Select Hardware Select OS Enter Summary Enter Description Attach Attachment Note − The above fields vary as per the customization of Bugzilla. The Mandatory fields are marked with a red asterisk (*). Step 5 − Once the user starts typing in the Summary, Bugzilla filters the already logged in defects and displays the list to avoid duplicate bugs. Step 6 − Click on the Submit Bug button to log the bug. Step 7 − As soon as the user clicks on the Submit bug button, a Bug Id is generated with the details that of bug as that were entered. Step 8 − The Deadline and the Status will be shown as depicted in the following screenshot. A user can also add additional information to the assigned bug like URL, keywords, whiteboard, tags, etc. This extra-information is helpful to give more details about the Bug that is created. Large text box URL Whiteboard Keywords Tags Depends on Blocks In the next chapter, we will learn how a bug can be cloned. Bugzilla has the provision of "Cloning" an existing bug. The newly created bug keeps most of the settings from the old bug. This helps in tracking similar concerns that require different handling in a new bug. To use this, go to the bug that user wants to clone. Then click on the “Clone This Bug” link on the footer of the bug page as shown in the screenshot below. After clicking on clone the bug link, the page will navigate the user to the Product group selection page. Once on the selection page, the user has to select a product. Enter the Bug page that is filled with the values same as the old bug has. The User can change the values and/or text if needed. Then, click on Submit Bug. Bug is logged successfully with dependency details. The main feature or the heart of Bugzilla is the page that displays details of a bug. Note that the labels for most fields are hyperlinks; clicking them will take to context-sensitive help of that particular field. Fields marked * may not be present on every installation of Bugzilla. Summary − It is a one-sentence summary of the problem, which is displayed in the header next to the bug number. It is similar to the title of the bug that gives the user an overview of the bug. Summary − It is a one-sentence summary of the problem, which is displayed in the header next to the bug number. It is similar to the title of the bug that gives the user an overview of the bug. Status (and Resolution) − These define status of the bug – It starts with even before being confirmed as a bug, then being fixed and the fix being confirmed by Quality Assurance. The different possible values for Status and Resolution on installation should be documented in the context-sensitive help for those items. Status supports Unconfirmed, Confirmed, Fixed, In Process, Resolved, Rejected, etc. Status (and Resolution) − These define status of the bug – It starts with even before being confirmed as a bug, then being fixed and the fix being confirmed by Quality Assurance. The different possible values for Status and Resolution on installation should be documented in the context-sensitive help for those items. Status supports Unconfirmed, Confirmed, Fixed, In Process, Resolved, Rejected, etc. Alias − An Alias is a unique short text name for the bug, which can be used instead of the bug number. It provides the unique identifiers and help to find the bug in case of Bug ID is not handy. It can be useful while searching for a bug. Alias − An Alias is a unique short text name for the bug, which can be used instead of the bug number. It provides the unique identifiers and help to find the bug in case of Bug ID is not handy. It can be useful while searching for a bug. Product and Component − Bugs are divided by Products and Components. A Product may have one or more Components in it. It helps to categorize the bugs and helps in segregating them as well. Product and Component − Bugs are divided by Products and Components. A Product may have one or more Components in it. It helps to categorize the bugs and helps in segregating them as well. Version − The "Version" field usually contains the numbers or names of the released versions of the product. It is used to indicate the version(s) affected by the bug report. Version − The "Version" field usually contains the numbers or names of the released versions of the product. It is used to indicate the version(s) affected by the bug report. Hardware (Platform and OS) − These indicate the tested environment or the operating system, where the bug was found. It also gives out the details of the hardware like RAM, Hard Disk Size, Processor, etc. Hardware (Platform and OS) − These indicate the tested environment or the operating system, where the bug was found. It also gives out the details of the hardware like RAM, Hard Disk Size, Processor, etc. Importance (Priority and Severity) − The Priority field is used to prioritize bugs. It can be updated by the assignee, business people or someone else from stakeholders with the authority to change. It is a good idea not to change this field on other bugs, which are not raised by a person. The default values are P1 to P5. Importance (Priority and Severity) − The Priority field is used to prioritize bugs. It can be updated by the assignee, business people or someone else from stakeholders with the authority to change. It is a good idea not to change this field on other bugs, which are not raised by a person. The default values are P1 to P5. Severity Field − The Severity field indicates how severe the problem is—from blocker ("application unusable") to trivial ("minor cosmetic issue"). User can also use this field to indicate whether a bug is an enhancement or future request. The common supportive severity statuses are – Blocker, Critical, Major, Normal, Minor, Trivial and enhancement. Severity Field − The Severity field indicates how severe the problem is—from blocker ("application unusable") to trivial ("minor cosmetic issue"). User can also use this field to indicate whether a bug is an enhancement or future request. The common supportive severity statuses are – Blocker, Critical, Major, Normal, Minor, Trivial and enhancement. Target Milestone − It is a future date by which the bug is to be fixed. Example – The Bugzilla Project's milestones for future Bugzilla versions are 4.4, 5.0, 6.0, etc. Milestones are not restricted to numbers though the user can use any text strings such as dates. Target Milestone − It is a future date by which the bug is to be fixed. Example – The Bugzilla Project's milestones for future Bugzilla versions are 4.4, 5.0, 6.0, etc. Milestones are not restricted to numbers though the user can use any text strings such as dates. Assigned To − A Bug is assigned to a person who is responsible to fix the bug or can check the credibility of the bug based on the business requirement. Assigned To − A Bug is assigned to a person who is responsible to fix the bug or can check the credibility of the bug based on the business requirement. QA Contact − The person responsible for quality assurance on this bug. It may be the reporter of the bug to provide more details if required or can be contacted for retest the defect once it is fixed. QA Contact − The person responsible for quality assurance on this bug. It may be the reporter of the bug to provide more details if required or can be contacted for retest the defect once it is fixed. URL − A URL associated with the bug, if any. URL − A URL associated with the bug, if any. Whiteboard − A free-form text area for adding short notes, new observations or retesting comments and tags to a bug. Whiteboard − A free-form text area for adding short notes, new observations or retesting comments and tags to a bug. Keywords − The administrator can define keywords that can be used to tag and categories bugs — for e.g. crash or regression. Keywords − The administrator can define keywords that can be used to tag and categories bugs — for e.g. crash or regression. Personal Tags − Keywords are global and visible by all users, while Personal Tags are personal and can only be viewed and edited by their author. Editing those tags will not send any notifications to other users. These tags are used to keep track of bugs that a user personally cares about, using their own classification system. Personal Tags − Keywords are global and visible by all users, while Personal Tags are personal and can only be viewed and edited by their author. Editing those tags will not send any notifications to other users. These tags are used to keep track of bugs that a user personally cares about, using their own classification system. Dependencies (Depends On and Blocks) − If a bug cannot be fixed as some other bugs are opened (depends on) or this bug stops other bugs for being fixed (blocks), their numbers are recorded here. Dependencies (Depends On and Blocks) − If a bug cannot be fixed as some other bugs are opened (depends on) or this bug stops other bugs for being fixed (blocks), their numbers are recorded here. Clicking on the Dependency tree link shows the dependency relationships of the bug as a tree structure. A user can change how much depth to show and hide the resolved bugs from this page. A user can also collapse/expand dependencies for each non-terminal bug on the tree view, using the [-] / [+] buttons that appear before the summary. Reported − It is the Time and Date when the bug is logged by a person in the system. Reported − It is the Time and Date when the bug is logged by a person in the system. Modified − It is the Date and Time when the bug was last changed in the system. Modified − It is the Date and Time when the bug was last changed in the system. CC List − A list of people who get mail when the bug changes, in addition to the Reporter, Assignee and QA Contact (if enabled). CC List − A list of people who get mail when the bug changes, in addition to the Reporter, Assignee and QA Contact (if enabled). Ignore Bug Mail − A user can check this field if he never wants to get an email notification from this bug. Ignore Bug Mail − A user can check this field if he never wants to get an email notification from this bug. See Also − Bugs, in this Bugzilla, other Bugzilla or other bug trackers those are related to this one. See Also − Bugs, in this Bugzilla, other Bugzilla or other bug trackers those are related to this one. Flags − A flag is a kind of status that can be set on bugs or attachments to indicate that the bugs/attachments are in a certain state. Each installation can define its own set of flags that can be set on bugs or attachments. Flags − A flag is a kind of status that can be set on bugs or attachments to indicate that the bugs/attachments are in a certain state. Each installation can define its own set of flags that can be set on bugs or attachments. Time Tracking − This form can be used for time tracking. To use this feature, a user has to be a member of the group specified by the timetrackinggroup parameter. Time Tracking − This form can be used for time tracking. To use this feature, a user has to be a member of the group specified by the timetrackinggroup parameter. Orig. Est. − This field shows the original estimated time. Orig. Est. − This field shows the original estimated time. Current Est. − This field shows the current estimated time. This number is calculated from Hours Worked and Hours Left. Current Est. − This field shows the current estimated time. This number is calculated from Hours Worked and Hours Left. Hours Worked − This field shows the number of hours worked on the particular defect. Hours Worked − This field shows the number of hours worked on the particular defect. Hours Left − This field shows the Current Est. - Hours Worked. This value + Hours Worked will become the new Current Estimated. Hours Left − This field shows the Current Est. - Hours Worked. This value + Hours Worked will become the new Current Estimated. %Complete − This field shows how much percentage of the task is complete. %Complete − This field shows how much percentage of the task is complete. Gain − This field shows the number of hours the bug is ahead of the Original Estimated. Gain − This field shows the number of hours the bug is ahead of the Original Estimated. Deadline − This field shows the deadline for this bug. Deadline − This field shows the deadline for this bug. Attachments − A user can attach files (evidence, test cases or patches) to bugs. If there are any attachments, they are listed in this section. Attachments − A user can attach files (evidence, test cases or patches) to bugs. If there are any attachments, they are listed in this section. Additional Comments − A user can add comments to the bug discussion here, if user/tester has something worthwhile to say. Additional Comments − A user can add comments to the bug discussion here, if user/tester has something worthwhile to say. In the next chapter, we will learn how to edit a bug. Bugzilla has a provision of editing an existing bug. A user can edit a bug during the lifecycle of any bug. Most of the fields have an edit hyperlink. It depends on administrator of Bugzilla to provide edit options with different fields. In the following screenshot, there are many fields that have an edit hyperlink such as – Status, Alias, Assignee, QA Contact, ‘Depends on’, Large Text box, Flags, CC list, etc. Click on the edit hyperlink of a particular field, that field will display as editable and the user can edit the field accordingly. After the editing is done, click on Save Changes button, which is on the top right hand corner of the page as shown in the screenshot below. After the changes are successfully done, the advisory will display of the bug details as shown in the following screenshot. A report helps to analyse the current state of the bug. The purpose of a Defect Report is to see the behaviour, communication, analysis and the current stage of a defect at any stage of the defect lifecycle. Defect reports are even useful after closing the defect and analysis the product and development quality. Following are some of the important points to consider regarding the various Bugzilla reports. Bugzilla supports those Tabular Reports that have HTML or CSV reports. Bugzilla supports those Tabular Reports that have HTML or CSV reports. Tabular reports can be viewed in 1-Dimensional, 2-Dimensional or 3-Dimensional ways. Tabular reports can be viewed in 1-Dimensional, 2-Dimensional or 3-Dimensional ways. The most common type of report supported by Bugzilla are the Graphical Reports. The most common type of report supported by Bugzilla are the Graphical Reports. Graphical Reports contain line graph, bar and pie charts. Graphical Reports contain line graph, bar and pie charts. Report functionality is based on Search and filter concept, for which the conditions are given by users. Report functionality is based on Search and filter concept, for which the conditions are given by users. The user provides his preference of vertical and horizontal axis to plot graphs, charts or tables along with filter criteria’s like Project, Component, Defect Status, etc. The user provides his preference of vertical and horizontal axis to plot graphs, charts or tables along with filter criteria’s like Project, Component, Defect Status, etc. The user can even choose 3-D reports for tables and images. The user can even choose 3-D reports for tables and images. For navigating the reports section in Bugzilla, we should follow the steps given below. Step 1 − Click on the Reports link in the header of the homepage. Step 2 − Bugzilla displays the Reporting and Charting Kitchen page. It has two sections to generate different type of reports – Tabular Reports and Graphical Reports. Other links like − Search − It will navigate the user to the standard search page. Search − It will navigate the user to the standard search page. Duplicate − It will display the most frequently reported bugs. Duplicate − It will display the most frequently reported bugs. In the next chapter, we will understand what graphical reports are and how to generate them. Graphical reports are a group of line, bar and pie charts. These Reports are helpful in many ways, for example if a user wants to know which component has the maximum number of defects reported and wants to represent in the graph, then that user can select from the following two options − Severity on the X-axis Component on the Y-axis Then click on Generate Report. It will generate a report with crucial information. Similarly, the user can a select number of combinations from those that are available. To generate graphical reports in Bugzilla, we have to follow the steps given below. Step 1 − To begin with, click on the Reports link at the header of the homepage. Step 2 − Click on the Graphical Reports hyperlink, which is listed under the Current State section as shown in the following screenshot. Step 3 − Now, set various options to present reports graphically. Some of the important options are given below. Vertical Axis Horizontal Axis Multiple Images Format- Line graph, Bar chart or Pie chart Plot data set Classify your bug Classify your product Classify your component Classify bug status Select resolution Step 4 − Click on Generate Report to display a Bar chart, where the Severity of a bug is the vertical axis, while the Component “Widget Gears” is the horizontal axis. Step 5 − Similarly, a Line Graph can be created for % Complete Vs Deadline. The result for the above mentioned line graph will be as follows. The Tabular Reports represent tables of bug counts in 1, 2 or 3 dimensions as HTML or CSV. To generate Tabular reports in Bugzilla, we have to follow the steps given below. Step 1 − Click on the Reports hyperlink in the Header section of the homepage and then click on the Tabular Reports in the Current State section as shown in the following screenshot. Step 2 − Similar to Graphical Reports, select Vertical, Horizontal axis along with Multiple tables (if required) and provide details in the other fields. Step 3 − After selecting all the fields, click on Generate Report. Based on the deadlines, it generates multiple tables − Step 4 − By clicking on CSV hyperlink below the table, it converts the report into a CSV file. Click OK after the appropriate selection, it will open an Excel sheet with the details of all the data tables. In Bugzilla, Duplicates are a list of bugs, which are raised most frequently. Duplicates are the most frequently seen open bugs. Duplicates are the most frequently seen open bugs. Duplicates count the numbers as the Dupe Count of direct and indirect duplicates of a defect report. This information is helpful to minimize the number of duplicate defects. Duplicates count the numbers as the Dupe Count of direct and indirect duplicates of a defect report. This information is helpful to minimize the number of duplicate defects. Duplicates help to save time for QA engineers to log a new defect always. Duplicates help to save time for QA engineers to log a new defect always. Duplicates also help stakeholders to find out the root cause, if the same defects are reopened repeatedly rather than just a new defect. Duplicates also help stakeholders to find out the root cause, if the same defects are reopened repeatedly rather than just a new defect. Review the most frequent bug list with the respective issue noticed. If the problem is listed as a bug in the list, then click on the bug id to view details and confirm whether it is the same issue or not. Comment on the additional observation, link it with your Test Case if required and re-open if it is closed. If the exact problem is not listed, try to find a similar defect that is already listed. If the user finds the defect that are dependent on new observations, he can comment and link the defect. If the user cannot find the defect, log a new one. To generate Duplicate reports in Bugzilla, we have to follow the steps given below. Step 1 − Click on the Report hyperlink in the header of the homepage. Step 2 − As soon as you click on Report, the Reporting and Charting Kitchen page opens. Click on Duplicates hyperlink under the Current State section. Step 3 − By clicking on Duplicates, open the Most Frequently Reported Bugs table. It has various columns as Bug Id, Dupe Count, Component, Severity, Priority, Target Milestone, and Summary. This is an interesting feature to filter or customize the Most Frequently Reported Bug tables. Following are some of the important pointers, which are explained in detail. Restrict to product − It filters out the table based on specific Product and components. The user can choose from single or multiple products by pressing CTRL + Click. Restrict to product − It filters out the table based on specific Product and components. The user can choose from single or multiple products by pressing CTRL + Click. When sorting or restricting, work with − It has two options, either the entire list or the currently visible list. When sorting or restricting, work with − It has two options, either the entire list or the currently visible list. Max Rows − The user can give a number to see the number of defects in one page. Max Rows − The user can give a number to see the number of defects in one page. Change column is change in last − The number of days a user wants to review the changes that have taken place. Change column is change in last − The number of days a user wants to review the changes that have taken place. Open Bugs only − This will filter out all the bugs those are closed. The result will have a list of only open defects. Open Bugs only − This will filter out all the bugs those are closed. The result will have a list of only open defects. When the user Clicks on the Change button, all these filters will change and the bug list will be filtered out. When clicking on the Bug List button at “Or just give this to me as a Bug List”, the resulting table will display in the format of a Bug List page as shown in the screenshot below − The Browse Function is one of the most important features of Bugzilla to find/trace/locate an existing logged bug. Following are steps to use this feature − Step 1 − Click on the Browse hyperlink on the header of the home page. Step 2 − A window – "Select a product category to browse" as shown below, the user can browse the bug according to the category. Select the product "Sam's Widget" or any other. Step 3 − It opens another window, in this – click on the component Widget Gears. Bugzilla Components are sub-sections of a product. For example, here, the product is SAM'S WIDGET, whose component is WIDGET GEARS. A product can have multiple components listed. Step 4 − When you click on the component, it will open another window. All the Bugs created under a particular category will be listed over here. From that Bug-list, click on the Bug# ID to see more details about that bug. Step 5 − Once you click on the Bug ID, another window will open, where information about the bug can be seen in detail. In the same window, the user can also change the assignee, QA contact or the CC list. The Simple Search feature is useful in finding a specific bug. It works like the web search engines such as Google, Bing, Yahoo, etc. The user needs to enter some keywords and then search. Following are steps for using the simple search feature − Step 1 − Click on the Search hyperlink in the header of the homepage. Step 2 − Click on the Simple Search section as shown in the following screenshot. Step 3 − Choose the Status of the bug from the list to filter. Then, choose the Product from the list and enter some Keywords related to the bug. Click on the Search button. Step 4 − The result will be as shown in the following screenshot. Step 5 − At the bottom of the search page, there are various options like how to see your bug - in XML Format, in Long Format or just as a Time Summary. Apart from that, the other option can be used – like sending a mail to the bug assignee, change several bugs at once or change the column of the screen, etc. The Quick Search feature is a single-text-box query tool. It is available on the Bugzilla home page as shown in the screenshot below. The Quick Search feature uses Meta characters to indicate what is to be searched. For example, typing bug|login into Quick Search would search for "bug" or "login" in the summary and whiteboard of a bug. The user can also use it to go directly to a bug by entering its number or its alias. By clicking on the Quick Search button, it displays list of bugs as shown in the screenshot below. The Advanced Search page displays a list of all the bugs, which are filtered exactly with different criteria that have been loaded by the users. This Advanced Search feature selects different possible values for all of the fields in a bug. For some fields, multiple values can be selected. In these cases, Bugzilla returns bugs where the content of the field matches with any one of the selected values. If none is selected, then the field can take any of values. Multiple values selection for one field is based on the “OR” functionality. If either one or any other value is matched among the user selection, the bug will be displayed. For using the advanced search feature in Bugzilla, we have to follow the steps given below. Step 1 − Click on the Search hyperlink on the header of the homepage. You will get two tabs, Simple Search and Advanced Search, click on the Advanced Search tab. Step 2 − Select the required option from the Summary field. Then, you can enter the keyword to identify or filter out the bugs. Step 3 − The next step is to select the category of Bug from the Classification box; here, we have selected Widget. Then, choose the Product under which the Bug is created; here, we have selected Sam's Widget. In the Component box, we have selected Widget Gears. In the Status box, click on Confirmed and in the Resolution box choose Fixed, all of these are shown in the following screenshot. Note − All these fields are optional and dependent on the user’s choice. Step 4 − Click on the Search Button after entering all the fields based on the requirement of the filter. Step 5 − Advance Search will detect the bug and the result will be as follows − Custom Search is an extended feature of the Advanced Search. It works on the principle of – “Did not find what you are looking for above? I.e. in advanced search”. This area allows words like AND, OR, and other more complex searches. Navigation of custom search is as follows: Search → Advanced Search → Go Down and click on Custom Search as depicted in the following screenshot. Custom Search compares a selected field with a defined operator for a specified value. It is possible that too much of this could be reproduced using the standard fields in an Advanced Search option. However, the user can combine options like "Match ANY" or "Match ALL", using parentheses for combining and priority to construct searches of complex queries. There are three fields in each row (known as a "term") of a custom search − Field − The name of the field being searched. Field − The name of the field being searched. Operator − The comparison operator. Operator − The comparison operator. Value − The value to which the field is being compared. Value − The value to which the field is being compared. The list of the available fields contains all the fields defined for a bug. It includes any custom fields, as well as some other fields like the Assignee Real Name, Days since Bug Changed, Time since Assignee Touched and other things, which might be useful to search further. There is a wide range of operators available. There are various string-matching operations (including regular expressions), numerical comparisons (which also work for dates) and to search for change information of a bug. When a field changed, what it changed from or to, and who did it. There are special operators is empty and is not empty, because Bugzilla cannot tell the difference between a value field left blank on purpose and one left blank by accident. The user can have n number of rows to define operators, values and fields. There is a dropdown box above them, which defines how these rows are related with the search. Match ALL of the following separately, Match ANY of the following separately or Match ALL of the following against the same field are three options listed in the dropdown. The difference between the first and the third can be described with a comment search. If a search is − Comment contains the string – “Bug” Comment contains the string – “issue” Under the “match all of the following separately”, the search would return bugs, where a "Bug" appeared in one comment can be an "issue" in the same or any other comment. Under the “match all of the following against the same field”, both strings would need to occur in exactly the same comment, i.e. it will select a bug having both Bug and issue words in the same comment. By clicking on Show Advanced features, more capabilities or features appear to use complex and specific search. The user can negate any row by checking a checkbox. It can also group lines of the search with parentheses to determine how different search terms are related. The user gets the choice of combining them using ALL (i.e. AND) or ANY (i.e. OR). A bug list is a group of searched bugs based on the user input. A Bug list is nothing other than filtered bugs based on different conditions in a Standard Search or an Advanced Search. The format of the list is configurable. For example, it can be sorted by clicking the column headings. Other useful features can be accessed using the links at the bottom of the list, which are − Long Format XML (icon) CSV (icon) Feed (icon) iCalendar (icon) Change Columns Change Several Bugs At Once Send Mail to Bug Assignees Edit Search Remember Search as All of these features have been explained in detail below. By clicking on the Long Format button, it provides a large page with a non-editable summary of the fields of each bug. By clicking on XML (icon), it converts the bug list displayed in table format as an XML format. It converts the bug list as comma-separated values, which can be imported into a spreadsheet or an excel sheet. It displays the bug list as an Atom Feed. The user can Copy this link into their favourite feed reader. To limit the number of bugs in the feed, add a limit=n parameter to the URL. If the user is using Firefox, get an option as save the list as a live bookmark by clicking the live bookmark icon in the status bar as shown in the screenshot below. To limit the number of bugs in the feed, add a limit=n parameter to the URL. Only the first bug is displayed as a Feed. It displays the bug list as an iCalendar file. Each bug is represented as a to–do item in the imported calendar. It is supported in Outlook only. The user can access this feature only if Outlook is configured in the system. It changes the bug attributes that appear in the list. The user can customize the view of a Bug List using this option. By clicking on the Change Columns button, the following page displays the user selection. The User can select one or multiple columns from the Available Columns section. These should display in the bug list. Then click on → (right arrow) to show this selection in the Selected Columns section. Similarly, the user can deselect any of the columns from the selected columns and click on the ← (left arrow). The user can change the appearing order of the columns as well by clicking on move up and down arrow at the right hand side of the Selected Columns section. By clicking on the Change Columns button, the bug list will be customized. Else, if the user clicks on the Reset to Bugzilla Default, it will change back to the Default settings. If an account is sufficiently empowered and more than one bug appears in the bug list, Change Several Bugs At Once is displayed and easily makes the same change to all the bugs in the list – for example, changing their Priority. If more than one bug appears in the bug list and there are at least two different bug assignees, this link is displayed. By clicking on this link, Outlook opens, if it is configured or it asks to configure the Outlook to send a mail to the assignees of all bugs on the list. If the user did not get the exact results he were looking for, the user can return to the Search page through this link and make small revisions to the search parameters to get accurate results. The user can give the Search, a name and remember it; a link will appear in the page footer giving quick access to run it again later. Preferences in Bugzilla are used to customize the default settings of Bugzilla as per requirement and guidelines. It can also be called as User Preferences. There are two ways to navigate on Preferences − The first way is to click on the Preferences hyperlink in the header of the homepage. The second way is to click on the User Preferences button, which is displayed on the Welcome Page Icons. By clicking on one of the links outlined (in red color) in the following screenshot, they will display different types of Preference that can be customized by the users. Bugzilla supports the following six types of User Preferences. General Preferences Email Preferences Saved Searches Account Information API Keys Permissions In the next chapter, we will discuss regarding the General Preferences of Bugzilla. General Preferences allows changing several default settings of Bugzilla. Administrators have the power to remove preferences from this list, so the user may not see all the preferences available. To navigate to General Preferences, click on Preferences or User Preferences from the Homepage of Bugzilla. By Default, the General Preferences tab opens with different preferences as shown in the screenshot below. Each preference is very straightforward and self-explanatory. The user can easily understand the field and select the option from the list. For example – To set “Automatically Add me to CC list of bugs I change”, select Always from dropdown list. Click on Submit Changes button, which is at the bottom left hand side of the page. A successful message will appear that says – “The changes to your general preferences have been saved” as shown in the following screenshot. Similarly, other General preferences can be changed simultaneously. The Email Preferences feature in Bugzilla allows to enable or disable email notifications on specific events. In general, the users have almost complete control over how many emails Bugzilla sends them. If the users want to receive the maximum number of emails possible, click on the Enable All Mail button. If the user does not want to receive any email from Bugzilla at all, click on the Disable All Mail button. To navigate, go to Preferences/User Preferences option on the home screen and click on the Email Preferences tab. There are two Global Options; where the user can check the checkboxes based on their requirement to get emails. These options are − Email me when someone asks me to set a flag and Email me when someone sets a flag I asked for. These define how a user wants to receive the bug emails concerning the flags. Their use is quite straightforward: enable the checkboxes, if the user wants Bugzilla to send a mail under either of the above conditions. Similarly, a user can check the checkboxes for Field/recipient specific options based on “I want to receive mail when” Bugzilla has a feature called as User Watching. When the user enters one or more comma delineated other user accounts (usually email addresses) into the text entry box, the user will receive a copy of all the bug emails those other users are sent. This powerful functionality is very important and useful in case if the developers change projects or users go on a holiday. User can mention a list of bugs from those never wants to get any email notification of any kind. For this, user needs to add Bug ID(s) as a comma-separated list. User can remove a bug from the current ignored list at any time and it will re-enable email notifications for the bug. After selections are made, click on the Submit Changes button at the bottom left hand side of the page. A successful message will display as “The changes to your email preferences have been saved” as shown in the screenshot below. In this Tab, the user can view and run any Saved Searches, which are created by the user as well as any Saved Searches that other members of the group have defined in the querysharegroup. For the Saved Searches tab, go to Preferences → click on the Saved Searches tab. The user can run his bug from the Saved Searches by clicking on the RUN command as highlighted in the following screenshot. After you click on RUN, the bug list page displays as shown below − Saved Searches can be added to the page footer from this screen. If somebody is sharing a Search with a group, the sharer may choose Show in Footer by checking the checkbox of a different Saved Search. Based on the permissions, other members can choose the Show in Footer checkbox. Once all the changes and selections are made, click on the Submit Changes button, which is on the bottom left hand side of the page. A successful message “The changes to your Saved searches have been saved” will show as seen in the following screenshot. In this Tab, the users can view their account information, which were provided at the time of registration. It also provides a feature where the users can change their password. To change the account password, the following entries are required − Provide the Current password in the Password text box to verify the account. Enter a new password in the field – New password. Re-enter the new password in the Confirm new password field. A user can change the name in the ‘Your real name (optional, but encouraged)’ field. Provide an email address. Once all entries are made, click on Submit Changes as depicted in the following screenshot. A successful message is displayed as “The changes to your account information has been saved” as shown in the following screenshot. In this Tab, a user can see all the permissions, which are provided by the Admin. The Admin can have all the permissions and based on the role of the user, the admin provides different permissions to various users. In this case, a user has two permissions − canconfirm − can confirm a log. canconfirm − can confirm a log. editbugs − can edit all aspects of a bug. editbugs − can edit all aspects of a bug. Similarly, a user can view different permission names and it has a straightforward explanation to understand. Print Add Notes Bookmark this page
[ { "code": null, "e": 2438, "s": 2245, "text": "Bugzilla is an open-source tool used to track bugs and issues of a project or a software. It helps the developers and other stakeholders to keep track of outstanding problems with the product." }, { "code": null, "e": 2508, "s": 2438, "text": "It was written by Terry Weissman in TCL programming language in 1998." }, { "code": null, "e": 2578, "s": 2508, "text": "It was written by Terry Weissman in TCL programming language in 1998." }, { "code": null, "e": 2646, "s": 2578, "text": "Later, Bugzilla was written in PERL and it uses the MYSQL database." }, { "code": null, "e": 2714, "s": 2646, "text": "Later, Bugzilla was written in PERL and it uses the MYSQL database." }, { "code": null, "e": 2870, "s": 2714, "text": "Bugzilla can be used as a Test Management tool since it can be easily linked with other test case management tools like Quality Centre, ALM, Testlink, etc." }, { "code": null, "e": 3026, "s": 2870, "text": "Bugzilla can be used as a Test Management tool since it can be easily linked with other test case management tools like Quality Centre, ALM, Testlink, etc." }, { "code": null, "e": 3131, "s": 3026, "text": "Bugzilla provides a powerful, easy to use solution to configuration management and replication problems." }, { "code": null, "e": 3236, "s": 3131, "text": "Bugzilla provides a powerful, easy to use solution to configuration management and replication problems." }, { "code": null, "e": 3397, "s": 3236, "text": "It can dramatically increase the productivity and accountability of an individual by providing a documented workflow and positive feedback for good performance." }, { "code": null, "e": 3558, "s": 3397, "text": "It can dramatically increase the productivity and accountability of an individual by providing a documented workflow and positive feedback for good performance." }, { "code": null, "e": 3916, "s": 3558, "text": "Most commercial and defect-tracking software vendors charged enormous licensing fees in the starting days of Bugzilla. As a result, Bugzilla quickly became a favorite among the open-source users, due to its genesis in the open-source browser project with Mozilla. It is now the most precious defect-tracking system against which all the others are measured." }, { "code": null, "e": 4097, "s": 3916, "text": "Bugzilla puts the power in an individual’s hand to improve the value of business while providing a usable framework for natural attention to detail and knowledge store to flourish." }, { "code": null, "e": 4243, "s": 4097, "text": "Bugzilla has many keys as well as advanced features, which makes it unique. Following is a list of some of Bugzilla’s most significant features −" }, { "code": null, "e": 4308, "s": 4243, "text": "Bugzilla is powerful and it has advanced searching capabilities." }, { "code": null, "e": 4373, "s": 4308, "text": "Bugzilla is powerful and it has advanced searching capabilities." }, { "code": null, "e": 4462, "s": 4373, "text": "Bugzilla supports user configurable email notifications whenever the bug status changes." }, { "code": null, "e": 4551, "s": 4462, "text": "Bugzilla supports user configurable email notifications whenever the bug status changes." }, { "code": null, "e": 4602, "s": 4551, "text": "Bugzilla displays the complete bug change history." }, { "code": null, "e": 4653, "s": 4602, "text": "Bugzilla displays the complete bug change history." }, { "code": null, "e": 4726, "s": 4653, "text": "Bugzilla provides inter bug dependency track and graphic representation." }, { "code": null, "e": 4799, "s": 4726, "text": "Bugzilla provides inter bug dependency track and graphic representation." }, { "code": null, "e": 4867, "s": 4799, "text": "Bugzilla allows users to attach Bug supportive files and manage it." }, { "code": null, "e": 4935, "s": 4867, "text": "Bugzilla allows users to attach Bug supportive files and manage it." }, { "code": null, "e": 5027, "s": 4935, "text": "Bugzilla has integrated, product-based, granular security schema that makes it more secure." }, { "code": null, "e": 5119, "s": 5027, "text": "Bugzilla has integrated, product-based, granular security schema that makes it more secure." }, { "code": null, "e": 5188, "s": 5119, "text": "It has complete security audit and runs under the Perl’s taint mode." }, { "code": null, "e": 5257, "s": 5188, "text": "It has complete security audit and runs under the Perl’s taint mode." }, { "code": null, "e": 5347, "s": 5257, "text": "Bugzilla supports a robust, stable RDBMS (Rational Data Base Management System) back end." }, { "code": null, "e": 5437, "s": 5347, "text": "Bugzilla supports a robust, stable RDBMS (Rational Data Base Management System) back end." }, { "code": null, "e": 5490, "s": 5437, "text": "It supports Web, XML, E-Mail and console interfaces." }, { "code": null, "e": 5543, "s": 5490, "text": "It supports Web, XML, E-Mail and console interfaces." }, { "code": null, "e": 5611, "s": 5543, "text": "Bugzilla has a wide range of customized, user preferences features." }, { "code": null, "e": 5679, "s": 5611, "text": "Bugzilla has a wide range of customized, user preferences features." }, { "code": null, "e": 5721, "s": 5679, "text": "It supports localized web user interface." }, { "code": null, "e": 5763, "s": 5721, "text": "It supports localized web user interface." }, { "code": null, "e": 5882, "s": 5763, "text": "Extensive configurability as it allows to be configured with other test management tools for a better user experience." }, { "code": null, "e": 6001, "s": 5882, "text": "Extensive configurability as it allows to be configured with other test management tools for a better user experience." }, { "code": null, "e": 6065, "s": 6001, "text": "Bugzilla has a smooth upgrade pathway among different versions." }, { "code": null, "e": 6129, "s": 6065, "text": "Bugzilla has a smooth upgrade pathway among different versions." }, { "code": null, "e": 6209, "s": 6129, "text": "In the next chapter, we will discuss the prerequisites for installing Bugzilla." }, { "code": null, "e": 6427, "s": 6209, "text": "To install and run Bugzilla on the server, the core requirement is to have Perl installed. This means that Bugzilla can be installed on any platform, where Perl can be installed; including Windows, Linux and Mac OS X." }, { "code": null, "e": 6473, "s": 6427, "text": "It is recommended to have a 4 GB RAM or more." }, { "code": null, "e": 6519, "s": 6473, "text": "It is recommended to have a 4 GB RAM or more." }, { "code": null, "e": 6586, "s": 6519, "text": "Should have a Fast Processor, for instance, at least 3GHz or more." }, { "code": null, "e": 6653, "s": 6586, "text": "Should have a Fast Processor, for instance, at least 3GHz or more." }, { "code": null, "e": 6775, "s": 6653, "text": "The hard disk space depends on the size of the team and the number of defects. A 50GB hard disk memory is a quite enough." }, { "code": null, "e": 6897, "s": 6775, "text": "The hard disk space depends on the size of the team and the number of defects. A 50GB hard disk memory is a quite enough." }, { "code": null, "e": 7121, "s": 6897, "text": "Bugzilla requires a database server, a web server and Perl. In all the cases, (the newer, the better) the newer releases have more bug fixes, but they are still supported and they still get security fixes from time to time." }, { "code": null, "e": 7432, "s": 7121, "text": "Perl − Bugzilla 4.4 and older requires Perl 5.8.1 or newer, but Bugzilla 5.0 and newer will require Perl 5.10.1 or newer. It is not recommend installing Perl 5.8.x at this stage. Instead, install Perl 5.12 or newer, as these newer versions have some useful improvements, which will give better user experience." }, { "code": null, "e": 7743, "s": 7432, "text": "Perl − Bugzilla 4.4 and older requires Perl 5.8.1 or newer, but Bugzilla 5.0 and newer will require Perl 5.10.1 or newer. It is not recommend installing Perl 5.8.x at this stage. Instead, install Perl 5.12 or newer, as these newer versions have some useful improvements, which will give better user experience." }, { "code": null, "e": 8320, "s": 7743, "text": "Database Server − Bugzilla supports MySQL, PostgreSQL, Oracle and SQLite. MySQL and PostgreSQL are highly recommended, as they have the best support from Bugzilla and are used daily by the Bugzilla developers. Oracle has several known issues and is a 2nd-class citizen. It should work decently in most cases, but may fail miserably in some cases too. SQLite is recommended for testing purposes only for small teams. If MySQL is used, version 5.0.15 is required by Bugzilla 4.x, but highly recommended version 5.5 or newer. For PostgreSQL installation, version 8.3 is required." }, { "code": null, "e": 8897, "s": 8320, "text": "Database Server − Bugzilla supports MySQL, PostgreSQL, Oracle and SQLite. MySQL and PostgreSQL are highly recommended, as they have the best support from Bugzilla and are used daily by the Bugzilla developers. Oracle has several known issues and is a 2nd-class citizen. It should work decently in most cases, but may fail miserably in some cases too. SQLite is recommended for testing purposes only for small teams. If MySQL is used, version 5.0.15 is required by Bugzilla 4.x, but highly recommended version 5.5 or newer. For PostgreSQL installation, version 8.3 is required." }, { "code": null, "e": 9157, "s": 8897, "text": "Web Server − Bugzilla has no minimum requirements for its web server. It is recommended to install Apache 2.2, although Bugzilla works fine with IIS too (IIS 7 or higher recommended). To improve performances in Apache, recommend to enable its mod_perl module." }, { "code": null, "e": 9417, "s": 9157, "text": "Web Server − Bugzilla has no minimum requirements for its web server. It is recommended to install Apache 2.2, although Bugzilla works fine with IIS too (IIS 7 or higher recommended). To improve performances in Apache, recommend to enable its mod_perl module." }, { "code": null, "e": 9560, "s": 9417, "text": "The Bugzilla GIT website is the best way to get Bugzilla. Download and install GIT from the website − https://git-scm.com/download and Run it." }, { "code": null, "e": 9650, "s": 9560, "text": "git clone --branch release-X.X-stable https://github.com/bugzilla/bugzilla \nC:\\bugzilla \n" }, { "code": null, "e": 9738, "s": 9650, "text": "Where, \"X.X\" is the 2-digit version number of the stable release of Bugzilla (e.g. 5.0)" }, { "code": null, "e": 9995, "s": 9738, "text": "The another way to download Bugzilla is from the following link − https://www.bugzilla.org/download/ and move down to the Stable Release section and select the latest one from the list as shown in the following screenshot. Click on Download Bugzilla 5.0.3." }, { "code": null, "e": 10113, "s": 9995, "text": "Bugzilla comes as a 'tarball' (.tar.gz extension), which any competent Windows archiving tool should be able to open." }, { "code": null, "e": 10266, "s": 10113, "text": "Bugzilla requires a number of Perl modules to be installed. Some of them are mandatory, and some others, which enable additional features, are optional." }, { "code": null, "e": 10464, "s": 10266, "text": "In ActivePerl, these modules are available in the ActiveState repository, and are installed with the ppm tool. Either it can use it on the command line or just type ppm and the user will get a GUI." }, { "code": null, "e": 10532, "s": 10464, "text": "Install the following mandatory modules with the following command." }, { "code": null, "e": 10559, "s": 10532, "text": "ppm install <modulename> \n" }, { "code": null, "e": 10626, "s": 10559, "text": "Some of the most important PERL modules have been described below." }, { "code": null, "e": 10821, "s": 10626, "text": "CGI.pm − It is an extensively used Perl module for programming the CGI (Common Gateway Interface) web applications. It helps to provide a consistent API for receiving and processing user inputs." }, { "code": null, "e": 11016, "s": 10821, "text": "CGI.pm − It is an extensively used Perl module for programming the CGI (Common Gateway Interface) web applications. It helps to provide a consistent API for receiving and processing user inputs." }, { "code": null, "e": 11281, "s": 11016, "text": "Digest-SHA − The Digest-SHA1 module allows you to use the NIST SHA-1 message digest algorithm from within the Perl programs. The algorithm takes as input a message of arbitrary length and produces as output a 160-bit \"fingerprint\" or \"message digest\" of the input." }, { "code": null, "e": 11546, "s": 11281, "text": "Digest-SHA − The Digest-SHA1 module allows you to use the NIST SHA-1 message digest algorithm from within the Perl programs. The algorithm takes as input a message of arbitrary length and produces as output a 160-bit \"fingerprint\" or \"message digest\" of the input." }, { "code": null, "e": 11669, "s": 11546, "text": "TimeDate − TimeDate is a class for the representation of time/date combinations, and is part of the Perl TimeDate project." }, { "code": null, "e": 11792, "s": 11669, "text": "TimeDate − TimeDate is a class for the representation of time/date combinations, and is part of the Perl TimeDate project." }, { "code": null, "e": 11915, "s": 11792, "text": "DateTime − DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project." }, { "code": null, "e": 12038, "s": 11915, "text": "DateTime − DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project." }, { "code": null, "e": 12246, "s": 12038, "text": "DateTime-TimeZone − This class is the base class for all time zone objects. A time zone is represented internally as a set of observances, each of which describes the offset from GMT for a given time period." }, { "code": null, "e": 12454, "s": 12246, "text": "DateTime-TimeZone − This class is the base class for all time zone objects. A time zone is represented internally as a set of observances, each of which describes the offset from GMT for a given time period." }, { "code": null, "e": 12662, "s": 12454, "text": "DBI − It is the standard database interface module for Perl. It defines a set of methods, variables and conventions that provide a consistent database interface independent of the actual database being used." }, { "code": null, "e": 12870, "s": 12662, "text": "DBI − It is the standard database interface module for Perl. It defines a set of methods, variables and conventions that provide a consistent database interface independent of the actual database being used." }, { "code": null, "e": 13109, "s": 12870, "text": "Template-Toolkit − The Template Toolkit is a collection of Perl modules, which implement a fast, flexible, powerful and extensible template processing system. It can be used for processing any kind of text documents and is input-agnostic." }, { "code": null, "e": 13348, "s": 13109, "text": "Template-Toolkit − The Template Toolkit is a collection of Perl modules, which implement a fast, flexible, powerful and extensible template processing system. It can be used for processing any kind of text documents and is input-agnostic." }, { "code": null, "e": 13563, "s": 13348, "text": "Email-Sender − The Email-Sender replaces the old and problematic email send library, which did a decent job at handling the simple email sending tasks, but it was not suitable for serious use for a several reasons." }, { "code": null, "e": 13778, "s": 13563, "text": "Email-Sender − The Email-Sender replaces the old and problematic email send library, which did a decent job at handling the simple email sending tasks, but it was not suitable for serious use for a several reasons." }, { "code": null, "e": 14022, "s": 13778, "text": "Email-MIME − This is an extension of the Email-Simple module. It is majorly used to handle MIME encoded messages. It takes a message as a string, splits it into its constituent parts and allows you to access the different parts of the message." }, { "code": null, "e": 14266, "s": 14022, "text": "Email-MIME − This is an extension of the Email-Simple module. It is majorly used to handle MIME encoded messages. It takes a message as a string, splits it into its constituent parts and allows you to access the different parts of the message." }, { "code": null, "e": 14495, "s": 14266, "text": "URI − A Uniform Resource Identifier is a compact string of characters that identifies an abstract or physical resource. A URI can be further classified as either a Uniform Resource Locator (URL) or a Uniform Resource Name (URN)." }, { "code": null, "e": 14724, "s": 14495, "text": "URI − A Uniform Resource Identifier is a compact string of characters that identifies an abstract or physical resource. A URI can be further classified as either a Uniform Resource Locator (URL) or a Uniform Resource Name (URN)." }, { "code": null, "e": 14862, "s": 14724, "text": "List-MoreUtils − It provides some trivial but commonly needed functionality on lists, which is not going to go into the List-Util module." }, { "code": null, "e": 15000, "s": 14862, "text": "List-MoreUtils − It provides some trivial but commonly needed functionality on lists, which is not going to go into the List-Util module." }, { "code": null, "e": 15183, "s": 15000, "text": "Math-Random-ISAAC − The ISAAC (Indirection, Shift, Accumulate, Add, and Count) algorithm is designed to take some seed information and produce seemingly random results as the output." }, { "code": null, "e": 15366, "s": 15183, "text": "Math-Random-ISAAC − The ISAAC (Indirection, Shift, Accumulate, Add, and Count) algorithm is designed to take some seed information and produce seemingly random results as the output." }, { "code": null, "e": 15575, "s": 15366, "text": "File-Slurp − This module provides subs that allow you to read or write files with one simple call. They are designed to be simple, have flexible ways to pass in or get the file content and are very efficient." }, { "code": null, "e": 15784, "s": 15575, "text": "File-Slurp − This module provides subs that allow you to read or write files with one simple call. They are designed to be simple, have flexible ways to pass in or get the file content and are very efficient." }, { "code": null, "e": 15947, "s": 15784, "text": "JSON-XS − This module converts the Perl data structures to JSON and vice versa. The primary goal of JSON-XS is to be correct and its secondary goal is to be fast." }, { "code": null, "e": 16110, "s": 15947, "text": "JSON-XS − This module converts the Perl data structures to JSON and vice versa. The primary goal of JSON-XS is to be correct and its secondary goal is to be fast." }, { "code": null, "e": 16176, "s": 16110, "text": "Win32 − The Win32 module contains functions to access Win32 APIs." }, { "code": null, "e": 16242, "s": 16176, "text": "Win32 − The Win32 module contains functions to access Win32 APIs." }, { "code": null, "e": 16404, "s": 16242, "text": "Win32-API − With this module, you can import and call arbitrary functions from the Win32's Dynamic Link Libraries (DLL), without having to write an XS extension." }, { "code": null, "e": 16566, "s": 16404, "text": "Win32-API − With this module, you can import and call arbitrary functions from the Win32's Dynamic Link Libraries (DLL), without having to write an XS extension." }, { "code": null, "e": 16686, "s": 16566, "text": "DateTime-TimeZone-Local-Win32 − This module provides methods for determining the local time zone on a Windows platform." }, { "code": null, "e": 16806, "s": 16686, "text": "DateTime-TimeZone-Local-Win32 − This module provides methods for determining the local time zone on a Windows platform." }, { "code": null, "e": 16921, "s": 16806, "text": "The following modules enable various optional Bugzilla features; try to install these based on your requirements −" }, { "code": null, "e": 16988, "s": 16921, "text": "GD − The GD module is only required if you want graphical reports." }, { "code": null, "e": 17055, "s": 16988, "text": "GD − The GD module is only required if you want graphical reports." }, { "code": null, "e": 17146, "s": 17055, "text": "Chart − This module is only required if you would want graphical reports as the GD module." }, { "code": null, "e": 17237, "s": 17146, "text": "Chart − This module is only required if you would want graphical reports as the GD module." }, { "code": null, "e": 17314, "s": 17237, "text": "Template-GD − This module has the template toolkit for the template plugins." }, { "code": null, "e": 17391, "s": 17314, "text": "Template-GD − This module has the template toolkit for the template plugins." }, { "code": null, "e": 17460, "s": 17391, "text": "GDTextUtil − This module has the text utilities for use with the GD." }, { "code": null, "e": 17529, "s": 17460, "text": "GDTextUtil − This module has the text utilities for use with the GD." }, { "code": null, "e": 17598, "s": 17529, "text": "GDGraph − It is a Perl5 module to create charts using the GD module." }, { "code": null, "e": 17667, "s": 17598, "text": "GDGraph − It is a Perl5 module to create charts using the GD module." }, { "code": null, "e": 17825, "s": 17667, "text": "MIME-tools − MIME-tools is a collection of Perl5 MIME modules for parsing, decoding and generating single or multipart (even nested multipart) MIME messages." }, { "code": null, "e": 17983, "s": 17825, "text": "MIME-tools − MIME-tools is a collection of Perl5 MIME modules for parsing, decoding and generating single or multipart (even nested multipart) MIME messages." }, { "code": null, "e": 18180, "s": 17983, "text": "libwww-perl − The World Wide Web library for Perl is also called as the libwww-perl. It is a set of Perl modules, which give Perl programming an easy access to send requests to the World Wide Web." }, { "code": null, "e": 18377, "s": 18180, "text": "libwww-perl − The World Wide Web library for Perl is also called as the libwww-perl. It is a set of Perl modules, which give Perl programming an easy access to send requests to the World Wide Web." }, { "code": null, "e": 18572, "s": 18377, "text": "XML-Twig − It is a Perl module used to process XML documents efficiently. This module offers a tree-oriented interface to a document while still allowing the processing of documents of any size." }, { "code": null, "e": 18767, "s": 18572, "text": "XML-Twig − It is a Perl module used to process XML documents efficiently. This module offers a tree-oriented interface to a document while still allowing the processing of documents of any size." }, { "code": null, "e": 18855, "s": 18767, "text": "PatchReader − This module has various utilities to read and manipulate patches and CVS." }, { "code": null, "e": 18943, "s": 18855, "text": "PatchReader − This module has various utilities to read and manipulate patches and CVS." }, { "code": null, "e": 19164, "s": 18943, "text": "perl-ldap − It is a collection of modules that implements LDAP services API for Perl programs. This module may be used to search directories or perform maintenance functions such as adding, deleting or modifying entries." }, { "code": null, "e": 19385, "s": 19164, "text": "perl-ldap − It is a collection of modules that implements LDAP services API for Perl programs. This module may be used to search directories or perform maintenance functions such as adding, deleting or modifying entries." }, { "code": null, "e": 19492, "s": 19385, "text": "Authen-SASL − This module provides an implementation framework that all protocols should be able to share." }, { "code": null, "e": 19599, "s": 19492, "text": "Authen-SASL − This module provides an implementation framework that all protocols should be able to share." }, { "code": null, "e": 19669, "s": 19599, "text": "Net-SMTP-SSL − This module provides the SSL support for Net-SMTP 1.04" }, { "code": null, "e": 19739, "s": 19669, "text": "Net-SMTP-SSL − This module provides the SSL support for Net-SMTP 1.04" }, { "code": null, "e": 19806, "s": 19739, "text": "RadiusPerl − This module provides simple Radius client facilities." }, { "code": null, "e": 19873, "s": 19806, "text": "RadiusPerl − This module provides simple Radius client facilities." }, { "code": null, "e": 20063, "s": 19873, "text": "SOAP-Lite − This module is a collection of Perl modules, which provide a simple and lightweight interface to the Simple Object Access Protocol (SOAP) on both the client and the server side." }, { "code": null, "e": 20253, "s": 20063, "text": "SOAP-Lite − This module is a collection of Perl modules, which provide a simple and lightweight interface to the Simple Object Access Protocol (SOAP) on both the client and the server side." }, { "code": null, "e": 20368, "s": 20253, "text": "XMLRPC-Lite − This Perl module provides a simple interface to the XML-RPC protocol both on client and server side." }, { "code": null, "e": 20483, "s": 20368, "text": "XMLRPC-Lite − This Perl module provides a simple interface to the XML-RPC protocol both on client and server side." }, { "code": null, "e": 20554, "s": 20483, "text": "JSON-RPC − A set of modules that implement the JSON RPC 2.0 protocols." }, { "code": null, "e": 20625, "s": 20554, "text": "JSON-RPC − A set of modules that implement the JSON RPC 2.0 protocols." }, { "code": null, "e": 20681, "s": 20625, "text": "Test-Taint − This module has Tools to test taintedness." }, { "code": null, "e": 20737, "s": 20681, "text": "Test-Taint − This module has Tools to test taintedness." }, { "code": null, "e": 20869, "s": 20737, "text": "HTML-Parser − This module defines a class HTMLParser, which serves as the basis for parsing text files formatted in HTML and XHTML." }, { "code": null, "e": 21001, "s": 20869, "text": "HTML-Parser − This module defines a class HTMLParser, which serves as the basis for parsing text files formatted in HTML and XHTML." }, { "code": null, "e": 21107, "s": 21001, "text": "HTML-Scrubber − This module helps to sanitize of scrub the html input in a reliable and flexible fashion." }, { "code": null, "e": 21213, "s": 21107, "text": "HTML-Scrubber − This module helps to sanitize of scrub the html input in a reliable and flexible fashion." }, { "code": null, "e": 21307, "s": 21213, "text": "Encode − This module provides an interface between Perl's strings and the rest of the system." }, { "code": null, "e": 21401, "s": 21307, "text": "Encode − This module provides an interface between Perl's strings and the rest of the system." }, { "code": null, "e": 21495, "s": 21401, "text": "Encode-Detect − This module is an Encode-Encoding subclass that detects the encoding of data." }, { "code": null, "e": 21589, "s": 21495, "text": "Encode-Detect − This module is an Encode-Encoding subclass that detects the encoding of data." }, { "code": null, "e": 21659, "s": 21589, "text": "Email-Reply − This module helps in replying to an email or a message." }, { "code": null, "e": 21729, "s": 21659, "text": "Email-Reply − This module helps in replying to an email or a message." }, { "code": null, "e": 21861, "s": 21729, "text": "HTML-FormatText-WithLinks − This module takes HTML and turns it into plain text, but prints all the links in the HTML as footnotes." }, { "code": null, "e": 21993, "s": 21861, "text": "HTML-FormatText-WithLinks − This module takes HTML and turns it into plain text, but prints all the links in the HTML as footnotes." }, { "code": null, "e": 22051, "s": 21993, "text": "TheSchwartz − This module is a reliable job queue system." }, { "code": null, "e": 22109, "s": 22051, "text": "TheSchwartz − This module is a reliable job queue system." }, { "code": null, "e": 22219, "s": 22109, "text": "Daemon-Generic − This module provides a framework for starting, stopping, reconfiguring daemon-like programs." }, { "code": null, "e": 22329, "s": 22219, "text": "Daemon-Generic − This module provides a framework for starting, stopping, reconfiguring daemon-like programs." }, { "code": null, "e": 22414, "s": 22329, "text": "mod_perl − This module helps in embedding a Perl interpreter into the Apache server." }, { "code": null, "e": 22499, "s": 22414, "text": "mod_perl − This module helps in embedding a Perl interpreter into the Apache server." }, { "code": null, "e": 22601, "s": 22499, "text": "Apache-SizeLimit − This module allows you to kill the Apache httpd processes, if they grow too large." }, { "code": null, "e": 22703, "s": 22601, "text": "Apache-SizeLimit − This module allows you to kill the Apache httpd processes, if they grow too large." }, { "code": null, "e": 22777, "s": 22703, "text": "File-MimeInfo − This module is used to determine the mime type of a file." }, { "code": null, "e": 22851, "s": 22777, "text": "File-MimeInfo − This module is used to determine the mime type of a file." }, { "code": null, "e": 23000, "s": 22851, "text": "IO-stringy − This toolkit mainly provides modules for performing both traditional and object-oriented (i/o) on things other than normal filehandles." }, { "code": null, "e": 23149, "s": 23000, "text": "IO-stringy − This toolkit mainly provides modules for performing both traditional and object-oriented (i/o) on things other than normal filehandles." }, { "code": null, "e": 23240, "s": 23149, "text": "Cache-Memcached − This module is a client library for the memory cache daemon (memcached)." }, { "code": null, "e": 23331, "s": 23240, "text": "Cache-Memcached − This module is a client library for the memory cache daemon (memcached)." }, { "code": null, "e": 23465, "s": 23331, "text": "Text-Markdown − This module is a text-to-HTML filter; it translates an easy-to-read / easy-to-write structured text format into HTML." }, { "code": null, "e": 23599, "s": 23465, "text": "Text-Markdown − This module is a text-to-HTML filter; it translates an easy-to-read / easy-to-write structured text format into HTML." }, { "code": null, "e": 23700, "s": 23599, "text": "File-Copy-Recursive − This module is a Perl extension for recursively copying files and directories." }, { "code": null, "e": 23801, "s": 23700, "text": "File-Copy-Recursive − This module is a Perl extension for recursively copying files and directories." }, { "code": null, "e": 23997, "s": 23801, "text": "In Strawberry Perl, use the cpanm script to install modules. Some of the most important modules are already installed by default. The remaining ones can be installed using the following command −" }, { "code": null, "e": 24026, "s": 23997, "text": "cpanm -l local <modulename>\n" }, { "code": null, "e": 24111, "s": 24026, "text": "The list of modules to install will be displayed by using the checksetup.pl command." }, { "code": null, "e": 24388, "s": 24111, "text": "The Bugzilla installation requires several technical aspects to start with. A few websites provide the Bugzilla web application – Landfill: The Bugzilla Test Server is one of these. https://landfill.bugzilla.org/bugzilla-2.16.11/ this is the testing and demonstration website." }, { "code": null, "e": 24641, "s": 24388, "text": "Note − Landfill is a home for test installations of the Bugzilla bug-tracking system. If you are evaluating Bugzilla, you can use them to try it. They are also useful if you are a developer and want to try to reproduce a bug that somebody has reported." }, { "code": null, "e": 24740, "s": 24641, "text": "Once you navigate to the above-mentioned URL, the Bugzilla home page will display as shown below −" }, { "code": null, "e": 24848, "s": 24740, "text": "The process of creating an account is similar to any other web based application like Facebook, Gmail, etc." }, { "code": null, "e": 24895, "s": 24848, "text": "Following are the steps to create an account −" }, { "code": null, "e": 24961, "s": 24895, "text": "Step 1 − Go to https://landfill.bugzilla.org/bugzilla-5.0-branch/" }, { "code": null, "e": 25083, "s": 24961, "text": "Step 2 − On the Bugzilla home page, click the New Account link placed on the header as shown in the following screenshot." }, { "code": null, "e": 25135, "s": 25083, "text": "Step 3 − Enter the email address and click on Send." }, { "code": null, "e": 25288, "s": 25135, "text": "Step 4 − Within moments, the user will receive an email to the given address. This Email should have a login name and a URL to confirm the registration." }, { "code": null, "e": 25565, "s": 25288, "text": "Step 5 − Once the registration is confirmed, Bugzilla will ask the real name (optional, but recommended) and ask the user to type their password and confirm their password. Depending on how Bugzilla is configured, there may be minimum complexity requirements for the password." }, { "code": null, "e": 25768, "s": 25565, "text": "Step 6 − Once the details are filled, click on Create, a successful message of account creation displays on the screen, else it will display an error message. Correct the error and then click on Create." }, { "code": null, "e": 25833, "s": 25768, "text": "To login into Bugzilla, we have to follow the steps given below." }, { "code": null, "e": 25898, "s": 25833, "text": "Step 1 − Click on the Log In link on the header of the homepage." }, { "code": null, "e": 25961, "s": 25898, "text": "Step 2 − Enter the Email Address, Password and click on Log In" }, { "code": null, "e": 26066, "s": 25961, "text": "Step 3 − The user will be logged in successfully; the users can see their user id in the header section." }, { "code": null, "e": 26193, "s": 26066, "text": "Step 4 − The user can see open bugs assigned to him, reported by him and requests addressed to him at the left bottom section." }, { "code": null, "e": 26274, "s": 26193, "text": "The procedure of filling a new bug is quite simple and has been explained below." }, { "code": null, "e": 26433, "s": 26274, "text": "Step 1 − Click on the ‘New’ link, present on the header or the footer or Click on the File a Bug button on the home page as shown in the following screenshot." }, { "code": null, "e": 26501, "s": 26433, "text": "Step 2 − Now, select the product group in which the bug is noticed." }, { "code": null, "e": 26629, "s": 26501, "text": "Step 3 − After selecting the Product, a form will appear where the user should enter the following details related to the bug −" }, { "code": null, "e": 26643, "s": 26629, "text": "Enter Product" }, { "code": null, "e": 26659, "s": 26643, "text": "Enter Component" }, { "code": null, "e": 26686, "s": 26659, "text": "Give Component description" }, { "code": null, "e": 26701, "s": 26686, "text": "Select version" }, { "code": null, "e": 26717, "s": 26701, "text": "Select severity" }, { "code": null, "e": 26733, "s": 26717, "text": "Select Hardware" }, { "code": null, "e": 26743, "s": 26733, "text": "Select OS" }, { "code": null, "e": 26757, "s": 26743, "text": "Enter Summary" }, { "code": null, "e": 26775, "s": 26757, "text": "Enter Description" }, { "code": null, "e": 26793, "s": 26775, "text": "Attach Attachment" }, { "code": null, "e": 26917, "s": 26793, "text": "Note − The above fields vary as per the customization of Bugzilla. The Mandatory fields are marked with a red asterisk (*)." }, { "code": null, "e": 27064, "s": 26917, "text": "Step 5 − Once the user starts typing in the Summary, Bugzilla filters the already logged in defects and displays the list to avoid duplicate bugs." }, { "code": null, "e": 27120, "s": 27064, "text": "Step 6 − Click on the Submit Bug button to log the bug." }, { "code": null, "e": 27255, "s": 27120, "text": "Step 7 − As soon as the user clicks on the Submit bug button, a Bug Id is generated with the details that of bug as that were entered." }, { "code": null, "e": 27347, "s": 27255, "text": "Step 8 − The Deadline and the Status will be shown as depicted in the following screenshot." }, { "code": null, "e": 27539, "s": 27347, "text": "A user can also add additional information to the assigned bug like URL, keywords, whiteboard, tags, etc. This extra-information is helpful to give more details about the Bug that is created." }, { "code": null, "e": 27554, "s": 27539, "text": "Large text box" }, { "code": null, "e": 27558, "s": 27554, "text": "URL" }, { "code": null, "e": 27569, "s": 27558, "text": "Whiteboard" }, { "code": null, "e": 27578, "s": 27569, "text": "Keywords" }, { "code": null, "e": 27583, "s": 27578, "text": "Tags" }, { "code": null, "e": 27594, "s": 27583, "text": "Depends on" }, { "code": null, "e": 27601, "s": 27594, "text": "Blocks" }, { "code": null, "e": 27661, "s": 27601, "text": "In the next chapter, we will learn how a bug can be cloned." }, { "code": null, "e": 27871, "s": 27661, "text": "Bugzilla has the provision of \"Cloning\" an existing bug. The newly created bug keeps most of the settings from the old bug. This helps in tracking similar concerns that require different handling in a new bug." }, { "code": null, "e": 28028, "s": 27871, "text": "To use this, go to the bug that user wants to clone. Then click on the “Clone This Bug” link on the footer of the bug page as shown in the screenshot below." }, { "code": null, "e": 28197, "s": 28028, "text": "After clicking on clone the bug link, the page will navigate the user to the Product group selection page. Once on the selection page, the user has to select a product." }, { "code": null, "e": 28272, "s": 28197, "text": "Enter the Bug page that is filled with the values same as the old bug has." }, { "code": null, "e": 28326, "s": 28272, "text": "The User can change the values and/or text if needed." }, { "code": null, "e": 28405, "s": 28326, "text": "Then, click on Submit Bug. Bug is logged successfully with dependency details." }, { "code": null, "e": 28690, "s": 28405, "text": "The main feature or the heart of Bugzilla is the page that displays details of a bug. Note that the labels for most fields are hyperlinks; clicking them will take to context-sensitive help of that particular field. Fields marked * may not be present on every installation of Bugzilla." }, { "code": null, "e": 28884, "s": 28690, "text": "Summary − It is a one-sentence summary of the problem, which is displayed in the header next to the bug number. It is similar to the title of the bug that gives the user an overview of the bug." }, { "code": null, "e": 29078, "s": 28884, "text": "Summary − It is a one-sentence summary of the problem, which is displayed in the header next to the bug number. It is similar to the title of the bug that gives the user an overview of the bug." }, { "code": null, "e": 29481, "s": 29078, "text": "Status (and Resolution) − These define status of the bug – It starts with even before being confirmed as a bug, then being fixed and the fix being confirmed by Quality Assurance. The different possible values for Status and Resolution on installation should be documented in the context-sensitive help for those items. Status supports Unconfirmed, Confirmed, Fixed, In Process, Resolved, Rejected, etc." }, { "code": null, "e": 29884, "s": 29481, "text": "Status (and Resolution) − These define status of the bug – It starts with even before being confirmed as a bug, then being fixed and the fix being confirmed by Quality Assurance. The different possible values for Status and Resolution on installation should be documented in the context-sensitive help for those items. Status supports Unconfirmed, Confirmed, Fixed, In Process, Resolved, Rejected, etc." }, { "code": null, "e": 30123, "s": 29884, "text": "Alias − An Alias is a unique short text name for the bug, which can be used instead of the bug number. It provides the unique identifiers and help to find the bug in case of Bug ID is not handy. It can be useful while searching for a bug." }, { "code": null, "e": 30362, "s": 30123, "text": "Alias − An Alias is a unique short text name for the bug, which can be used instead of the bug number. It provides the unique identifiers and help to find the bug in case of Bug ID is not handy. It can be useful while searching for a bug." }, { "code": null, "e": 30551, "s": 30362, "text": "Product and Component − Bugs are divided by Products and Components. A Product may have one or more Components in it. It helps to categorize the bugs and helps in segregating them as well." }, { "code": null, "e": 30740, "s": 30551, "text": "Product and Component − Bugs are divided by Products and Components. A Product may have one or more Components in it. It helps to categorize the bugs and helps in segregating them as well." }, { "code": null, "e": 30915, "s": 30740, "text": "Version − The \"Version\" field usually contains the numbers or names of the released versions of the product. It is used to indicate the version(s) affected by the bug report." }, { "code": null, "e": 31090, "s": 30915, "text": "Version − The \"Version\" field usually contains the numbers or names of the released versions of the product. It is used to indicate the version(s) affected by the bug report." }, { "code": null, "e": 31295, "s": 31090, "text": "Hardware (Platform and OS) − These indicate the tested environment or the operating system, where the bug was found. It also gives out the details of the hardware like RAM, Hard Disk Size, Processor, etc." }, { "code": null, "e": 31500, "s": 31295, "text": "Hardware (Platform and OS) − These indicate the tested environment or the operating system, where the bug was found. It also gives out the details of the hardware like RAM, Hard Disk Size, Processor, etc." }, { "code": null, "e": 31824, "s": 31500, "text": "Importance (Priority and Severity) − The Priority field is used to prioritize bugs. It can be updated by the assignee, business people or someone else from stakeholders with the authority to change. It is a good idea not to change this field on other bugs, which are not raised by a person. The default values are P1 to P5." }, { "code": null, "e": 32148, "s": 31824, "text": "Importance (Priority and Severity) − The Priority field is used to prioritize bugs. It can be updated by the assignee, business people or someone else from stakeholders with the authority to change. It is a good idea not to change this field on other bugs, which are not raised by a person. The default values are P1 to P5." }, { "code": null, "e": 32499, "s": 32148, "text": "Severity Field − The Severity field indicates how severe the problem is—from blocker (\"application unusable\") to trivial (\"minor cosmetic issue\"). User can also use this field to indicate whether a bug is an enhancement or future request. The common supportive severity statuses are – Blocker, Critical, Major, Normal, Minor, Trivial and enhancement." }, { "code": null, "e": 32850, "s": 32499, "text": "Severity Field − The Severity field indicates how severe the problem is—from blocker (\"application unusable\") to trivial (\"minor cosmetic issue\"). User can also use this field to indicate whether a bug is an enhancement or future request. The common supportive severity statuses are – Blocker, Critical, Major, Normal, Minor, Trivial and enhancement." }, { "code": null, "e": 33116, "s": 32850, "text": "Target Milestone − It is a future date by which the bug is to be fixed. Example – The Bugzilla Project's milestones for future Bugzilla versions are 4.4, 5.0, 6.0, etc. Milestones are not restricted to numbers though the user can use any text strings such as dates." }, { "code": null, "e": 33382, "s": 33116, "text": "Target Milestone − It is a future date by which the bug is to be fixed. Example – The Bugzilla Project's milestones for future Bugzilla versions are 4.4, 5.0, 6.0, etc. Milestones are not restricted to numbers though the user can use any text strings such as dates." }, { "code": null, "e": 33535, "s": 33382, "text": "Assigned To − A Bug is assigned to a person who is responsible to fix the bug or can check the credibility of the bug based on the business requirement." }, { "code": null, "e": 33688, "s": 33535, "text": "Assigned To − A Bug is assigned to a person who is responsible to fix the bug or can check the credibility of the bug based on the business requirement." }, { "code": null, "e": 33889, "s": 33688, "text": "QA Contact − The person responsible for quality assurance on this bug. It may be the reporter of the bug to provide more details if required or can be contacted for retest the defect once it is fixed." }, { "code": null, "e": 34090, "s": 33889, "text": "QA Contact − The person responsible for quality assurance on this bug. It may be the reporter of the bug to provide more details if required or can be contacted for retest the defect once it is fixed." }, { "code": null, "e": 34135, "s": 34090, "text": "URL − A URL associated with the bug, if any." }, { "code": null, "e": 34180, "s": 34135, "text": "URL − A URL associated with the bug, if any." }, { "code": null, "e": 34297, "s": 34180, "text": "Whiteboard − A free-form text area for adding short notes, new observations or retesting comments and tags to a bug." }, { "code": null, "e": 34414, "s": 34297, "text": "Whiteboard − A free-form text area for adding short notes, new observations or retesting comments and tags to a bug." }, { "code": null, "e": 34539, "s": 34414, "text": "Keywords − The administrator can define keywords that can be used to tag and categories bugs — for e.g. crash or regression." }, { "code": null, "e": 34664, "s": 34539, "text": "Keywords − The administrator can define keywords that can be used to tag and categories bugs — for e.g. crash or regression." }, { "code": null, "e": 34994, "s": 34664, "text": "Personal Tags − Keywords are global and visible by all users, while Personal Tags are personal and can only be viewed and edited by their author. Editing those tags will not send any notifications to other users. These tags are used to keep track of bugs that a user personally cares about, using their own classification system." }, { "code": null, "e": 35324, "s": 34994, "text": "Personal Tags − Keywords are global and visible by all users, while Personal Tags are personal and can only be viewed and edited by their author. Editing those tags will not send any notifications to other users. These tags are used to keep track of bugs that a user personally cares about, using their own classification system." }, { "code": null, "e": 35519, "s": 35324, "text": "Dependencies (Depends On and Blocks) − If a bug cannot be fixed as some other bugs are opened (depends on) or this bug stops other bugs for being fixed (blocks), their numbers are recorded here." }, { "code": null, "e": 35714, "s": 35519, "text": "Dependencies (Depends On and Blocks) − If a bug cannot be fixed as some other bugs are opened (depends on) or this bug stops other bugs for being fixed (blocks), their numbers are recorded here." }, { "code": null, "e": 36051, "s": 35714, "text": "Clicking on the Dependency tree link shows the dependency relationships of the bug as a tree structure. A user can change how much depth to show and hide the resolved bugs from this page. A user can also collapse/expand dependencies for each non-terminal bug on the tree view, using the [-] / [+] buttons that appear before the summary." }, { "code": null, "e": 36136, "s": 36051, "text": "Reported − It is the Time and Date when the bug is logged by a person in the system." }, { "code": null, "e": 36221, "s": 36136, "text": "Reported − It is the Time and Date when the bug is logged by a person in the system." }, { "code": null, "e": 36301, "s": 36221, "text": "Modified − It is the Date and Time when the bug was last changed in the system." }, { "code": null, "e": 36381, "s": 36301, "text": "Modified − It is the Date and Time when the bug was last changed in the system." }, { "code": null, "e": 36510, "s": 36381, "text": "CC List − A list of people who get mail when the bug changes, in addition to the Reporter, Assignee and QA Contact (if enabled)." }, { "code": null, "e": 36639, "s": 36510, "text": "CC List − A list of people who get mail when the bug changes, in addition to the Reporter, Assignee and QA Contact (if enabled)." }, { "code": null, "e": 36747, "s": 36639, "text": "Ignore Bug Mail − A user can check this field if he never wants to get an email notification from this bug." }, { "code": null, "e": 36855, "s": 36747, "text": "Ignore Bug Mail − A user can check this field if he never wants to get an email notification from this bug." }, { "code": null, "e": 36958, "s": 36855, "text": "See Also − Bugs, in this Bugzilla, other Bugzilla or other bug trackers those are related to this one." }, { "code": null, "e": 37061, "s": 36958, "text": "See Also − Bugs, in this Bugzilla, other Bugzilla or other bug trackers those are related to this one." }, { "code": null, "e": 37287, "s": 37061, "text": "Flags − A flag is a kind of status that can be set on bugs or attachments to indicate that the bugs/attachments are in a certain state. Each installation can define its own set of flags that can be set on bugs or attachments." }, { "code": null, "e": 37513, "s": 37287, "text": "Flags − A flag is a kind of status that can be set on bugs or attachments to indicate that the bugs/attachments are in a certain state. Each installation can define its own set of flags that can be set on bugs or attachments." }, { "code": null, "e": 37676, "s": 37513, "text": "Time Tracking − This form can be used for time tracking. To use this feature, a user has to be a member of the group specified by the timetrackinggroup parameter." }, { "code": null, "e": 37839, "s": 37676, "text": "Time Tracking − This form can be used for time tracking. To use this feature, a user has to be a member of the group specified by the timetrackinggroup parameter." }, { "code": null, "e": 37898, "s": 37839, "text": "Orig. Est. − This field shows the original estimated time." }, { "code": null, "e": 37957, "s": 37898, "text": "Orig. Est. − This field shows the original estimated time." }, { "code": null, "e": 38077, "s": 37957, "text": "Current Est. − This field shows the current estimated time. This number is calculated from Hours Worked and Hours Left." }, { "code": null, "e": 38197, "s": 38077, "text": "Current Est. − This field shows the current estimated time. This number is calculated from Hours Worked and Hours Left." }, { "code": null, "e": 38282, "s": 38197, "text": "Hours Worked − This field shows the number of hours worked on the particular defect." }, { "code": null, "e": 38367, "s": 38282, "text": "Hours Worked − This field shows the number of hours worked on the particular defect." }, { "code": null, "e": 38495, "s": 38367, "text": "Hours Left − This field shows the Current Est. - Hours Worked. This value + Hours Worked will become the new Current Estimated." }, { "code": null, "e": 38623, "s": 38495, "text": "Hours Left − This field shows the Current Est. - Hours Worked. This value + Hours Worked will become the new Current Estimated." }, { "code": null, "e": 38697, "s": 38623, "text": "%Complete − This field shows how much percentage of the task is complete." }, { "code": null, "e": 38771, "s": 38697, "text": "%Complete − This field shows how much percentage of the task is complete." }, { "code": null, "e": 38859, "s": 38771, "text": "Gain − This field shows the number of hours the bug is ahead of the Original Estimated." }, { "code": null, "e": 38947, "s": 38859, "text": "Gain − This field shows the number of hours the bug is ahead of the Original Estimated." }, { "code": null, "e": 39002, "s": 38947, "text": "Deadline − This field shows the deadline for this bug." }, { "code": null, "e": 39057, "s": 39002, "text": "Deadline − This field shows the deadline for this bug." }, { "code": null, "e": 39201, "s": 39057, "text": "Attachments − A user can attach files (evidence, test cases or patches) to bugs. If there are any attachments, they are listed in this section." }, { "code": null, "e": 39345, "s": 39201, "text": "Attachments − A user can attach files (evidence, test cases or patches) to bugs. If there are any attachments, they are listed in this section." }, { "code": null, "e": 39467, "s": 39345, "text": "Additional Comments − A user can add comments to the bug discussion here, if user/tester has something worthwhile to say." }, { "code": null, "e": 39589, "s": 39467, "text": "Additional Comments − A user can add comments to the bug discussion here, if user/tester has something worthwhile to say." }, { "code": null, "e": 39643, "s": 39589, "text": "In the next chapter, we will learn how to edit a bug." }, { "code": null, "e": 39881, "s": 39643, "text": "Bugzilla has a provision of editing an existing bug. A user can edit a bug during the lifecycle of any bug. Most of the fields have an edit hyperlink. It depends on administrator of Bugzilla to provide edit options with different fields." }, { "code": null, "e": 40058, "s": 39881, "text": "In the following screenshot, there are many fields that have an edit hyperlink such as – Status, Alias, Assignee, QA Contact, ‘Depends on’, Large Text box, Flags, CC list, etc." }, { "code": null, "e": 40190, "s": 40058, "text": "Click on the edit hyperlink of a particular field, that field will display as editable and the user can edit the field accordingly." }, { "code": null, "e": 40331, "s": 40190, "text": "After the editing is done, click on Save Changes button, which is on the top right hand corner of the page as shown in the screenshot below." }, { "code": null, "e": 40455, "s": 40331, "text": "After the changes are successfully done, the advisory will display of the bug details as shown in the following screenshot." }, { "code": null, "e": 40769, "s": 40455, "text": "A report helps to analyse the current state of the bug. The purpose of a Defect Report is to see the behaviour, communication, analysis and the current stage of a defect at any stage of the defect lifecycle. Defect reports are even useful after closing the defect and analysis the product and development quality." }, { "code": null, "e": 40864, "s": 40769, "text": "Following are some of the important points to consider regarding the various Bugzilla reports." }, { "code": null, "e": 40935, "s": 40864, "text": "Bugzilla supports those Tabular Reports that have HTML or CSV reports." }, { "code": null, "e": 41006, "s": 40935, "text": "Bugzilla supports those Tabular Reports that have HTML or CSV reports." }, { "code": null, "e": 41091, "s": 41006, "text": "Tabular reports can be viewed in 1-Dimensional, 2-Dimensional or 3-Dimensional ways." }, { "code": null, "e": 41176, "s": 41091, "text": "Tabular reports can be viewed in 1-Dimensional, 2-Dimensional or 3-Dimensional ways." }, { "code": null, "e": 41256, "s": 41176, "text": "The most common type of report supported by Bugzilla are the Graphical Reports." }, { "code": null, "e": 41336, "s": 41256, "text": "The most common type of report supported by Bugzilla are the Graphical Reports." }, { "code": null, "e": 41394, "s": 41336, "text": "Graphical Reports contain line graph, bar and pie charts." }, { "code": null, "e": 41452, "s": 41394, "text": "Graphical Reports contain line graph, bar and pie charts." }, { "code": null, "e": 41557, "s": 41452, "text": "Report functionality is based on Search and filter concept, for which the conditions are given by users." }, { "code": null, "e": 41662, "s": 41557, "text": "Report functionality is based on Search and filter concept, for which the conditions are given by users." }, { "code": null, "e": 41834, "s": 41662, "text": "The user provides his preference of vertical and horizontal axis to plot graphs, charts or tables along with filter criteria’s like Project, Component, Defect Status, etc." }, { "code": null, "e": 42006, "s": 41834, "text": "The user provides his preference of vertical and horizontal axis to plot graphs, charts or tables along with filter criteria’s like Project, Component, Defect Status, etc." }, { "code": null, "e": 42066, "s": 42006, "text": "The user can even choose 3-D reports for tables and images." }, { "code": null, "e": 42126, "s": 42066, "text": "The user can even choose 3-D reports for tables and images." }, { "code": null, "e": 42214, "s": 42126, "text": "For navigating the reports section in Bugzilla, we should follow the steps given below." }, { "code": null, "e": 42280, "s": 42214, "text": "Step 1 − Click on the Reports link in the header of the homepage." }, { "code": null, "e": 42447, "s": 42280, "text": "Step 2 − Bugzilla displays the Reporting and Charting Kitchen page. It has two sections to generate different type of reports – Tabular Reports and Graphical Reports." }, { "code": null, "e": 42466, "s": 42447, "text": "Other links like −" }, { "code": null, "e": 42530, "s": 42466, "text": "Search − It will navigate the user to the standard search page." }, { "code": null, "e": 42594, "s": 42530, "text": "Search − It will navigate the user to the standard search page." }, { "code": null, "e": 42657, "s": 42594, "text": "Duplicate − It will display the most frequently reported bugs." }, { "code": null, "e": 42720, "s": 42657, "text": "Duplicate − It will display the most frequently reported bugs." }, { "code": null, "e": 42813, "s": 42720, "text": "In the next chapter, we will understand what graphical reports are and how to generate them." }, { "code": null, "e": 43103, "s": 42813, "text": "Graphical reports are a group of line, bar and pie charts. These Reports are helpful in many ways, for example if a user wants to know which component has the maximum number of defects reported and wants to represent in the graph, then that user can select from the following two options −" }, { "code": null, "e": 43126, "s": 43103, "text": "Severity on the X-axis" }, { "code": null, "e": 43150, "s": 43126, "text": "Component on the Y-axis" }, { "code": null, "e": 43181, "s": 43150, "text": "Then click on Generate Report." }, { "code": null, "e": 43320, "s": 43181, "text": "It will generate a report with crucial information. Similarly, the user can a select number of combinations from those that are available." }, { "code": null, "e": 43404, "s": 43320, "text": "To generate graphical reports in Bugzilla, we have to follow the steps given below." }, { "code": null, "e": 43485, "s": 43404, "text": "Step 1 − To begin with, click on the Reports link at the header of the homepage." }, { "code": null, "e": 43622, "s": 43485, "text": "Step 2 − Click on the Graphical Reports hyperlink, which is listed under the Current State section as shown in the following screenshot." }, { "code": null, "e": 43735, "s": 43622, "text": "Step 3 − Now, set various options to present reports graphically. Some of the important options are given below." }, { "code": null, "e": 43749, "s": 43735, "text": "Vertical Axis" }, { "code": null, "e": 43765, "s": 43749, "text": "Horizontal Axis" }, { "code": null, "e": 43781, "s": 43765, "text": "Multiple Images" }, { "code": null, "e": 43824, "s": 43781, "text": "Format- Line graph, Bar chart or Pie chart" }, { "code": null, "e": 43838, "s": 43824, "text": "Plot data set" }, { "code": null, "e": 43856, "s": 43838, "text": "Classify your bug" }, { "code": null, "e": 43878, "s": 43856, "text": "Classify your product" }, { "code": null, "e": 43902, "s": 43878, "text": "Classify your component" }, { "code": null, "e": 43922, "s": 43902, "text": "Classify bug status" }, { "code": null, "e": 43940, "s": 43922, "text": "Select resolution" }, { "code": null, "e": 44107, "s": 43940, "text": "Step 4 − Click on Generate Report to display a Bar chart, where the Severity of a bug is the vertical axis, while the Component “Widget Gears” is the horizontal axis." }, { "code": null, "e": 44183, "s": 44107, "text": "Step 5 − Similarly, a Line Graph can be created for % Complete Vs Deadline." }, { "code": null, "e": 44249, "s": 44183, "text": "The result for the above mentioned line graph will be as follows." }, { "code": null, "e": 44422, "s": 44249, "text": "The Tabular Reports represent tables of bug counts in 1, 2 or 3 dimensions as HTML or CSV. To generate Tabular reports in Bugzilla, we have to follow the steps given below." }, { "code": null, "e": 44605, "s": 44422, "text": "Step 1 − Click on the Reports hyperlink in the Header section of the homepage and then click on the Tabular Reports in the Current State section as shown in the following screenshot." }, { "code": null, "e": 44759, "s": 44605, "text": "Step 2 − Similar to Graphical Reports, select Vertical, Horizontal axis along with Multiple tables (if required) and provide details in the other fields." }, { "code": null, "e": 44881, "s": 44759, "text": "Step 3 − After selecting all the fields, click on Generate Report. Based on the deadlines, it generates multiple tables −" }, { "code": null, "e": 44976, "s": 44881, "text": "Step 4 − By clicking on CSV hyperlink below the table, it converts the report into a CSV file." }, { "code": null, "e": 45087, "s": 44976, "text": "Click OK after the appropriate selection, it will open an Excel sheet with the details of all the data tables." }, { "code": null, "e": 45165, "s": 45087, "text": "In Bugzilla, Duplicates are a list of bugs, which are raised most frequently." }, { "code": null, "e": 45216, "s": 45165, "text": "Duplicates are the most frequently seen open bugs." }, { "code": null, "e": 45267, "s": 45216, "text": "Duplicates are the most frequently seen open bugs." }, { "code": null, "e": 45441, "s": 45267, "text": "Duplicates count the numbers as the Dupe Count of direct and indirect duplicates of a defect report. This information is helpful to minimize the number of duplicate defects." }, { "code": null, "e": 45615, "s": 45441, "text": "Duplicates count the numbers as the Dupe Count of direct and indirect duplicates of a defect report. This information is helpful to minimize the number of duplicate defects." }, { "code": null, "e": 45689, "s": 45615, "text": "Duplicates help to save time for QA engineers to log a new defect always." }, { "code": null, "e": 45763, "s": 45689, "text": "Duplicates help to save time for QA engineers to log a new defect always." }, { "code": null, "e": 45900, "s": 45763, "text": "Duplicates also help stakeholders to find out the root cause, if the same defects are reopened repeatedly rather than just a new defect." }, { "code": null, "e": 46037, "s": 45900, "text": "Duplicates also help stakeholders to find out the root cause, if the same defects are reopened repeatedly rather than just a new defect." }, { "code": null, "e": 46351, "s": 46037, "text": "Review the most frequent bug list with the respective issue noticed. If the problem is listed as a bug in the list, then click on the bug id to view details and confirm whether it is the same issue or not. Comment on the additional observation, link it with your Test Case if required and re-open if it is closed." }, { "code": null, "e": 46596, "s": 46351, "text": "If the exact problem is not listed, try to find a similar defect that is already listed. If the user finds the defect that are dependent on new observations, he can comment and link the defect. If the user cannot find the defect, log a new one." }, { "code": null, "e": 46680, "s": 46596, "text": "To generate Duplicate reports in Bugzilla, we have to follow the steps given below." }, { "code": null, "e": 46750, "s": 46680, "text": "Step 1 − Click on the Report hyperlink in the header of the homepage." }, { "code": null, "e": 46901, "s": 46750, "text": "Step 2 − As soon as you click on Report, the Reporting and Charting Kitchen page opens. Click on Duplicates hyperlink under the Current State section." }, { "code": null, "e": 47091, "s": 46901, "text": "Step 3 − By clicking on Duplicates, open the Most Frequently Reported Bugs table. It has various columns as Bug Id, Dupe Count, Component, Severity, Priority, Target Milestone, and Summary." }, { "code": null, "e": 47263, "s": 47091, "text": "This is an interesting feature to filter or customize the Most Frequently Reported Bug tables. Following are some of the important pointers, which are explained in detail." }, { "code": null, "e": 47431, "s": 47263, "text": "Restrict to product − It filters out the table based on specific Product and components. The user can choose from single or multiple products by pressing CTRL + Click." }, { "code": null, "e": 47599, "s": 47431, "text": "Restrict to product − It filters out the table based on specific Product and components. The user can choose from single or multiple products by pressing CTRL + Click." }, { "code": null, "e": 47714, "s": 47599, "text": "When sorting or restricting, work with − It has two options, either the entire list or the currently visible list." }, { "code": null, "e": 47829, "s": 47714, "text": "When sorting or restricting, work with − It has two options, either the entire list or the currently visible list." }, { "code": null, "e": 47909, "s": 47829, "text": "Max Rows − The user can give a number to see the number of defects in one page." }, { "code": null, "e": 47989, "s": 47909, "text": "Max Rows − The user can give a number to see the number of defects in one page." }, { "code": null, "e": 48100, "s": 47989, "text": "Change column is change in last − The number of days a user wants to review the changes that have taken place." }, { "code": null, "e": 48211, "s": 48100, "text": "Change column is change in last − The number of days a user wants to review the changes that have taken place." }, { "code": null, "e": 48330, "s": 48211, "text": "Open Bugs only − This will filter out all the bugs those are closed. The result will have a list of only open defects." }, { "code": null, "e": 48449, "s": 48330, "text": "Open Bugs only − This will filter out all the bugs those are closed. The result will have a list of only open defects." }, { "code": null, "e": 48561, "s": 48449, "text": "When the user Clicks on the Change button, all these filters will change and the bug list will be filtered out." }, { "code": null, "e": 48743, "s": 48561, "text": "When clicking on the Bug List button at “Or just give this to me as a Bug List”, the resulting table will display in the format of a Bug List page as shown in the screenshot below −" }, { "code": null, "e": 48858, "s": 48743, "text": "The Browse Function is one of the most important features of Bugzilla to find/trace/locate an existing logged bug." }, { "code": null, "e": 48900, "s": 48858, "text": "Following are steps to use this feature −" }, { "code": null, "e": 48971, "s": 48900, "text": "Step 1 − Click on the Browse hyperlink on the header of the home page." }, { "code": null, "e": 49148, "s": 48971, "text": "Step 2 − A window – \"Select a product category to browse\" as shown below, the user can browse the bug according to the category. Select the product \"Sam's Widget\" or any other." }, { "code": null, "e": 49408, "s": 49148, "text": "Step 3 − It opens another window, in this – click on the component Widget Gears. Bugzilla Components are sub-sections of a product. For example, here, the product is SAM'S WIDGET, whose component is WIDGET GEARS. A product can have multiple components listed." }, { "code": null, "e": 49631, "s": 49408, "text": "Step 4 − When you click on the component, it will open another window. All the Bugs created under a particular category will be listed over here. From that Bug-list, click on the Bug# ID to see more details about that bug." }, { "code": null, "e": 49837, "s": 49631, "text": "Step 5 − Once you click on the Bug ID, another window will open, where information about the bug can be seen in detail. In the same window, the user can also change the assignee, QA contact or the CC list." }, { "code": null, "e": 50026, "s": 49837, "text": "The Simple Search feature is useful in finding a specific bug. It works like the web search engines such as Google, Bing, Yahoo, etc. The user needs to enter some keywords and then search." }, { "code": null, "e": 50084, "s": 50026, "text": "Following are steps for using the simple search feature −" }, { "code": null, "e": 50154, "s": 50084, "text": "Step 1 − Click on the Search hyperlink in the header of the homepage." }, { "code": null, "e": 50236, "s": 50154, "text": "Step 2 − Click on the Simple Search section as shown in the following screenshot." }, { "code": null, "e": 50410, "s": 50236, "text": "Step 3 − Choose the Status of the bug from the list to filter. Then, choose the Product from the list and enter some Keywords related to the bug. Click on the Search button." }, { "code": null, "e": 50476, "s": 50410, "text": "Step 4 − The result will be as shown in the following screenshot." }, { "code": null, "e": 50787, "s": 50476, "text": "Step 5 − At the bottom of the search page, there are various options like how to see your bug - in XML Format, in Long Format or just as a Time Summary. Apart from that, the other option can be used – like sending a mail to the bug assignee, change several bugs at once or change the column of the screen, etc." }, { "code": null, "e": 50921, "s": 50787, "text": "The Quick Search feature is a single-text-box query tool. It is available on the Bugzilla home page as shown in the screenshot below." }, { "code": null, "e": 51211, "s": 50921, "text": "The Quick Search feature uses Meta characters to indicate what is to be searched. For example, typing bug|login into Quick Search would search for \"bug\" or \"login\" in the summary and whiteboard of a bug. The user can also use it to go directly to a bug by entering its number or its alias." }, { "code": null, "e": 51310, "s": 51211, "text": "By clicking on the Quick Search button, it displays list of bugs as shown in the screenshot below." }, { "code": null, "e": 51455, "s": 51310, "text": "The Advanced Search page displays a list of all the bugs, which are filtered exactly with different criteria that have been loaded by the users." }, { "code": null, "e": 51947, "s": 51455, "text": "This Advanced Search feature selects different possible values for all of the fields in a bug. For some fields, multiple values can be selected. In these cases, Bugzilla returns bugs where the content of the field matches with any one of the selected values. If none is selected, then the field can take any of values. Multiple values selection for one field is based on the “OR” functionality. If either one or any other value is matched among the user selection, the bug will be displayed." }, { "code": null, "e": 52039, "s": 51947, "text": "For using the advanced search feature in Bugzilla, we have to follow the steps given below." }, { "code": null, "e": 52201, "s": 52039, "text": "Step 1 − Click on the Search hyperlink on the header of the homepage. You will get two tabs, Simple Search and Advanced Search, click on the Advanced Search tab." }, { "code": null, "e": 52329, "s": 52201, "text": "Step 2 − Select the required option from the Summary field. Then, you can enter the keyword to identify or filter out the bugs." }, { "code": null, "e": 52722, "s": 52329, "text": "Step 3 − The next step is to select the category of Bug from the Classification box; here, we have selected Widget. Then, choose the Product under which the Bug is created; here, we have selected Sam's Widget. In the Component box, we have selected Widget Gears. In the Status box, click on Confirmed and in the Resolution box choose Fixed, all of these are shown in the following screenshot." }, { "code": null, "e": 52795, "s": 52722, "text": "Note − All these fields are optional and dependent on the user’s choice." }, { "code": null, "e": 52901, "s": 52795, "text": "Step 4 − Click on the Search Button after entering all the fields based on the requirement of the filter." }, { "code": null, "e": 52981, "s": 52901, "text": "Step 5 − Advance Search will detect the bug and the result will be as follows −" }, { "code": null, "e": 53215, "s": 52981, "text": "Custom Search is an extended feature of the Advanced Search. It works on the principle of – “Did not find what you are looking for above? I.e. in advanced search”. This area allows words like AND, OR, and other more complex searches." }, { "code": null, "e": 53361, "s": 53215, "text": "Navigation of custom search is as follows: Search → Advanced Search → Go Down and click on Custom Search as depicted in the following screenshot." }, { "code": null, "e": 53719, "s": 53361, "text": "Custom Search compares a selected field with a defined operator for a specified value. It is possible that too much of this could be reproduced using the standard fields in an Advanced Search option. However, the user can combine options like \"Match ANY\" or \"Match ALL\", using parentheses for combining and priority to construct searches of complex queries." }, { "code": null, "e": 53795, "s": 53719, "text": "There are three fields in each row (known as a \"term\") of a custom search −" }, { "code": null, "e": 53841, "s": 53795, "text": "Field − The name of the field being searched." }, { "code": null, "e": 53887, "s": 53841, "text": "Field − The name of the field being searched." }, { "code": null, "e": 53923, "s": 53887, "text": "Operator − The comparison operator." }, { "code": null, "e": 53959, "s": 53923, "text": "Operator − The comparison operator." }, { "code": null, "e": 54015, "s": 53959, "text": "Value − The value to which the field is being compared." }, { "code": null, "e": 54071, "s": 54015, "text": "Value − The value to which the field is being compared." }, { "code": null, "e": 54347, "s": 54071, "text": "The list of the available fields contains all the fields defined for a bug. It includes any custom fields, as well as some other fields like the Assignee Real Name, Days since Bug Changed, Time since Assignee Touched and other things, which might be useful to search further." }, { "code": null, "e": 54568, "s": 54347, "text": "There is a wide range of operators available. There are various string-matching operations (including regular expressions), numerical comparisons (which also work for dates) and to search for change information of a bug." }, { "code": null, "e": 54809, "s": 54568, "text": "When a field changed, what it changed from or to, and who did it. There are special operators is empty and is not empty, because Bugzilla cannot tell the difference between a value field left blank on purpose and one left blank by accident." }, { "code": null, "e": 54978, "s": 54809, "text": "The user can have n number of rows to define operators, values and fields. There is a dropdown box above them, which defines how these rows are related with the search." }, { "code": null, "e": 55254, "s": 54978, "text": "Match ALL of the following separately, Match ANY of the following separately or Match ALL of the following against the same field are three options listed in the dropdown. The difference between the first and the third can be described with a comment search. If a search is −" }, { "code": null, "e": 55290, "s": 55254, "text": "Comment contains the string – “Bug”" }, { "code": null, "e": 55328, "s": 55290, "text": "Comment contains the string – “issue”" }, { "code": null, "e": 55499, "s": 55328, "text": "Under the “match all of the following separately”, the search would return bugs, where a \"Bug\" appeared in one comment can be an \"issue\" in the same or any other comment." }, { "code": null, "e": 55703, "s": 55499, "text": "Under the “match all of the following against the same field”, both strings would need to occur in exactly the same comment, i.e. it will select a bug having both Bug and issue words in the same comment." }, { "code": null, "e": 56057, "s": 55703, "text": "By clicking on Show Advanced features, more capabilities or features appear to use complex and specific search. The user can negate any row by checking a checkbox. It can also group lines of the search with parentheses to determine how different search terms are related. The user gets the choice of combining them using ALL (i.e. AND) or ANY (i.e. OR)." }, { "code": null, "e": 56242, "s": 56057, "text": "A bug list is a group of searched bugs based on the user input. A Bug list is nothing other than filtered bugs based on different conditions in a Standard Search or an Advanced Search." }, { "code": null, "e": 56438, "s": 56242, "text": "The format of the list is configurable. For example, it can be sorted by clicking the column headings. Other useful features can be accessed using the links at the bottom of the list, which are −" }, { "code": null, "e": 56450, "s": 56438, "text": "Long Format" }, { "code": null, "e": 56461, "s": 56450, "text": "XML (icon)" }, { "code": null, "e": 56472, "s": 56461, "text": "CSV (icon)" }, { "code": null, "e": 56484, "s": 56472, "text": "Feed (icon)" }, { "code": null, "e": 56501, "s": 56484, "text": "iCalendar (icon)" }, { "code": null, "e": 56516, "s": 56501, "text": "Change Columns" }, { "code": null, "e": 56544, "s": 56516, "text": "Change Several Bugs At Once" }, { "code": null, "e": 56571, "s": 56544, "text": "Send Mail to Bug Assignees" }, { "code": null, "e": 56583, "s": 56571, "text": "Edit Search" }, { "code": null, "e": 56602, "s": 56583, "text": "Remember Search as" }, { "code": null, "e": 56661, "s": 56602, "text": "All of these features have been explained in detail below." }, { "code": null, "e": 56780, "s": 56661, "text": "By clicking on the Long Format button, it provides a large page with a non-editable summary of the fields of each bug." }, { "code": null, "e": 56876, "s": 56780, "text": "By clicking on XML (icon), it converts the bug list displayed in table format as an XML format." }, { "code": null, "e": 56988, "s": 56876, "text": "It converts the bug list as comma-separated values, which can be imported into a spreadsheet or an excel sheet." }, { "code": null, "e": 57169, "s": 56988, "text": "It displays the bug list as an Atom Feed. The user can Copy this link into their favourite feed reader. To limit the number of bugs in the feed, add a limit=n parameter to the URL." }, { "code": null, "e": 57336, "s": 57169, "text": "If the user is using Firefox, get an option as save the list as a live bookmark by clicking the live bookmark icon in the status bar as shown in the screenshot below." }, { "code": null, "e": 57413, "s": 57336, "text": "To limit the number of bugs in the feed, add a limit=n parameter to the URL." }, { "code": null, "e": 57456, "s": 57413, "text": "Only the first bug is displayed as a Feed." }, { "code": null, "e": 57680, "s": 57456, "text": "It displays the bug list as an iCalendar file. Each bug is represented as a to–do item in the imported calendar. It is supported in Outlook only. The user can access this feature only if Outlook is configured in the system." }, { "code": null, "e": 57890, "s": 57680, "text": "It changes the bug attributes that appear in the list. The user can customize the view of a Bug List using this option. By clicking on the Change Columns button, the following page displays the user selection." }, { "code": null, "e": 58094, "s": 57890, "text": "The User can select one or multiple columns from the Available Columns section. These should display in the bug list. Then click on → (right arrow) to show this selection in the Selected Columns section." }, { "code": null, "e": 58205, "s": 58094, "text": "Similarly, the user can deselect any of the columns from the selected columns and click on the ← (left arrow)." }, { "code": null, "e": 58362, "s": 58205, "text": "The user can change the appearing order of the columns as well by clicking on move up and down arrow at the right hand side of the Selected Columns section." }, { "code": null, "e": 58541, "s": 58362, "text": "By clicking on the Change Columns button, the bug list will be customized. Else, if the user clicks on the Reset to Bugzilla Default, it will change back to the Default settings." }, { "code": null, "e": 58770, "s": 58541, "text": "If an account is sufficiently empowered and more than one bug appears in the bug list, Change Several Bugs At Once is displayed and easily makes the same change to all the bugs in the list – for example, changing their Priority." }, { "code": null, "e": 59045, "s": 58770, "text": "If more than one bug appears in the bug list and there are at least two different bug assignees, this link is displayed. By clicking on this link, Outlook opens, if it is configured or it asks to configure the Outlook to send a mail to the assignees of all bugs on the list." }, { "code": null, "e": 59240, "s": 59045, "text": "If the user did not get the exact results he were looking for, the user can return to the Search page through this link and make small revisions to the search parameters to get accurate results." }, { "code": null, "e": 59375, "s": 59240, "text": "The user can give the Search, a name and remember it; a link will appear in the page footer giving quick access to run it again later." }, { "code": null, "e": 59532, "s": 59375, "text": "Preferences in Bugzilla are used to customize the default settings of Bugzilla as per requirement and guidelines. It can also be called as User Preferences." }, { "code": null, "e": 59580, "s": 59532, "text": "There are two ways to navigate on Preferences −" }, { "code": null, "e": 59666, "s": 59580, "text": "The first way is to click on the Preferences hyperlink in the header of the homepage." }, { "code": null, "e": 59771, "s": 59666, "text": "The second way is to click on the User Preferences button, which is displayed on the Welcome Page Icons." }, { "code": null, "e": 59941, "s": 59771, "text": "By clicking on one of the links outlined (in red color) in the following screenshot, they will display different types of Preference that can be customized by the users." }, { "code": null, "e": 60004, "s": 59941, "text": "Bugzilla supports the following six types of User Preferences." }, { "code": null, "e": 60024, "s": 60004, "text": "General Preferences" }, { "code": null, "e": 60042, "s": 60024, "text": "Email Preferences" }, { "code": null, "e": 60057, "s": 60042, "text": "Saved Searches" }, { "code": null, "e": 60077, "s": 60057, "text": "Account Information" }, { "code": null, "e": 60086, "s": 60077, "text": "API Keys" }, { "code": null, "e": 60098, "s": 60086, "text": "Permissions" }, { "code": null, "e": 60182, "s": 60098, "text": "In the next chapter, we will discuss regarding the General Preferences of Bugzilla." }, { "code": null, "e": 60379, "s": 60182, "text": "General Preferences allows changing several default settings of Bugzilla. Administrators have the power to remove preferences from this list, so the user may not see all the preferences available." }, { "code": null, "e": 60594, "s": 60379, "text": "To navigate to General Preferences, click on Preferences or User Preferences from the Homepage of Bugzilla. By Default, the General Preferences tab opens with different preferences as shown in the screenshot below." }, { "code": null, "e": 60734, "s": 60594, "text": "Each preference is very straightforward and self-explanatory. The user can easily understand the field and select the option from the list." }, { "code": null, "e": 60841, "s": 60734, "text": "For example – To set “Automatically Add me to CC list of bugs I change”, select Always from dropdown list." }, { "code": null, "e": 60924, "s": 60841, "text": "Click on Submit Changes button, which is at the bottom left hand side of the page." }, { "code": null, "e": 61065, "s": 60924, "text": "A successful message will appear that says – “The changes to your general preferences have been saved” as shown in the following screenshot." }, { "code": null, "e": 61133, "s": 61065, "text": "Similarly, other General preferences can be changed simultaneously." }, { "code": null, "e": 61548, "s": 61133, "text": "The Email Preferences feature in Bugzilla allows to enable or disable email notifications on specific events. In general, the users have almost complete control over how many emails Bugzilla sends them. If the users want to receive the maximum number of emails possible, click on the Enable All Mail button. If the user does not want to receive any email from Bugzilla at all, click on the Disable All Mail button." }, { "code": null, "e": 61662, "s": 61548, "text": "To navigate, go to Preferences/User Preferences option on the home screen and click on the Email Preferences tab." }, { "code": null, "e": 61794, "s": 61662, "text": "There are two Global Options; where the user can check the checkboxes based on their requirement to get emails. These options are −" }, { "code": null, "e": 61842, "s": 61794, "text": "Email me when someone asks me to set a flag and" }, { "code": null, "e": 61889, "s": 61842, "text": "Email me when someone sets a flag I asked for." }, { "code": null, "e": 62106, "s": 61889, "text": "These define how a user wants to receive the bug emails concerning the flags. Their use is quite straightforward: enable the checkboxes, if the user wants Bugzilla to send a mail under either of the above conditions." }, { "code": null, "e": 62225, "s": 62106, "text": "Similarly, a user can check the checkboxes for Field/recipient specific options based on “I want to receive mail when”" }, { "code": null, "e": 62598, "s": 62225, "text": "Bugzilla has a feature called as User Watching. When the user enters one or more comma delineated other user accounts (usually email addresses) into the text entry box, the user will receive a copy of all the bug emails those other users are sent. This powerful functionality is very important and useful in case if the developers change projects or users go on a holiday." }, { "code": null, "e": 62984, "s": 62598, "text": "User can mention a list of bugs from those never wants to get any email notification of any kind. For this, user needs to add Bug ID(s) as a comma-separated list. User can remove a bug from the current ignored list at any time and it will re-enable email notifications for the bug. After selections are made, click on the Submit Changes button at the bottom left hand side of the page." }, { "code": null, "e": 63111, "s": 62984, "text": "A successful message will display as “The changes to your email preferences have been saved” as shown in the screenshot below." }, { "code": null, "e": 63299, "s": 63111, "text": "In this Tab, the user can view and run any Saved Searches, which are created by the user as well as any Saved Searches that other members of the group have defined in the querysharegroup." }, { "code": null, "e": 63380, "s": 63299, "text": "For the Saved Searches tab, go to Preferences → click on the Saved Searches tab." }, { "code": null, "e": 63504, "s": 63380, "text": "The user can run his bug from the Saved Searches by clicking on the RUN command as highlighted in the following screenshot." }, { "code": null, "e": 63572, "s": 63504, "text": "After you click on RUN, the bug list page displays as shown below −" }, { "code": null, "e": 63854, "s": 63572, "text": "Saved Searches can be added to the page footer from this screen. If somebody is sharing a Search with a group, the sharer may choose Show in Footer by checking the checkbox of a different Saved Search. Based on the permissions, other members can choose the Show in Footer checkbox." }, { "code": null, "e": 63987, "s": 63854, "text": "Once all the changes and selections are made, click on the Submit Changes button, which is on the bottom left hand side of the page." }, { "code": null, "e": 64108, "s": 63987, "text": "A successful message “The changes to your Saved searches have been saved” will show as seen in the following screenshot." }, { "code": null, "e": 64286, "s": 64108, "text": "In this Tab, the users can view their account information, which were provided at the time of registration. It also provides a feature where the users can change their password." }, { "code": null, "e": 64355, "s": 64286, "text": "To change the account password, the following entries are required −" }, { "code": null, "e": 64432, "s": 64355, "text": "Provide the Current password in the Password text box to verify the account." }, { "code": null, "e": 64482, "s": 64432, "text": "Enter a new password in the field – New password." }, { "code": null, "e": 64543, "s": 64482, "text": "Re-enter the new password in the Confirm new password field." }, { "code": null, "e": 64628, "s": 64543, "text": "A user can change the name in the ‘Your real name (optional, but encouraged)’ field." }, { "code": null, "e": 64654, "s": 64628, "text": "Provide an email address." }, { "code": null, "e": 64746, "s": 64654, "text": "Once all entries are made, click on Submit Changes as depicted in the following screenshot." }, { "code": null, "e": 64878, "s": 64746, "text": "A successful message is displayed as “The changes to your account information has been saved” as shown in the following screenshot." }, { "code": null, "e": 65093, "s": 64878, "text": "In this Tab, a user can see all the permissions, which are provided by the Admin. The Admin can have all the permissions and based on the role of the user, the admin provides different permissions to various users." }, { "code": null, "e": 65136, "s": 65093, "text": "In this case, a user has two permissions −" }, { "code": null, "e": 65168, "s": 65136, "text": "canconfirm − can confirm a log." }, { "code": null, "e": 65200, "s": 65168, "text": "canconfirm − can confirm a log." }, { "code": null, "e": 65242, "s": 65200, "text": "editbugs − can edit all aspects of a bug." }, { "code": null, "e": 65284, "s": 65242, "text": "editbugs − can edit all aspects of a bug." }, { "code": null, "e": 65394, "s": 65284, "text": "Similarly, a user can view different permission names and it has a straightforward explanation to understand." }, { "code": null, "e": 65401, "s": 65394, "text": " Print" }, { "code": null, "e": 65412, "s": 65401, "text": " Add Notes" } ]
3 Lines of Python Code to Write A Web Server | by Christopher Tao | Towards Data Science
You must know that Python can be used to write web servers very effectively. It is known that there are many popular and excellent frameworks and libraries such as Django and Flask, which allows backend developers to focus on the business logic and save a lot of time on coding. However, have you ever know that Python’s built-in library http.server that can also be used to write a web server? Also, do you know that you may even write one with only three lines of code? In this article, I’ll show you how to write a web server and run it in ONE minute! The web server will need to be started somewhere, so you need to think about where you want to start it. Then, you probably want to put your code over there. Also, we will need to import the http.server library. Optionally, it is recommended to import the os library to make sure that the webserver is indeed running in the “current” directory. In other words, using the current directory as the root path of the webserver. import osfrom http.server import HTTPServer, CGIHTTPRequestHandler From the http.server library, we need the HTTPServer class to instantiate the server object, as well as the CGIHTTPRequestHandler class as the request handler. If you don’t know what is CGI, here is a brief definition from Wikipedia: In computing, Common Gateway Interface (CGI) is an interface specification for web servers to execute programs like console applications (also called command-line interface programs) running on a server that generates web pages dynamically. Such programs are known as CGI scripts or simply as CGIs. The specifics of how the script is executed by the server are determined by the server. In the common case, a CGI script executes at the time a request is made and generates HTML.[1] Then, let’s code the server in three lines of code, no kidding. Let’s make sure that the server is created at the current directory and use it as the root path. os.chdir() method will set the path as the current working directory. Here we set the ., which is the current directory as its working directory. # Make sure the server is created at current directoryos.chdir('.') Let’s create a “server object” from the HTTPServer class. It takes two arguments, the first one is the server_address which is a tuple of The address that listens to, where the empty string means listen to localhost The port number that listens to. I’ll use port 80 so I don’t have to input the port number to access. It is up to you to use other port numbers such as 8080 # Create server object listening the port 80server_object = HTTPServer(server_address=('', 80), RequestHandlerClass=CGIHTTPRequestHandler) The second argument is the request handler class. Here we use CGIHTTPRequestHandler that we have already imported. Nothing else, let’s run it! # Start the web serverserver_object.serve_forever() The serve_forever() method will start the server based on the server object we have just created and make sure it is constantly running. Here is all the code:import osfrom http.server import HTTPServer, CGIHTTPRequestHandler# Make sure the server is created at current directoryos.chdir('.')# Create server object listening the port 80server_object = HTTPServer(server_address=('', 80), RequestHandlerClass=CGIHTTPRequestHandler)# Start the web serverserver_object.serve_forever() Save all the code into a file called pyserver.py. Then, go to the command line and run the Python script. python pyserver.py You will see nothing comes out in the stdout, that is expected. Go to your browser and type in localhost, the webserver is already working. So, this web server will allow you to browse files from the root path. Now, you may ask why I need this webserver? Right, it is not that useful. But think about what you can do with a web browser? For example, I use to download some academic research papers which are usually in PDF format. You’ll find that navigating between sub-folders and opening PDF files in a web browser is much faster than using Windows Explorer and Mac OS Finder. Also, in this example, we’re running the web server on the local machine. If you could run this Python script on a remote machine, then you got a very quick file sharing server! In this article, I have introduced how to use only three lines of Python code to write a web server that allows you to browse the files on the server. However, it needs to be conscious that the http.server with such a simple implementation cannot be secure. Therefore, please do not use only these three lines of code in an important environment, which might become a security hole that potentially can be hacked. medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above) [1] Common Gateway Interface, Wikipedia https://en.wikipedia.org/wiki/Common_Gateway_Interface
[ { "code": null, "e": 450, "s": 171, "text": "You must know that Python can be used to write web servers very effectively. It is known that there are many popular and excellent frameworks and libraries such as Django and Flask, which allows backend developers to focus on the business logic and save a lot of time on coding." }, { "code": null, "e": 726, "s": 450, "text": "However, have you ever know that Python’s built-in library http.server that can also be used to write a web server? Also, do you know that you may even write one with only three lines of code? In this article, I’ll show you how to write a web server and run it in ONE minute!" }, { "code": null, "e": 884, "s": 726, "text": "The web server will need to be started somewhere, so you need to think about where you want to start it. Then, you probably want to put your code over there." }, { "code": null, "e": 1150, "s": 884, "text": "Also, we will need to import the http.server library. Optionally, it is recommended to import the os library to make sure that the webserver is indeed running in the “current” directory. In other words, using the current directory as the root path of the webserver." }, { "code": null, "e": 1217, "s": 1150, "text": "import osfrom http.server import HTTPServer, CGIHTTPRequestHandler" }, { "code": null, "e": 1377, "s": 1217, "text": "From the http.server library, we need the HTTPServer class to instantiate the server object, as well as the CGIHTTPRequestHandler class as the request handler." }, { "code": null, "e": 1451, "s": 1377, "text": "If you don’t know what is CGI, here is a brief definition from Wikipedia:" }, { "code": null, "e": 1933, "s": 1451, "text": "In computing, Common Gateway Interface (CGI) is an interface specification for web servers to execute programs like console applications (also called command-line interface programs) running on a server that generates web pages dynamically. Such programs are known as CGI scripts or simply as CGIs. The specifics of how the script is executed by the server are determined by the server. In the common case, a CGI script executes at the time a request is made and generates HTML.[1]" }, { "code": null, "e": 1997, "s": 1933, "text": "Then, let’s code the server in three lines of code, no kidding." }, { "code": null, "e": 2240, "s": 1997, "text": "Let’s make sure that the server is created at the current directory and use it as the root path. os.chdir() method will set the path as the current working directory. Here we set the ., which is the current directory as its working directory." }, { "code": null, "e": 2308, "s": 2240, "text": "# Make sure the server is created at current directoryos.chdir('.')" }, { "code": null, "e": 2446, "s": 2308, "text": "Let’s create a “server object” from the HTTPServer class. It takes two arguments, the first one is the server_address which is a tuple of" }, { "code": null, "e": 2524, "s": 2446, "text": "The address that listens to, where the empty string means listen to localhost" }, { "code": null, "e": 2681, "s": 2524, "text": "The port number that listens to. I’ll use port 80 so I don’t have to input the port number to access. It is up to you to use other port numbers such as 8080" }, { "code": null, "e": 2820, "s": 2681, "text": "# Create server object listening the port 80server_object = HTTPServer(server_address=('', 80), RequestHandlerClass=CGIHTTPRequestHandler)" }, { "code": null, "e": 2935, "s": 2820, "text": "The second argument is the request handler class. Here we use CGIHTTPRequestHandler that we have already imported." }, { "code": null, "e": 2963, "s": 2935, "text": "Nothing else, let’s run it!" }, { "code": null, "e": 3015, "s": 2963, "text": "# Start the web serverserver_object.serve_forever()" }, { "code": null, "e": 3152, "s": 3015, "text": "The serve_forever() method will start the server based on the server object we have just created and make sure it is constantly running." }, { "code": null, "e": 3496, "s": 3152, "text": "Here is all the code:import osfrom http.server import HTTPServer, CGIHTTPRequestHandler# Make sure the server is created at current directoryos.chdir('.')# Create server object listening the port 80server_object = HTTPServer(server_address=('', 80), RequestHandlerClass=CGIHTTPRequestHandler)# Start the web serverserver_object.serve_forever()" }, { "code": null, "e": 3602, "s": 3496, "text": "Save all the code into a file called pyserver.py. Then, go to the command line and run the Python script." }, { "code": null, "e": 3621, "s": 3602, "text": "python pyserver.py" }, { "code": null, "e": 3761, "s": 3621, "text": "You will see nothing comes out in the stdout, that is expected. Go to your browser and type in localhost, the webserver is already working." }, { "code": null, "e": 3832, "s": 3761, "text": "So, this web server will allow you to browse files from the root path." }, { "code": null, "e": 4201, "s": 3832, "text": "Now, you may ask why I need this webserver? Right, it is not that useful. But think about what you can do with a web browser? For example, I use to download some academic research papers which are usually in PDF format. You’ll find that navigating between sub-folders and opening PDF files in a web browser is much faster than using Windows Explorer and Mac OS Finder." }, { "code": null, "e": 4379, "s": 4201, "text": "Also, in this example, we’re running the web server on the local machine. If you could run this Python script on a remote machine, then you got a very quick file sharing server!" }, { "code": null, "e": 4530, "s": 4379, "text": "In this article, I have introduced how to use only three lines of Python code to write a web server that allows you to browse the files on the server." }, { "code": null, "e": 4793, "s": 4530, "text": "However, it needs to be conscious that the http.server with such a simple implementation cannot be secure. Therefore, please do not use only these three lines of code in an important environment, which might become a security hole that potentially can be hacked." }, { "code": null, "e": 4804, "s": 4793, "text": "medium.com" }, { "code": null, "e": 4952, "s": 4804, "text": "If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)" } ]
TCS Coding Practice Question | HCF or GCD of 2 Numbers - GeeksforGeeks
09 Apr, 2019 Given two numbers, the task is to find the HCF of two numbers using Command Line Arguments. GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. Examples: Input: n1 = 10, n2 = 20 Output: 10 Input: n1 = 100, n2 = 101 Output: 1 Approach: Since the numbers are entered as Command line Arguments, there is no need for a dedicated input line Extract the input numbers from the command line argument This extracted numbers will be in String type. Convert these numbers into integer type and store it in variables, say num1 and num2 Find the HCF of the numbers. An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number. Print or return the HCF Program: C Java // C program to compute the HCF of two numbers// using command line arguments #include <stdio.h>#include <stdlib.h> /* atoi */ // Function to compute the HCF of two numbersint HCF(int a, int b){ if (b == 0) return a; return HCF(b, a % b);} // Driver codeint main(int argc, char* argv[]){ int num1, num2; // Check if the length of args array is 1 if (argc == 1) printf("No command line arguments found.\n"); else { // Get the command line argument and // Convert it from string type to integer type // using function "atoi( argument)" num1 = atoi(argv[1]); num2 = atoi(argv[2]); // Find the HCF and print it printf("%d\n", HCF(num1, num2)); } return 0;} // Java program to compute the HCF of two numbers// using command line arguments class GFG { // Function to compute the HCF of two numbers static int HCF(int a, int b) { if (b == 0) return a; return HCF(b, a % b); } // Driver code public static void main(String[] args) { // Check if length of args array is // greater than 0 if (args.length > 0) { // Get the command line argument and // Convert it from string type to integer type int num1 = Integer.parseInt(args[0]); int num2 = Integer.parseInt(args[1]); // Find the HCF int res = HCF(num1, num2); // Print the HCF System.out.println(res); } else System.out.println("No command line " + "arguments found."); }} In C: In Java: TCS TCS-coding-questions C++ Programs Java Programs Placements TCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Program for QuickSort cin in C++ delete keyword in C++ Shallow Copy and Deep Copy in C++ Check if given number is perfect square Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24785, "s": 24757, "text": "\n09 Apr, 2019" }, { "code": null, "e": 25002, "s": 24785, "text": "Given two numbers, the task is to find the HCF of two numbers using Command Line Arguments. GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them." }, { "code": null, "e": 25012, "s": 25002, "text": "Examples:" }, { "code": null, "e": 25085, "s": 25012, "text": "Input: n1 = 10, n2 = 20\nOutput: 10\n\nInput: n1 = 100, n2 = 101\nOutput: 1\n" }, { "code": null, "e": 25095, "s": 25085, "text": "Approach:" }, { "code": null, "e": 25196, "s": 25095, "text": "Since the numbers are entered as Command line Arguments, there is no need for a dedicated input line" }, { "code": null, "e": 25253, "s": 25196, "text": "Extract the input numbers from the command line argument" }, { "code": null, "e": 25300, "s": 25253, "text": "This extracted numbers will be in String type." }, { "code": null, "e": 25385, "s": 25300, "text": "Convert these numbers into integer type and store it in variables, say num1 and num2" }, { "code": null, "e": 25618, "s": 25385, "text": "Find the HCF of the numbers. An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number." }, { "code": null, "e": 25642, "s": 25618, "text": "Print or return the HCF" }, { "code": null, "e": 25651, "s": 25642, "text": "Program:" }, { "code": null, "e": 25653, "s": 25651, "text": "C" }, { "code": null, "e": 25658, "s": 25653, "text": "Java" }, { "code": "// C program to compute the HCF of two numbers// using command line arguments #include <stdio.h>#include <stdlib.h> /* atoi */ // Function to compute the HCF of two numbersint HCF(int a, int b){ if (b == 0) return a; return HCF(b, a % b);} // Driver codeint main(int argc, char* argv[]){ int num1, num2; // Check if the length of args array is 1 if (argc == 1) printf(\"No command line arguments found.\\n\"); else { // Get the command line argument and // Convert it from string type to integer type // using function \"atoi( argument)\" num1 = atoi(argv[1]); num2 = atoi(argv[2]); // Find the HCF and print it printf(\"%d\\n\", HCF(num1, num2)); } return 0;}", "e": 26413, "s": 25658, "text": null }, { "code": "// Java program to compute the HCF of two numbers// using command line arguments class GFG { // Function to compute the HCF of two numbers static int HCF(int a, int b) { if (b == 0) return a; return HCF(b, a % b); } // Driver code public static void main(String[] args) { // Check if length of args array is // greater than 0 if (args.length > 0) { // Get the command line argument and // Convert it from string type to integer type int num1 = Integer.parseInt(args[0]); int num2 = Integer.parseInt(args[1]); // Find the HCF int res = HCF(num1, num2); // Print the HCF System.out.println(res); } else System.out.println(\"No command line \" + \"arguments found.\"); }}", "e": 27306, "s": 26413, "text": null }, { "code": null, "e": 27312, "s": 27306, "text": "In C:" }, { "code": null, "e": 27321, "s": 27312, "text": "In Java:" }, { "code": null, "e": 27325, "s": 27321, "text": "TCS" }, { "code": null, "e": 27346, "s": 27325, "text": "TCS-coding-questions" }, { "code": null, "e": 27359, "s": 27346, "text": "C++ Programs" }, { "code": null, "e": 27373, "s": 27359, "text": "Java Programs" }, { "code": null, "e": 27384, "s": 27373, "text": "Placements" }, { "code": null, "e": 27388, "s": 27384, "text": "TCS" }, { "code": null, "e": 27486, "s": 27388, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27495, "s": 27486, "text": "Comments" }, { "code": null, "e": 27508, "s": 27495, "text": "Old Comments" }, { "code": null, "e": 27534, "s": 27508, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27545, "s": 27534, "text": "cin in C++" }, { "code": null, "e": 27567, "s": 27545, "text": "delete keyword in C++" }, { "code": null, "e": 27601, "s": 27567, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 27641, "s": 27601, "text": "Check if given number is perfect square" }, { "code": null, "e": 27685, "s": 27641, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27713, "s": 27685, "text": "Initializing a List in Java" }, { "code": null, "e": 27739, "s": 27713, "text": "Java Programming Examples" }, { "code": null, "e": 27773, "s": 27739, "text": "Convert Double to Integer in Java" } ]
Find numbers a and b that satisfy the given condition in C++
Consider we have an integer n. Our task is to find two numbers a and b, where these three conditions will be satisfied. a mod b = 0 a * b > n a / b < n If no pair is found, print -1. For an example, if the number n = 10, then a and b can be a = 90, b = 10. This satisfies given rules. To solve this problem, we will follow these steps − Let b = n. a can be found using these three conditions a mod b = 0 when a is multiple of b a / b < n, so a / b = n – 1 which is < n (a * b > n) => a = n #include<iostream> using namespace std; void findAandB(int n) { int b = n; int a = b * (n - 1); if (a * b > n && a / b < n) { cout << "a: " << a << endl; cout << "b: " << b; }else cout << -1 << endl; } int main() { int n = 10; findAandB(n); } a: 90 b: 10
[ { "code": null, "e": 1182, "s": 1062, "text": "Consider we have an integer n. Our task is to find two numbers a and b, where these three conditions will be satisfied." }, { "code": null, "e": 1194, "s": 1182, "text": "a mod b = 0" }, { "code": null, "e": 1204, "s": 1194, "text": "a * b > n" }, { "code": null, "e": 1214, "s": 1204, "text": "a / b < n" }, { "code": null, "e": 1245, "s": 1214, "text": "If no pair is found, print -1." }, { "code": null, "e": 1347, "s": 1245, "text": "For an example, if the number n = 10, then a and b can be a = 90, b = 10. This satisfies given rules." }, { "code": null, "e": 1399, "s": 1347, "text": "To solve this problem, we will follow these steps −" }, { "code": null, "e": 1454, "s": 1399, "text": "Let b = n. a can be found using these three conditions" }, { "code": null, "e": 1490, "s": 1454, "text": "a mod b = 0 when a is multiple of b" }, { "code": null, "e": 1531, "s": 1490, "text": "a / b < n, so a / b = n – 1 which is < n" }, { "code": null, "e": 1552, "s": 1531, "text": "(a * b > n) => a = n" }, { "code": null, "e": 1834, "s": 1552, "text": "#include<iostream>\nusing namespace std;\nvoid findAandB(int n) {\n int b = n;\n int a = b * (n - 1);\n if (a * b > n && a / b < n) {\n cout << \"a: \" << a << endl;\n cout << \"b: \" << b;\n }else\n cout << -1 << endl;\n }\nint main() {\n int n = 10;\n findAandB(n);\n}" }, { "code": null, "e": 1846, "s": 1834, "text": "a: 90\nb: 10" } ]
How to create a JavaScript code for multiple keys pressed at once?
Use the keydown event in JavaScript to get to know which keys are pressed at once. The following is the script − var log = $('#log')[0], keyPressed = []; $(document.body).keydown(function (evt) { var li = keyPressed [evt.keyCode]; if (!li) { li = log.appendChild(document.createElement('li')); keyPressed [evt.keyCode] = li; } $(li).text(Key Down: ' + evt.keyCode); $(li).removeClass('key-up'); }); $(document.body).keyup(function (evt) { var li = keyPressed [evt.keyCode]; if (!li) { li = log.appendChild(document.createElement('li')); } $(li).text('Key Up: ' + evt.keyCode); $(li).addClass('key-up'); });
[ { "code": null, "e": 1175, "s": 1062, "text": "Use the keydown event in JavaScript to get to know which keys are pressed at once. The following is the script −" }, { "code": null, "e": 1722, "s": 1175, "text": "var log = $('#log')[0],\n keyPressed = [];\n\n$(document.body).keydown(function (evt) {\n var li = keyPressed [evt.keyCode];\n if (!li) {\n li = log.appendChild(document.createElement('li'));\n keyPressed [evt.keyCode] = li;\n }\n $(li).text(Key Down: ' + evt.keyCode);\n $(li).removeClass('key-up');\n});\n\n$(document.body).keyup(function (evt) {\n var li = keyPressed [evt.keyCode];\n if (!li) {\n li = log.appendChild(document.createElement('li'));\n }\n $(li).text('Key Up: ' + evt.keyCode);\n $(li).addClass('key-up');\n});" } ]
React useReducer Hook
The useReducer Hook is similar to the useState Hook. It allows for custom state logic. If you find yourself keeping track of multiple pieces of state that rely on complex logic, useReducer may be useful. The useReducer Hook accepts two arguments. useReducer(<reducer>, <initialState>) The reducer function contains your custom state logic and the initialStatecan be a simple value but generally will contain an object. The useReducer Hook returns the current stateand a dispatchmethod. Here is an example of useReducer in a counter app: import { useReducer } from "react"; import ReactDOM from "react-dom/client"; const initialTodos = [ { id: 1, title: "Todo 1", complete: false, }, { id: 2, title: "Todo 2", complete: false, }, ]; const reducer = (state, action) => { switch (action.type) { case "COMPLETE": return state.map((todo) => { if (todo.id === action.id) { return { ...todo, complete: !todo.complete }; } else { return todo; } }); default: return state; } }; function Todos() { const [todos, dispatch] = useReducer(reducer, initialTodos); const handleComplete = (todo) => { dispatch({ type: "COMPLETE", id: todo.id }); }; return ( <> {todos.map((todo) => ( <div key={todo.id}> <label> <input type="checkbox" checked={todo.complete} onChange={() => handleComplete(todo)} /> {todo.title} </label> </div> ))} </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Todos />); Run Example » This is just the logic to keep track of the todo complete status. All of the logic to add, delete, and complete a todo could be contained within a single useReducer Hook by adding more actions. We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 53, "s": 0, "text": "The useReducer Hook is similar to the useState Hook." }, { "code": null, "e": 87, "s": 53, "text": "It allows for custom state logic." }, { "code": null, "e": 204, "s": 87, "text": "If you find yourself keeping track of multiple pieces of state that rely on complex logic, useReducer may be useful." }, { "code": null, "e": 247, "s": 204, "text": "The useReducer Hook accepts two arguments." }, { "code": null, "e": 285, "s": 247, "text": "useReducer(<reducer>, <initialState>)" }, { "code": null, "e": 419, "s": 285, "text": "The reducer function contains your custom state logic and the initialStatecan be a simple value but generally will contain an object." }, { "code": null, "e": 486, "s": 419, "text": "The useReducer Hook returns the current stateand a dispatchmethod." }, { "code": null, "e": 537, "s": 486, "text": "Here is an example of useReducer in a counter app:" }, { "code": null, "e": 1677, "s": 537, "text": "import { useReducer } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nconst initialTodos = [\n {\n id: 1,\n title: \"Todo 1\",\n complete: false,\n },\n {\n id: 2,\n title: \"Todo 2\",\n complete: false,\n },\n];\n\nconst reducer = (state, action) => {\n switch (action.type) {\n case \"COMPLETE\":\n return state.map((todo) => {\n if (todo.id === action.id) {\n return { ...todo, complete: !todo.complete };\n } else {\n return todo;\n }\n });\n default:\n return state;\n }\n};\n\nfunction Todos() {\n const [todos, dispatch] = useReducer(reducer, initialTodos);\n\n const handleComplete = (todo) => {\n dispatch({ type: \"COMPLETE\", id: todo.id });\n };\n\n return (\n <>\n {todos.map((todo) => (\n <div key={todo.id}>\n <label>\n <input\n type=\"checkbox\"\n checked={todo.complete}\n onChange={() => handleComplete(todo)}\n />\n {todo.title}\n </label>\n </div>\n ))}\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Todos />);\n" }, { "code": null, "e": 1694, "s": 1677, "text": "\nRun \nExample »\n" }, { "code": null, "e": 1760, "s": 1694, "text": "This is just the logic to keep track of the todo complete status." }, { "code": null, "e": 1888, "s": 1760, "text": "All of the logic to add, delete, and complete a todo could be contained within a single\nuseReducer Hook by adding more actions." }, { "code": null, "e": 1921, "s": 1888, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1963, "s": 1921, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2070, "s": 1963, "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": 2089, "s": 2070, "text": "help@w3schools.com" } ]
How to add new keys to a dictionary in Python?
Dictionary is an unordered collection of key-value pairs. Each element is not identified by positional index. Moreover, the fact that key can’t be repeated, we simply use a new key and assign a value to it so that a new pair will be added to dictionary. >>> D1 = {1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3} >>> D1[10] = 'z' >>> D1 {1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3, 10: 'z'}
[ { "code": null, "e": 1316, "s": 1062, "text": "Dictionary is an unordered collection of key-value pairs. Each element is not identified by positional index. Moreover, the fact that key can’t be repeated, we simply use a new key and assign a value to it so that a new pair will be added to dictionary." }, { "code": null, "e": 1456, "s": 1316, "text": ">>> D1 = {1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3}\n>>> D1[10] = 'z'\n>>> D1\n{1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3, 10: 'z'}" } ]
Addition and Blending of images using OpenCv in Python
We know that when we solve any image related problem, we have to take a matrix. The matrix content will vary depending upon the image type - either it would be a binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So if we want to add of two images then that means very simple we have to add respective two matrices. In OpenCV library, we have a function cv2.add() to add the images. But for image addition the size of the two images should be same. import cv2 # Readingour Image1 my_firstpic = cv2.imread('C:/Users/TP/Pictures/west bengal/bishnupur/mqdefaultILPT6GSR.jpg', 1) cv2.imshow('image', my_firstpic) # Readingour Image2 my_secpic = cv2.imread('C:/Users/Satyajit/Pictures/west bengal/bishnupur/pp.jpg', 1) img = cv2.add(my_firstpic,my_secpic) cv2.waitKey(0) cv2.distroyAllWindows() cv2.addWeighted() function is used for blending of two images. import cv2 # Read our Image1 My_first = cv2.imread('C:/Users/TP/Pictures/west bengal/bishnupur/mqdefaultILPT6GSR.jpg', 1) # Reading ourImage2 My_second = cv2.imread('C:/Users/TP/Pictures/west bengal/bishnupur/pp.jpg', 1) # Blending the images with 0.3 and 0.7 My_img = cv2.addWeighted(My_first, 0.3, My_second, 0.7, 0) # Show the image cv2.imshow('image', My_img) # Wait for a key cv2.waitKey(0) # Destroy all the window open cv2.distroyAllWindows()
[ { "code": null, "e": 1398, "s": 1062, "text": "We know that when we solve any image related problem, we have to take a matrix. The matrix content will vary depending upon the image type - either it would be a binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So if we want to add of two images then that means very simple we have to add respective two matrices." }, { "code": null, "e": 1531, "s": 1398, "text": "In OpenCV library, we have a function cv2.add() to add the images. But for image addition the size of the two images should be same." }, { "code": null, "e": 1872, "s": 1531, "text": "import cv2\n# Readingour Image1\nmy_firstpic = cv2.imread('C:/Users/TP/Pictures/west bengal/bishnupur/mqdefaultILPT6GSR.jpg', 1)\ncv2.imshow('image', my_firstpic)\n# Readingour Image2\nmy_secpic = cv2.imread('C:/Users/Satyajit/Pictures/west bengal/bishnupur/pp.jpg', 1)\nimg = cv2.add(my_firstpic,my_secpic)\ncv2.waitKey(0)\ncv2.distroyAllWindows()" }, { "code": null, "e": 1935, "s": 1872, "text": "cv2.addWeighted() function is used for blending of two images." }, { "code": null, "e": 2385, "s": 1935, "text": "import cv2\n# Read our Image1\nMy_first = cv2.imread('C:/Users/TP/Pictures/west bengal/bishnupur/mqdefaultILPT6GSR.jpg', 1)\n# Reading ourImage2\nMy_second = cv2.imread('C:/Users/TP/Pictures/west bengal/bishnupur/pp.jpg', 1)\n# Blending the images with 0.3 and 0.7\nMy_img = cv2.addWeighted(My_first, 0.3, My_second, 0.7, 0)\n# Show the image\ncv2.imshow('image', My_img)\n# Wait for a key\ncv2.waitKey(0)\n# Destroy all the window open\ncv2.distroyAllWindows()" } ]
Explaining K-Means Clustering. Comparing PCA and t-SNE dimensionality... | by Kamil Mysiak | Towards Data Science
Today’s data comes in all shapes and sizes. NLP data encompasses the written word, time-series data tracks sequential data movement over time (ie. stocks), structured data which allows computers to learn by example, and unclassified data allows the computer to apply structure. Whichever dataset you possess, you can be sure there is an algorithm ready to decipher its secrets. In this article, we want to cover a clustering algorithm named KMeans which attempts to uncover hidden subgroups hiding in your dataset. Furthermore, we will examine what effects dimension reduction has on the quality of the clusters obtained from KMeans. In our example, we will be examining a human resources dataset consisting of 15,000 individual employees. The dataset contains employee job characteristics such as job satisfaction, performance score, workload, years of tenure, accidents, number of promotions. We will apply KMeans in order to uncover similar groups of employees. Classification problems will have target labels which we are trying to predict. Famous datasets such as Titanic and Iris are both prime for classification as they both have targets we are trying to predict (ie. survived and species). Furthermore, classification tasks require us to split our data into training and test, where the classifier is trained on the training data and then its performance is measured via the test dataset. When dealing with a clustering problem, we want to use an algorithm to uncover meaningful groups in our data. Perhaps we are trying to uncover customer segments or identify anomalies in our data. Either way, the algorithm uncovers the groups with little human intervention as we don’t have target labels to predict. That said, we can partner unsupervised clustering algorithms with supervised algorithms by first identifying groups/clusters and then building supervised models to predict the cluster membership. At its core, KMeans attempts to organize the data into a specified number of clusters. Unfortunately, it is up to us to determine the number of clusters we wish to find but fear not we have tools at our disposal that assist with this process. The goal of KMeans is to identify similar data points and cluster them together while trying to distance each cluster as far as possible. Its “similarity” calculation is determined via Euclidean distance or an ordinary straight line between two points (Wiki). The shorter the Euclidean distance the more similar the points are. First, the user (ie. you or I) determines the number of clusters KMeans needs to find. The number of clusters cannot exceed the number of features in the dataset. Next, KMeans will select a random point for each centroid. The number of centroids is equal to the number of clusters selected. The centroid is the point around which each cluster is built around. Second, the Euclidean distance is calculated between each point and each centroid. Each point will be initially assigned to the closest centroid/cluster based on the Euclidean distance. Each data point can belong to one cluster or centroid. The algorithm then averages Euclidean distance (between each point and centroid) for each cluster and this point becomes the new centroid. This process of averaging the Euclidean distances within clusters and assigning new centroids repeats until cluster centroids no longer move. The animation below shows the process, refresh the page if needed. We need to be aware of how KMeans selects the initial centroid/s and what problems might this produce. Without our intervention, KMeans will randomly select the initial centroid/s which ultimately can cause different resulting clusters on the same data. From the plots below we can see how running the KMeans algorithm on two different occasions resulted in different initial centroids. The same data points were assigned to different clusters between the first and second time running KMeans. Have no fear Sklearn has our backs! The Sklearn KMeans library has certain parameters such as “n_int” and “max_iter” to mitigate this issue. The “n_int” parameter determines the number of times KMeans will randomly select different centroids. “Max_iter” determines how many iterations will run. An iteration is the process of finding the distance, taking the average distance, and moving the centroid. If we set our parameters at n_int=25 and max_iter=200 KMeans will randomly select 25 initial centroids and run each centroid up to 200 iterations. The best out of those 25 centroids will be the final cluster. The Sklearn also has an “int” parameter which will select the first centroid at random and locate all the data points which are furthest away from the first centroid. Then, the second centroid is assigned nearby those far points as they are less likely to belong to the first centroid. Sklearn selects “int=kmeans++” by default which applies the above logic. “You mentioned something about needing to select the number of clusters....? Just how do we do that?” Domain Knowledge: Very often we have a certain level of knowledge and experience in the domain from which our dataset was gathered. This expertise can allow us to set the number of clusters we believe exists in the general population. Hypothesis Testing: Setting a specific number of clusters can also act as a test of a certain hypothesis we might have. For example, when analyzing marketing data we have a hunch there are 3 subgroups of customers who very likely, likely, and not likely to purchase our product. Data Comes Pre-Labeled: There are times when the data we are analyzing comes with pre-labeled targets. These datasets are typically used for supervised ML problems but that doesn’t mean we cannot cluster the data. Pre-labeled data is unique as you need to remove the targets from your initial analysis and then use them to validate how well the model clustered the data. Elbow Method: This is a very popular iterative statistical technique for determining the optimal number of clusters by actually running the K-Means algorithm for a range of cluster values. The elbow method calculates the sum of squared distances from each point to its assigned centroid for each iteration of KMeans. Each iteration runs through a different number of clusters. The result is a line chart that displays the sum of squared distances at each cluster. We want to select the number of clusters at the elbow of the line chart or the lowest sum of squared distances (ie. Inertia) at the lowest number of clusters. The lower the sum of squares distances means the data inside each cluster are more tightly grouped. KMeans is very sensitive to scale and requires all features to be on the same scale. KMeans will put more weight or emphasis on features with larger variances and those features will impose more influence on the final cluster shape. For example, let’s consider a dataset of car information such as weight (lbs) and horsepower (hp). If there is a larger variation in weight between all the cars the average Euclidean distance will be more affected by weight. Ultimately, the membership of each cluster will be more affected by weight than horsepower. Clustering algorithms such as KMeans have a difficult time accurately clustering data of high dimensionality (ie. too many features). Our dataset is not necessarily highly dimensional as it contains 7 features but even this amount will create issues for KMeans. I would suggest you explore the Curse of Dimensionality for more details. As we saw earlier, many clustering algorithms use a distance formula (ie. Euclidean distance) to determine cluster membership. When our clustering algorithm has too many dimensions, pairs of points will begin to have very similar distances and we wouldn’t be able to obtain meaningful clusters. In this example, we are going to compare PCA and t-SNE data reduction techniques prior to running our K-Means clustering algorithm. Let’s take a few mins to explain PCA and t-SNE. Principal component analysis or (PCA) is a classic method we can use to reduce high-dimensional data to a low-dimensional space. In other words, we simply cannot accurately visualize high-dimensional datasets because we cannot visualize anything above 3 features (1 feature=1D, 2 features = 2D, 3 features=3D plots). The main purpose behind PCA is to transform datasets with more than 3 features (high-dimensional) into typically a 2D or 3D plots for us feeble humans. That’s what is meant by low-dimensional space. The beauty behind PCA is the fact that despite the reduction into a lower-dimensional space we still retain most (+90%) of the variance or information from our original high-dimensional dataset. The information or variance from our original features is “squeezed” into what PCA calls principal components (PC). The first PC will contain the majority of the information from the original features. The second PC will contain the next largest amount of information, the 3rd PC the third largest amount of info and so on and so on. The PC are not correlated (ie. orthogonal) which means they all contain unique pieces of information. We can typically “squeeze” most (ie. 80–90%) of the information or variance contained in the original features into a few principal components. We use these principal components in our analyses instead of using the original features. This way we can perform an analysis with only 2 or 3 principal components instead of 50 features while still maintaining 80–90% of the information from our original features. Let’s take a look at some of the details behind how PCA does its magic. To make the explanation a bit easier let’s see how we can reduce a dataset with 2 features (ie. 2D) in one principal component (1D). That said, reducing 50 features into 3 or 4 principal components utilizes the same methodology. We have a 2D plot of weight and height. In other words, we have a dataset of 7 people and have plotted their height in relation to their weight. First, PCA needs to center the data by measuring the distances from each point to the y-axis (height) and x-axis (weight). It then calculates the average distance for both axes (ie. height and weight) and centers the data using these averages. Then PCA will plot the first principal component (PC1) or the best fitting line which maximizes the variance or the amount of information between weight and height. It determines the best fitting line by maximizing the distance from the point projected onto the best fitting line and the origin (ie. blue light below). It does it for each green point and then it squares each distance, to remove negative values, and sums everything up. The best-fitting line or PC1 will have the largest sum of squared distances from the origin to the projected points for all points. Now, we simply rotate the axes to where PC1 is now our x-axis and we are finished. If we wanted to reduce 3 features down to two principal components we would simply place a perpendicular (y-axis) to our best-fitting line in a 2D space. Why a perpendicular line? Because each principal component is orthogonal or uncorrelated with all other features. If we wanted to find a third principal component we would simply find another orthogonal line to PC1 and PC2 but this time in a 3D space. As you can see from the bar plot below, we initially began with a dataset of 5 features. Remember the number of principal components will always equal the number of features. However, we can see that the first 2 principal components account for 90% of the variance or information contained in the original 5 features. This is how we determine the optimal number of principal components. It is important to remember PCA is very often used for visualizing very high dimensional data (ie. thousands of features), therefore, you will most often see PCA of 2 or 3 principal components. Just like PCA, t-SNE takes high-dimensional data and reduces it to a low-dimensional graph (2-D typically). It is also a great dimensionality reduction technique. Unlike PCA, t-SNE can reduce dimensions with non-linear relationships. In other words, if our data had this “Swiss Roll” non-linear distribution where the change in X or Y does not correspond with a constant change in the other variable. PCA would not be able to accurately distill this data into principal components. This is because PCA would attempt to draw the best fitting line through the distribution. T-SNE would be a better solution in this case because it calculates a similarity measure based on the distance between points instead of trying to maximize variance. Let’s examine how t-SNE converts high dimensional data space into lower dimensions. It looks at the similarity between local or nearby points by observing the distance (think Euclidean distance). Points that are nearby each other are considered similar. t-SNE then converts this similarity distance for each pair of points into a probability for each pair of points. If two points are close to each other in the high-dimensional space they will have a high probability value and vice versa. This way the probability of picking a set of points is proportional to their similarity. Then each point gets randomly projected into a low dimensional space. For this example, we are plotting in a 1-D space but we can plot this in a 2-D or 3-D space as well. Why 2-D or 3-D? Because those are the only dimensions we (humans) can visualize. Remember t-SNE is a visualization tool first and a dimensionality reduction tool second. Finally, t-SNE calculates the similarity probability score in a low dimensional space in order to cluster the points together. The result is a 1-D plot we see below. One last thing we need to discuss about t-SNE is “Perplexity”, which is a required parameter when running the algorithm. “Perplexity” determines how broad or how tight of a space t-SNE captures similarities between points. If your perplexity is low (perhaps 2), t-SNE will only use two similar points and produce a plot with many scattered clusters. However, when we increase the perplexity to 10, t-SNE will consider 10 neighbor points as similar and cluster them together resulting in larger clusters of points. There is a point of diminishing returns where perplexity can become too large and we achieve a plot with one or two scattered clusters. At this point, t-SNE incorrectly considers points not necessarily related as belonging to a cluster. We typically set perplexity anywhere between 5 and 50, according to the original published paper (link). One of the main limitations of t-SNE is its high computational costs. If you have a very large feature set it might be good to first use PCA to reduce the number of features to a few principal components and then use t-SNE to further reduce the data to 2 or 3 clusters. Let’s get back to KMeans........ When using unsupervised ML algorithms we often cannot compare our results against a known true label. In other words, we do not have a test set to gauge the performance of our model. That said, we still need to understand how well K-Means managed to cluster our data. We already know how tightly the data is contained within our clusters by looking at the Elbow graph and the number of clusters we selected. Silhouette Method: This technique measures the separability between clusters. First, an average distance is found between each point and all other points in a cluster. Then it measures the distance between each point and each point in other clusters. We subtract the two average measures and divide by whichever average is larger. We ultimately want a high (ie. closest to 1) score which would indicate that there is a small intra-cluster average distance (tight clusters) and a large inter-cluster average distance (clusters well separated). Visual Cluster Interpretation: Once you have obtained your clusters it is very important to interpret each cluster. This is typically done by merging the original dataset with the clusters and visualizing each cluster. The more clear and distinct each cluster is the better. We will review this process below. Here’s the plan for the analysis below: Standardize the dataApplying KMeans on the original datasetFeature Reduction via PCAApplying KMeans to PCA principal componentsFeature Reduction via t-SNEApplying KMeans to t-SNE clustersComparing PCA and t-SNE KMeans derived clusters Standardize the data Applying KMeans on the original dataset Feature Reduction via PCA Applying KMeans to PCA principal components Feature Reduction via t-SNE Applying KMeans to t-SNE clusters Comparing PCA and t-SNE KMeans derived clusters import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport seaborn as snsimport plotly.offline as pyopyo.init_notebook_mode()import plotly.graph_objs as gofrom plotly import toolsfrom plotly.subplots import make_subplotsimport plotly.offline as pyimport plotly.express as pxfrom sklearn.cluster import KMeansfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAfrom sklearn.manifold import TSNEfrom sklearn.metrics import silhouette_score%matplotlib inlinefrom warnings import filterwarningsfilterwarnings('ignore')with open('HR_data.csv') as f: df = pd.read_csv(f, usecols=['satisfaction_level', 'last_evaluation', 'number_project', 'average_montly_hours', 'time_spend_company', 'Work_accident','promotion_last_5years'])f.close()df.head() This is a relatively clean dataset without any missing values or outliers. We do not see any mixed-type features, odd values or rare labels which need encoding. Features have low multicollinearity as well. Let’s move on to scaling our dataset. As aforementioned, the standardization of data will ultimately bring all features to the same scale and bringing the mean to zero and the standard deviation to 1. scaler = StandardScaler()scaler.fit(df)X_scale = scaler.transform(df)df_scale = pd.DataFrame(X_scale, columns=df.columns)df_scale.head() Let’s utilize the Elbow Method to determine the optimal number of clusters KMeans should obtain. It seem 4 or 5 clusters would be best and for the sake of simplicity we’ll select 4. sse = []k_list = range(1, 15)for k in k_list: km = KMeans(n_clusters=k) km.fit(df_scale) sse.append([k, km.inertia_]) oca_results_scale = pd.DataFrame({'Cluster': range(1,15), 'SSE': sse})plt.figure(figsize=(12,6))plt.plot(pd.DataFrame(sse)[0], pd.DataFrame(sse)[1], marker='o')plt.title('Optimal Number of Clusters using Elbow Method (Scaled Data)')plt.xlabel('Number of clusters')plt.ylabel('Inertia') Let’s apply KMeans on the original dataset requesting 4 clusters. We achieved a silhouette score of 0.25 which is on the low end. df_scale2 = df_scale.copy()kmeans_scale = KMeans(n_clusters=4, n_init=100, max_iter=400, init='k-means++', random_state=42).fit(df_scale2)print('KMeans Scaled Silhouette Score: {}'.format(silhouette_score(df_scale2, kmeans_scale.labels_, metric='euclidean')))labels_scale = kmeans_scale.labels_clusters_scale = pd.concat([df_scale2, pd.DataFrame({'cluster_scaled':labels_scale})], axis=1) Using PCA to reduce the dataset into 3 principal components we can plot the KMeans derived clusters into 2D and 3D visuals. PCA visualizations tend to aggregate clusters around a central point which makes interpretation difficult but we can see clusters 1 and 3 to have some distinct structure compared to clusters 0 and 2. However, when we plot the clusters into a 3D space we can clearly distinct all 4 clusters. pca2 = PCA(n_components=3).fit(df_scale2)pca2d = pca2.transform(df_scale2)plt.figure(figsize = (10,10))sns.scatterplot(pca2d[:,0], pca2d[:,1], hue=labels_scale, palette='Set1', s=100, alpha=0.2).set_title('KMeans Clusters (4) Derived from Original Dataset', fontsize=15)plt.legend()plt.ylabel('PC2')plt.xlabel('PC1')plt.show() Scene = dict(xaxis = dict(title = 'PC1'),yaxis = dict(title = 'PC2'),zaxis = dict(title = 'PC3'))labels = labels_scaletrace = go.Scatter3d(x=pca2d[:,0], y=pca2d[:,1], z=pca2d[:,2], mode='markers',marker=dict(color = labels, colorscale='Viridis', size = 10, line = dict(color = 'gray',width = 5)))layout = go.Layout(margin=dict(l=0,r=0),scene = Scene, height = 1000,width = 1000)data = [trace]fig = go.Figure(data = data, layout = layout)fig.show() First, let’s determine what is the optimal number of principal components we need. By examining the amount of variance each principal component encompasses we can see that the first 3 principal components explain roughly 70% of the variance. Finally, we apply PCA again and reduce our dataset to 3 principal components. #n_components=7 because we have 7 features in the datasetpca = PCA(n_components=7)pca.fit(df_scale)variance = pca.explained_variance_ratio_var = np.cumsum(np.round(variance, 3)*100)plt.figure(figsize=(12,6))plt.ylabel('% Variance Explained')plt.xlabel('# of Features')plt.title('PCA Analysis')plt.ylim(0,100.5)plt.plot(var) pca = PCA(n_components=3)pca_scale = pca.fit_transform(df_scale)pca_df_scale = pd.DataFrame(pca_scale, columns=['pc1','pc2','pc3'])print(pca.explained_variance_ratio_) Now that we have reduced the original dataset of 7 features to just 3 principal components let’s apply the KMeans algorithm. We once again needed to determine what is the optimal number of clusters and again it seems 4 is the right choice. It is important to remember we are now using the 3 principal components instead of the original 7 features to determine the optimal number of clusters. sse = []k_list = range(1, 15)for k in k_list: km = KMeans(n_clusters=k) km.fit(pca_df_scale) sse.append([k, km.inertia_]) pca_results_scale = pd.DataFrame({'Cluster': range(1,15), 'SSE': sse})plt.figure(figsize=(12,6))plt.plot(pd.DataFrame(sse)[0], pd.DataFrame(sse)[1], marker='o')plt.title('Optimal Number of Clusters using Elbow Method (PCA_Scaled Data)')plt.xlabel('Number of clusters')plt.ylabel('Inertia') Now we are ready to apply KMeans on the PCA principal components. We can see that we were able to increase our silhouette score from 0.25 to 0.36 by passing KMeans a lower dimensional dataset. Looking at the 2D and 3D scatter plots we can see a significant improvement in the distinction between clusters. kmeans_pca_scale = KMeans(n_clusters=4, n_init=100, max_iter=400, init='k-means++', random_state=42).fit(pca_df_scale)print('KMeans PCA Scaled Silhouette Score: {}'.format(silhouette_score(pca_df_scale, kmeans_pca_scale.labels_, metric='euclidean')))labels_pca_scale = kmeans_pca_scale.labels_clusters_pca_scale = pd.concat([pca_df_scale, pd.DataFrame({'pca_clusters':labels_pca_scale})], axis=1) plt.figure(figsize = (10,10))sns.scatterplot(clusters_pca_scale.iloc[:,0],clusters_pca_scale.iloc[:,1], hue=labels_pca_scale, palette='Set1', s=100, alpha=0.2).set_title('KMeans Clusters (4) Derived from PCA', fontsize=15)plt.legend()plt.show() We can see a definite improvement in KMeans ability to cluster our data when we reduce the number of dimensions to 3 principal components. In this section we will reduce our data once again using t-SNE and compare KMeans results to that of PCA KMeans. We will reduce down to 3 t-SNE components. Please keep in mind t-SNE is a computationally heavy algorithm. Computational time can be reduced using the ‘n_iter’ parameter. Furthermore, the code you see below is a result of dozens iterations of the ‘Perplexity’ parameter. Anything above a perplexity of 80 tended to aggregate our data into one large disperse cluster. tsne = TSNE(n_components=3, verbose=1, perplexity=80, n_iter=5000, learning_rate=200)tsne_scale_results = tsne.fit_transform(df_scale)tsne_df_scale = pd.DataFrame(tsne_scale_results, columns=['tsne1', 'tsne2', 'tsne3'])plt.figure(figsize = (10,10))plt.scatter(tsne_df_scale.iloc[:,0],tsne_df_scale.iloc[:,1],alpha=0.25, facecolor='lightslategray')plt.xlabel('tsne1')plt.ylabel('tsne2')plt.show() Below is the result of reducing our original dataset into 3 t-SNE components plotted into a 2D space. Once again it seems 4 is the magic number of clusters for our KMeans analysis. sse = []k_list = range(1, 15)for k in k_list: km = KMeans(n_clusters=k) km.fit(tsne_df_scale) sse.append([k, km.inertia_]) tsne_results_scale = pd.DataFrame({'Cluster': range(1,15), 'SSE': sse})plt.figure(figsize=(12,6))plt.plot(pd.DataFrame(sse)[0], pd.DataFrame(sse)[1], marker='o')plt.title('Optimal Number of Clusters using Elbow Method (tSNE_Scaled Data)')plt.xlabel('Number of clusters')plt.ylabel('Inertia') Applying KMeans to our 3 t-SNE derived components we were able to obtain a Silhouette score of 0.39. If you recall the Silhouette score obtained from KMeans on PCA’s 3 principal components was 0.36. A relatively small improvement but an improvement nonetheless. kmeans_tsne_scale = KMeans(n_clusters=4, n_init=100, max_iter=400, init='k-means++', random_state=42).fit(tsne_df_scale)print('KMeans tSNE Scaled Silhouette Score: {}'.format(silhouette_score(tsne_df_scale, kmeans_tsne_scale.labels_, metric='euclidean')))labels_tsne_scale = kmeans_tsne_scale.labels_clusters_tsne_scale = pd.concat([tsne_df_scale, pd.DataFrame({'tsne_clusters':labels_tsne_scale})], axis=1) The interpretation of t-SNE can be slightly counterintuitive as the density of t-SNE clusters (ie. low dimensional space) is not proportionally related to the data relationships in the original (high dimensional space) dataset. In other words, we can have quality dense clusters as derived from KMeans but t-SNE might display them as very broad or even as multiple clusters, especially when perplexity is too low. Density, cluster size, the number of clusters (under the same KMeans cluster) and shape really have little meaning when it comes to reading t-SNE plots. We can have very broad, dense or even multiple clusters (especially when perplexity is too low) for the same KMeans cluster but that does not relate to the quality of the cluster. Rather, t-SNE’s major advantage is the distance and location of each KMeans cluster. Clusters which are close to each other will be more related to each other. However, that does not mean clusters which are far away from each are dissimilar proportionally. Finally, we want to see a certain degree of separation between KMeans clusters as displayed using t-SNE. plt.figure(figsize = (15,15))sns.scatterplot(clusters_tsne_scale.iloc[:,0],clusters_tsne_scale.iloc[:,1],hue=labels_tsne_scale, palette='Set1', s=100, alpha=0.6).set_title('Cluster Vis tSNE Scaled Data', fontsize=15)plt.legend()plt.show() Scene = dict(xaxis = dict(title = 'tsne1'),yaxis = dict(title = 'tsne2'),zaxis = dict(title = 'tsne3'))labels = labels_tsne_scaletrace = go.Scatter3d(x=clusters_tsne_scale.iloc[:,0], y=clusters_tsne_scale.iloc[:,1], z=clusters_tsne_scale.iloc[:,2], mode='markers',marker=dict(color = labels, colorscale='Viridis', size = 10, line = dict(color = 'yellow',width = 5)))layout = go.Layout(margin=dict(l=0,r=0),scene = Scene, height = 1000,width = 1000)data = [trace]fig = go.Figure(data = data, layout = layout)fig.show() Staring at PCA/t-SNE plots and comparing evaluation metrics such as the Silhouette score will give us a technical perspective on the clusters derived from KMeans. If we want to understand the clusters from a business perspective we need to examine the clusters against the original features. In other words, what types of employees make up the clusters we obtained from KMeans. Not only will this analysis help guide the business and potentially continued analysis but also give us insights into the quality of the clusters. Let’s first merge the KMeans clusters with the original unscaled features. We’ll create two separate data frames. One for the PCA derives KMeans clusters and one for the t-SNE KMeans clusters. cluster_tsne_profile = pd.merge(df, clusters_tsne_scale['tsne_clusters'], left_index=True, right_index=True )cluster_pca_profile = pd.merge(df, clusters_pca_scale['pca_clusters'], left_index=True, right_index=True ) Let’s begin with a univariate review of the clusters by comparing the clusters based on each individual feature. for c in cluster_pca_profile: grid = sns.FacetGrid(cluster_pca_profile, col='pca_clusters') grid.map(plt.hist, c) for c in cluster_tsne_profile: grid = sns.FacetGrid(cluster_tsne_profile, col='tsne_clusters') grid.map(plt.hist, c) Where the real fun begins when we examine the clusters from a bivariate perspective. When we examine employee satisfaction and last evaluation scores, we can see that KMeans clusters derived from our principal components are much more defined. We will focus our examination of this bivariate relationship between satisfaction and performance on the clusters derived from PCA. Cluster 0 represents the largest amount of employees (7488) who on average are relatively satisfied at work with a very wide range of performance scores. Since this cluster represents almost 50% of the population it is not surprising we are seeing this wide range of satisfaction and performance scores. There is also a smaller but visible cluster of very satisfied and high performing employees. Cluster 1 represents a critical part of the workforce as these are very high performing employees but unfortunately, have extremely low employee satisfaction. The fact cluster 1 represents 20% of the workforce only adds to the severity of the situation. Unsatisfied employees are at a much greater risk of voluntary turnover. Their high-performance scores indicate not only their proficiency but potential institutional knowledge. Losing these employees would create a significant reduction in organizational knowledge and performance. It would be interesting to see the organizational level (ie. mgr, director, executive) of these employees. Losing a large portion of senior management is a significant problem. Cluster 2 seems to represent low performing employees who are on the lower end of the satisfaction continuum. Once again dissatisfied employees are at a higher risk of voluntary turnover and due to their low-performance evaluation we might consider these employees as ‘constructive turnover’. In other words, the voluntary turnover of these employees might actually be a good thing for the organization. We have to look at these results from two different perspectives. First, these employees make up over 25% of the population. If a significant portion of these employees quit the organization might be hard-pressed to have enough employees to successfully perform its function. Secondly, such a large portion of the population being dissatisfied and poorly performing speaks volumes about the recruiting, management, and training function of the organization. These employees might be the result of poorly constructed organizational initiatives. The company would be doing itself an enormous service if they delved deeper into what makes these employees dissatisfied and poorly performing. Finally, cluster 3 contains only 2% of the population and has no discernible distribution. We need a larger dataset to fully explore these employees. plt.figure(figsize=(15,10))fig , (ax1, ax2) = plt.subplots(1,2, figsize=(20,15))sns.scatterplot(data=cluster_pca_profile, x='last_evaluation', y='satisfaction_level', hue='pca_clusters', s=85, alpha=0.4, palette='bright', ax=ax1).set_title( '(PCA) Clusters by satisfaction level and last_evaluation',fontsize=18)sns.scatterplot(data=cluster_tsne_profile, x='last_evaluation', y='satisfaction_level', hue='tsne_clusters', s=85, alpha=0.4, palette='bright', ax=ax2).set_title('(tSNE) Clusters by satisfaction level and last evaluation', fontsize=18) Very interesting, the bivariate relationship between satisfaction and performance scores is almost identical to satisfaction and average monthly hours. Once again the KMeans clusters derived from PCA are significantly more distinct, let’s focus our attention on the PCA features. It seems the employees in PCA cluster 0 not only have a wide range of performance but also average monthly hours. Overall, these results are promising as the majority of the workforce is overall happy, performing admirably, and working a significant amount of hours. Cluster 1 employees are once again dissatisfied and working the largest average monthly hours. If you recall these were also the very high performing employees. These long hours could very well have an impact on their overall job satisfaction. Keep in mind there is a smaller yet emerging group of cluster 1 employees who are overall satisfied and very high performing. There could be more than just 4 clusters in our dataset. The cluster 2 employees are not only low performing but also working the lowest average monthly hours. Keep in mind this dataset might be a little skewed as working 160 hours in a month is considered full-time. Finally, cluster 3 again does not present itself in the plots. plt.figure(figsize=(15,10))fig , (ax1, ax2) = plt.subplots(1,2, figsize=(20,15))sns.scatterplot(data=cluster_pca_profile, x='average_montly_hours', y='satisfaction_level', hue='pca_clusters',s=85, alpha=0.4, palette='bright', ax=ax1).set_title( '(PCA) Clusters by Satisfaction Level and Average Monthly Hours',fontsize=18)sns.scatterplot(data=cluster_tsne_profile, x='average_montly_hours', y='satisfaction_level', hue='tsne_clusters', s=85, alpha=0.4, palette='bright', ax=ax2).set_title( '(tSNE) Clusters by Satisfaction Level and Average Monthly Hours', fontsize=18) As we continue with our bivariate plots we compare satisfaction and time spent in company or tenure. To no surprise, KMeans clusters from PCA principal components are much more distinct. The t-SNE plot has a similar shape to the PCA plot but its clusters are much more scattered. Looking at the PCA plots we have made an important discovery regarding cluster 0 or the vast majority (50%) of the employees. The employees in cluster 0 have primarily been with the company between 2 and 4 years. This is a fairly common statistic as the number of employees with extended tenure (ie 5 years plus) will decrease as tenure increases. Furthermore, their overall high satisfaction points to a potential increase in average tenure as satisfied employees are less likely to quit. Cluster 1 is a little hard to describe as its data points are scattered around two distinct clusters. Overall, their tenure doesn’t vary much between 4 and 6 years of tenure, however, their satisfaction is the opposite of each other. There is a cluster is high job satisfaction and a larger cluster with very low job satisfaction. It would seem cluster 1 might encompass two distinct groups of employees. Those who are very happy and very dissatisfied with their jobs. That said, despite their differences in satisfaction, their job performance, average monthly hours and tenure are on the higher end. It seems cluster 1 are either happy or unhappy very hardworking and committed employees. Cluster 2 follows the same pattern as the plots above. Not only are they dissatisfied at work, but they have one of the lowest average tenures as well. However, it is important to recall these employees account for 26% of the organization. Losing a significant portion of these employees would create issues. Lastly, dissatisfied employees are less likely to engage in organizational citizenship behaviors such as altruism, conscientiousness, helpfulness, and more likely to engage in counterproductive work behavior which can create toxic cultures. Dissecting who are these employees in terms of tenure, company level, turnover rates, location, and job types would be very helpful in diagnosing the issue and developing an action plan. Finally, cluster 3 is yet again too scattered to provide us with any useful information. There simply aren’t enough employees which encompass this cluster to discern any useful patterns. plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='time_spend_company', y='satisfaction_level', hue='pca_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='time_spend_company', y='satisfaction_level', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by satisfaction level and time_spend_company', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by satisfaction level and time_spend_company', fontsize=16)plt.close(1)plt.close(2) PCA derived clusters once again outperformed t-SNE, however, only marginally. Cluster 0 has continued to follow a similar trend, overall happy employees with an average number of projects. Nothing to be overly excited or worried about. This might point to the ideal number of projects for the organization’s employees. Cluster 1 employees are also following their trend we have seen from previous plots. Very dissatisfied employees who are being worked extremely hard when looking at the number of projects. If you recall, this group was also working very long hours during the month. We are once again seeing a smaller but visible group of satisfied employees working on an average number of projects. This was the same trend we saw with satisfaction X tenure, average monthly hours, and last evaluation score. There is definitely yet another group of very satisfied and hard-working employees. Gaining a more in-depth understanding of these employees in terms of recruiting (ie. sources, recruiters), management practices, compensation, might lead to insights into successful recruiting and hiring practices. These insights might also help the organization understand how to convert lower-performing employees. Cluster 2 is following its trend as well. Less satisfied employees working on a very small number of projects. This trend has been seen across all bivariate relationships with satisfaction. Cluster 3 is simply too small to make out any discernible trends. plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='number_project', y='satisfaction_level', hue='pca_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='number_project', y='satisfaction_level', hue='tsne_clusters', jitter=0.47, s=7,alpha=0.5, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Satisfaction Level and Number of Projects', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Satisfaction Level and Number of Projects', fontsize=16)plt.close(1)plt.close(2) We can certainly continue examining the bivariate relationship between each cluster and our features but we are seeing a definitive trend. Below are the remaining relationship plots we urge you to examine. The purpose of this article was to examine the effects of different dimension reduction techniques (ie. PCA and t-SNE) will have on the quality of clusters produced by KMeans. We examined a relatively clean human resources dataset consisting of over 15,000 employees along with their job characteristics. From the original 7 features, we managed to reduce the dataset into 3 principal components and 3 t-SNE components. Our silhouette scores ranged from 0.25 (unreduced dataset) to 0.36 (PCA) and 0.39 (t-SNE). Upon visual inspection, both PCA and t-SNE derived KMeans clusters did a much better job clustering the data compared to the unreduced original 7 features. It wasn’t until we began to compare the PCA and t-SNE KMeans derived clusters in terms of employee job characteristics that we saw significant differences. The PCA KMeans extracted clusters seemed to produce much clearer and defined clusters. From a business perspective we would be doing the reader a disservice if the PCA KMeans clusters were not summarized as well. Cluster 0: This cluster encompassed the majority of the employees (50%) in the dataset. This cluster contains mostly the average employees. They maintain an average level of job satisfaction, their number of monthly worked hours has a very wide range but not extending to the extreme. The same is true regarding their performance as they mostly maintain satisfactory performance scores. The number of projects this cluster of employees is involved in also average between 3 and 5. The only outlier we saw for these employees is their relatively young tenure (2–4 yrs) with the company. These results are not uncommon as even organizations with enough employees will follow a Gaussian distribution on many factors. As we increase the sample size we will statistically have a higher probability of selecting employees that fall towards the middle of the distribution and the outliers will have less and less pull on the distribution (ie. regression to the mean). It is easy to see why KMeans created this cluster of employees. Cluster 1: There was a certain duality or juxtaposition to this group of employees at times. On one hand, we saw a very dissatisfied group of employees who achieved absolutely stunning performance scores, worked very long hours, managed an extreme number of projects, had an above-average tenure, and committing zero accidents. In other words, very hard working and valuable employees who were dissatisfied with the organization. The company would suffer a significant loss of productivity and knowledge if these employees began to turnover. On the other hand, we were seeing a smaller but visible cluster of very satisfied employees with amazing performance scores, above-average number of projects, monthly hours, and tenure. By all means, the model employee the organization was lucky to have. Satisfaction was definitely the splitting factor as the two unique groups tended to merge when we compare the group’s performance with tenure or even number of projects. It would seem there are additional clusters of employees KMeans did not identify. Perhaps 5 or even 6 clusters might have been better criteria for the KMeans algorithm. Cluster 2: Although this cluster was not as well defined as cluster 0, we were able to see a definite trend among the data. On average these employees were not overly satisfied with the organization. Their performance typically ranked towards the lower end of the scale. They worked the lowest number of monthly hours on the lowest number of projects. Their tenure hovered around 3 years which was average. Cluster 3: Finally, cluster 3 employees made up roughly 2% of the dataset which made it virtually impossible to identify any discernible trend in the data. plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='Work_accident', y='satisfaction_level', hue='pca_clusters', jitter=0.47, s=7, alpha=0.3, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='Work_accident', y='satisfaction_level', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.3, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Satisfaction Level and Work Accident', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Satisfaction Level and Work Accident', fontsize=16)plt.close(1)plt.close(2) plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='number_project', y='last_evaluation', hue='pca_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='number_project', y='last_evaluation', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Last Evaluation and Number Projects', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Last Evaluation and Number Projects', fontsize=16)plt.close(1)plt.close(2) plt.figure(figsize=(15,10))fig , (ax1, ax2) = plt.subplots(1,2, figsize=(20,15))sns.scatterplot(data=cluster_pca_profile, x='average_montly_hours', y='last_evaluation', hue='pca_clusters', s=85, alpha=0.3, palette='bright', ax=ax1).set_title( '(PCA) Clusters by Last Evaluation and Average Montly Hours',fontsize=18)sns.scatterplot(data=cluster_tsne_profile, x='average_montly_hours', y='last_evaluation', hue='tsne_clusters', s=85, alpha=0.3, palette='bright', ax=ax2).set_title( '(tSNE) Clusters by Last Evaluation and Average Montly Hours', fontsize=18) plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='time_spend_company', y='last_evaluation', hue='pca_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='time_spend_company', y='last_evaluation', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Last Evaluation and Time Spend Company', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Last Evaluation and Time Spend Company', fontsize=16)plt.close(1)plt.close(2) plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='Work_accident', y='last_evaluation', hue='pca_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='Work_accident', y='last_evaluation', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Last Evaluation and Work Accident', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Last Evaluation and Work Accident', fontsize=16)plt.close(1)plt.close(2) plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='number_project', y='average_montly_hours', hue='pca_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='number_project', y='average_montly_hours', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Number Project and Average Montly Hours', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Number Project and Average Montly Hours', fontsize=16)plt.close(1)plt.close(2) plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='number_project', y='time_spend_company', hue='pca_clusters', jitter=0.4, s=30, alpha=0.2, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='number_project', y='time_spend_company', hue='tsne_clusters', jitter=0.4, s=30, alpha=0.2, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Number Project and Time Spend Company', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Number Project and Time Spend Company', fontsize=16)plt.close(1)plt.close(2) plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='Work_accident', y='number_project', hue='pca_clusters', jitter=0.45, s=30, alpha=0.2, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='Work_accident', y='number_project', hue='tsne_clusters', jitter=0.45, s=30, alpha=0.2, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Number Project and Work Accident', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Number Project and Work Accident', fontsize=16)plt.close(1)plt.close(2) plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='time_spend_company', y='average_montly_hours', hue='pca_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='time_spend_company', y='average_montly_hours', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Time Spend Company and Average Monthly Hours', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Time Spend Company and Average Monthly Hours', fontsize=16)plt.close(1)plt.close(2) plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='Work_accident', y='average_montly_hours', hue='pca_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='Work_accident', y='average_montly_hours', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Work Accident and Average Monthly Hours', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Work Accident and Average Monthly Hours', fontsize=16)plt.close(1)plt.close(2) plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='Work_accident', y='time_spend_company', hue='pca_clusters', jitter=0.45, s=40, alpha=0.2, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='Work_accident', y='time_spend_company', hue='tsne_clusters', jitter=0.45, s=40, alpha=0.2, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Work Accident and Time Spend Company', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Work Accident and Time Spend Company', fontsize=16)plt.close(1)plt.close(2)
[ { "code": null, "e": 806, "s": 172, "text": "Today’s data comes in all shapes and sizes. NLP data encompasses the written word, time-series data tracks sequential data movement over time (ie. stocks), structured data which allows computers to learn by example, and unclassified data allows the computer to apply structure. Whichever dataset you possess, you can be sure there is an algorithm ready to decipher its secrets. In this article, we want to cover a clustering algorithm named KMeans which attempts to uncover hidden subgroups hiding in your dataset. Furthermore, we will examine what effects dimension reduction has on the quality of the clusters obtained from KMeans." }, { "code": null, "e": 1137, "s": 806, "text": "In our example, we will be examining a human resources dataset consisting of 15,000 individual employees. The dataset contains employee job characteristics such as job satisfaction, performance score, workload, years of tenure, accidents, number of promotions. We will apply KMeans in order to uncover similar groups of employees." }, { "code": null, "e": 1570, "s": 1137, "text": "Classification problems will have target labels which we are trying to predict. Famous datasets such as Titanic and Iris are both prime for classification as they both have targets we are trying to predict (ie. survived and species). Furthermore, classification tasks require us to split our data into training and test, where the classifier is trained on the training data and then its performance is measured via the test dataset." }, { "code": null, "e": 1886, "s": 1570, "text": "When dealing with a clustering problem, we want to use an algorithm to uncover meaningful groups in our data. Perhaps we are trying to uncover customer segments or identify anomalies in our data. Either way, the algorithm uncovers the groups with little human intervention as we don’t have target labels to predict." }, { "code": null, "e": 2082, "s": 1886, "text": "That said, we can partner unsupervised clustering algorithms with supervised algorithms by first identifying groups/clusters and then building supervised models to predict the cluster membership." }, { "code": null, "e": 2653, "s": 2082, "text": "At its core, KMeans attempts to organize the data into a specified number of clusters. Unfortunately, it is up to us to determine the number of clusters we wish to find but fear not we have tools at our disposal that assist with this process. The goal of KMeans is to identify similar data points and cluster them together while trying to distance each cluster as far as possible. Its “similarity” calculation is determined via Euclidean distance or an ordinary straight line between two points (Wiki). The shorter the Euclidean distance the more similar the points are." }, { "code": null, "e": 3013, "s": 2653, "text": "First, the user (ie. you or I) determines the number of clusters KMeans needs to find. The number of clusters cannot exceed the number of features in the dataset. Next, KMeans will select a random point for each centroid. The number of centroids is equal to the number of clusters selected. The centroid is the point around which each cluster is built around." }, { "code": null, "e": 3602, "s": 3013, "text": "Second, the Euclidean distance is calculated between each point and each centroid. Each point will be initially assigned to the closest centroid/cluster based on the Euclidean distance. Each data point can belong to one cluster or centroid. The algorithm then averages Euclidean distance (between each point and centroid) for each cluster and this point becomes the new centroid. This process of averaging the Euclidean distances within clusters and assigning new centroids repeats until cluster centroids no longer move. The animation below shows the process, refresh the page if needed." }, { "code": null, "e": 4096, "s": 3602, "text": "We need to be aware of how KMeans selects the initial centroid/s and what problems might this produce. Without our intervention, KMeans will randomly select the initial centroid/s which ultimately can cause different resulting clusters on the same data. From the plots below we can see how running the KMeans algorithm on two different occasions resulted in different initial centroids. The same data points were assigned to different clusters between the first and second time running KMeans." }, { "code": null, "e": 4498, "s": 4096, "text": "Have no fear Sklearn has our backs! The Sklearn KMeans library has certain parameters such as “n_int” and “max_iter” to mitigate this issue. The “n_int” parameter determines the number of times KMeans will randomly select different centroids. “Max_iter” determines how many iterations will run. An iteration is the process of finding the distance, taking the average distance, and moving the centroid." }, { "code": null, "e": 4707, "s": 4498, "text": "If we set our parameters at n_int=25 and max_iter=200 KMeans will randomly select 25 initial centroids and run each centroid up to 200 iterations. The best out of those 25 centroids will be the final cluster." }, { "code": null, "e": 5066, "s": 4707, "text": "The Sklearn also has an “int” parameter which will select the first centroid at random and locate all the data points which are furthest away from the first centroid. Then, the second centroid is assigned nearby those far points as they are less likely to belong to the first centroid. Sklearn selects “int=kmeans++” by default which applies the above logic." }, { "code": null, "e": 5168, "s": 5066, "text": "“You mentioned something about needing to select the number of clusters....? Just how do we do that?”" }, { "code": null, "e": 5403, "s": 5168, "text": "Domain Knowledge: Very often we have a certain level of knowledge and experience in the domain from which our dataset was gathered. This expertise can allow us to set the number of clusters we believe exists in the general population." }, { "code": null, "e": 5682, "s": 5403, "text": "Hypothesis Testing: Setting a specific number of clusters can also act as a test of a certain hypothesis we might have. For example, when analyzing marketing data we have a hunch there are 3 subgroups of customers who very likely, likely, and not likely to purchase our product." }, { "code": null, "e": 6053, "s": 5682, "text": "Data Comes Pre-Labeled: There are times when the data we are analyzing comes with pre-labeled targets. These datasets are typically used for supervised ML problems but that doesn’t mean we cannot cluster the data. Pre-labeled data is unique as you need to remove the targets from your initial analysis and then use them to validate how well the model clustered the data." }, { "code": null, "e": 6776, "s": 6053, "text": "Elbow Method: This is a very popular iterative statistical technique for determining the optimal number of clusters by actually running the K-Means algorithm for a range of cluster values. The elbow method calculates the sum of squared distances from each point to its assigned centroid for each iteration of KMeans. Each iteration runs through a different number of clusters. The result is a line chart that displays the sum of squared distances at each cluster. We want to select the number of clusters at the elbow of the line chart or the lowest sum of squared distances (ie. Inertia) at the lowest number of clusters. The lower the sum of squares distances means the data inside each cluster are more tightly grouped." }, { "code": null, "e": 7326, "s": 6776, "text": "KMeans is very sensitive to scale and requires all features to be on the same scale. KMeans will put more weight or emphasis on features with larger variances and those features will impose more influence on the final cluster shape. For example, let’s consider a dataset of car information such as weight (lbs) and horsepower (hp). If there is a larger variation in weight between all the cars the average Euclidean distance will be more affected by weight. Ultimately, the membership of each cluster will be more affected by weight than horsepower." }, { "code": null, "e": 7957, "s": 7326, "text": "Clustering algorithms such as KMeans have a difficult time accurately clustering data of high dimensionality (ie. too many features). Our dataset is not necessarily highly dimensional as it contains 7 features but even this amount will create issues for KMeans. I would suggest you explore the Curse of Dimensionality for more details. As we saw earlier, many clustering algorithms use a distance formula (ie. Euclidean distance) to determine cluster membership. When our clustering algorithm has too many dimensions, pairs of points will begin to have very similar distances and we wouldn’t be able to obtain meaningful clusters." }, { "code": null, "e": 8137, "s": 7957, "text": "In this example, we are going to compare PCA and t-SNE data reduction techniques prior to running our K-Means clustering algorithm. Let’s take a few mins to explain PCA and t-SNE." }, { "code": null, "e": 9693, "s": 8137, "text": "Principal component analysis or (PCA) is a classic method we can use to reduce high-dimensional data to a low-dimensional space. In other words, we simply cannot accurately visualize high-dimensional datasets because we cannot visualize anything above 3 features (1 feature=1D, 2 features = 2D, 3 features=3D plots). The main purpose behind PCA is to transform datasets with more than 3 features (high-dimensional) into typically a 2D or 3D plots for us feeble humans. That’s what is meant by low-dimensional space. The beauty behind PCA is the fact that despite the reduction into a lower-dimensional space we still retain most (+90%) of the variance or information from our original high-dimensional dataset. The information or variance from our original features is “squeezed” into what PCA calls principal components (PC). The first PC will contain the majority of the information from the original features. The second PC will contain the next largest amount of information, the 3rd PC the third largest amount of info and so on and so on. The PC are not correlated (ie. orthogonal) which means they all contain unique pieces of information. We can typically “squeeze” most (ie. 80–90%) of the information or variance contained in the original features into a few principal components. We use these principal components in our analyses instead of using the original features. This way we can perform an analysis with only 2 or 3 principal components instead of 50 features while still maintaining 80–90% of the information from our original features." }, { "code": null, "e": 9994, "s": 9693, "text": "Let’s take a look at some of the details behind how PCA does its magic. To make the explanation a bit easier let’s see how we can reduce a dataset with 2 features (ie. 2D) in one principal component (1D). That said, reducing 50 features into 3 or 4 principal components utilizes the same methodology." }, { "code": null, "e": 10139, "s": 9994, "text": "We have a 2D plot of weight and height. In other words, we have a dataset of 7 people and have plotted their height in relation to their weight." }, { "code": null, "e": 10383, "s": 10139, "text": "First, PCA needs to center the data by measuring the distances from each point to the y-axis (height) and x-axis (weight). It then calculates the average distance for both axes (ie. height and weight) and centers the data using these averages." }, { "code": null, "e": 10952, "s": 10383, "text": "Then PCA will plot the first principal component (PC1) or the best fitting line which maximizes the variance or the amount of information between weight and height. It determines the best fitting line by maximizing the distance from the point projected onto the best fitting line and the origin (ie. blue light below). It does it for each green point and then it squares each distance, to remove negative values, and sums everything up. The best-fitting line or PC1 will have the largest sum of squared distances from the origin to the projected points for all points." }, { "code": null, "e": 11035, "s": 10952, "text": "Now, we simply rotate the axes to where PC1 is now our x-axis and we are finished." }, { "code": null, "e": 11441, "s": 11035, "text": "If we wanted to reduce 3 features down to two principal components we would simply place a perpendicular (y-axis) to our best-fitting line in a 2D space. Why a perpendicular line? Because each principal component is orthogonal or uncorrelated with all other features. If we wanted to find a third principal component we would simply find another orthogonal line to PC1 and PC2 but this time in a 3D space." }, { "code": null, "e": 12022, "s": 11441, "text": "As you can see from the bar plot below, we initially began with a dataset of 5 features. Remember the number of principal components will always equal the number of features. However, we can see that the first 2 principal components account for 90% of the variance or information contained in the original 5 features. This is how we determine the optimal number of principal components. It is important to remember PCA is very often used for visualizing very high dimensional data (ie. thousands of features), therefore, you will most often see PCA of 2 or 3 principal components." }, { "code": null, "e": 12760, "s": 12022, "text": "Just like PCA, t-SNE takes high-dimensional data and reduces it to a low-dimensional graph (2-D typically). It is also a great dimensionality reduction technique. Unlike PCA, t-SNE can reduce dimensions with non-linear relationships. In other words, if our data had this “Swiss Roll” non-linear distribution where the change in X or Y does not correspond with a constant change in the other variable. PCA would not be able to accurately distill this data into principal components. This is because PCA would attempt to draw the best fitting line through the distribution. T-SNE would be a better solution in this case because it calculates a similarity measure based on the distance between points instead of trying to maximize variance." }, { "code": null, "e": 13340, "s": 12760, "text": "Let’s examine how t-SNE converts high dimensional data space into lower dimensions. It looks at the similarity between local or nearby points by observing the distance (think Euclidean distance). Points that are nearby each other are considered similar. t-SNE then converts this similarity distance for each pair of points into a probability for each pair of points. If two points are close to each other in the high-dimensional space they will have a high probability value and vice versa. This way the probability of picking a set of points is proportional to their similarity." }, { "code": null, "e": 13681, "s": 13340, "text": "Then each point gets randomly projected into a low dimensional space. For this example, we are plotting in a 1-D space but we can plot this in a 2-D or 3-D space as well. Why 2-D or 3-D? Because those are the only dimensions we (humans) can visualize. Remember t-SNE is a visualization tool first and a dimensionality reduction tool second." }, { "code": null, "e": 13847, "s": 13681, "text": "Finally, t-SNE calculates the similarity probability score in a low dimensional space in order to cluster the points together. The result is a 1-D plot we see below." }, { "code": null, "e": 14703, "s": 13847, "text": "One last thing we need to discuss about t-SNE is “Perplexity”, which is a required parameter when running the algorithm. “Perplexity” determines how broad or how tight of a space t-SNE captures similarities between points. If your perplexity is low (perhaps 2), t-SNE will only use two similar points and produce a plot with many scattered clusters. However, when we increase the perplexity to 10, t-SNE will consider 10 neighbor points as similar and cluster them together resulting in larger clusters of points. There is a point of diminishing returns where perplexity can become too large and we achieve a plot with one or two scattered clusters. At this point, t-SNE incorrectly considers points not necessarily related as belonging to a cluster. We typically set perplexity anywhere between 5 and 50, according to the original published paper (link)." }, { "code": null, "e": 14973, "s": 14703, "text": "One of the main limitations of t-SNE is its high computational costs. If you have a very large feature set it might be good to first use PCA to reduce the number of features to a few principal components and then use t-SNE to further reduce the data to 2 or 3 clusters." }, { "code": null, "e": 15006, "s": 14973, "text": "Let’s get back to KMeans........" }, { "code": null, "e": 15414, "s": 15006, "text": "When using unsupervised ML algorithms we often cannot compare our results against a known true label. In other words, we do not have a test set to gauge the performance of our model. That said, we still need to understand how well K-Means managed to cluster our data. We already know how tightly the data is contained within our clusters by looking at the Elbow graph and the number of clusters we selected." }, { "code": null, "e": 15745, "s": 15414, "text": "Silhouette Method: This technique measures the separability between clusters. First, an average distance is found between each point and all other points in a cluster. Then it measures the distance between each point and each point in other clusters. We subtract the two average measures and divide by whichever average is larger." }, { "code": null, "e": 15957, "s": 15745, "text": "We ultimately want a high (ie. closest to 1) score which would indicate that there is a small intra-cluster average distance (tight clusters) and a large inter-cluster average distance (clusters well separated)." }, { "code": null, "e": 16267, "s": 15957, "text": "Visual Cluster Interpretation: Once you have obtained your clusters it is very important to interpret each cluster. This is typically done by merging the original dataset with the clusters and visualizing each cluster. The more clear and distinct each cluster is the better. We will review this process below." }, { "code": null, "e": 16307, "s": 16267, "text": "Here’s the plan for the analysis below:" }, { "code": null, "e": 16542, "s": 16307, "text": "Standardize the dataApplying KMeans on the original datasetFeature Reduction via PCAApplying KMeans to PCA principal componentsFeature Reduction via t-SNEApplying KMeans to t-SNE clustersComparing PCA and t-SNE KMeans derived clusters" }, { "code": null, "e": 16563, "s": 16542, "text": "Standardize the data" }, { "code": null, "e": 16603, "s": 16563, "text": "Applying KMeans on the original dataset" }, { "code": null, "e": 16629, "s": 16603, "text": "Feature Reduction via PCA" }, { "code": null, "e": 16673, "s": 16629, "text": "Applying KMeans to PCA principal components" }, { "code": null, "e": 16701, "s": 16673, "text": "Feature Reduction via t-SNE" }, { "code": null, "e": 16735, "s": 16701, "text": "Applying KMeans to t-SNE clusters" }, { "code": null, "e": 16783, "s": 16735, "text": "Comparing PCA and t-SNE KMeans derived clusters" }, { "code": null, "e": 17620, "s": 16783, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport seaborn as snsimport plotly.offline as pyopyo.init_notebook_mode()import plotly.graph_objs as gofrom plotly import toolsfrom plotly.subplots import make_subplotsimport plotly.offline as pyimport plotly.express as pxfrom sklearn.cluster import KMeansfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAfrom sklearn.manifold import TSNEfrom sklearn.metrics import silhouette_score%matplotlib inlinefrom warnings import filterwarningsfilterwarnings('ignore')with open('HR_data.csv') as f: df = pd.read_csv(f, usecols=['satisfaction_level', 'last_evaluation', 'number_project', 'average_montly_hours', 'time_spend_company', 'Work_accident','promotion_last_5years'])f.close()df.head()" }, { "code": null, "e": 17864, "s": 17620, "text": "This is a relatively clean dataset without any missing values or outliers. We do not see any mixed-type features, odd values or rare labels which need encoding. Features have low multicollinearity as well. Let’s move on to scaling our dataset." }, { "code": null, "e": 18027, "s": 17864, "text": "As aforementioned, the standardization of data will ultimately bring all features to the same scale and bringing the mean to zero and the standard deviation to 1." }, { "code": null, "e": 18164, "s": 18027, "text": "scaler = StandardScaler()scaler.fit(df)X_scale = scaler.transform(df)df_scale = pd.DataFrame(X_scale, columns=df.columns)df_scale.head()" }, { "code": null, "e": 18346, "s": 18164, "text": "Let’s utilize the Elbow Method to determine the optimal number of clusters KMeans should obtain. It seem 4 or 5 clusters would be best and for the sake of simplicity we’ll select 4." }, { "code": null, "e": 18762, "s": 18346, "text": "sse = []k_list = range(1, 15)for k in k_list: km = KMeans(n_clusters=k) km.fit(df_scale) sse.append([k, km.inertia_]) oca_results_scale = pd.DataFrame({'Cluster': range(1,15), 'SSE': sse})plt.figure(figsize=(12,6))plt.plot(pd.DataFrame(sse)[0], pd.DataFrame(sse)[1], marker='o')plt.title('Optimal Number of Clusters using Elbow Method (Scaled Data)')plt.xlabel('Number of clusters')plt.ylabel('Inertia')" }, { "code": null, "e": 18892, "s": 18762, "text": "Let’s apply KMeans on the original dataset requesting 4 clusters. We achieved a silhouette score of 0.25 which is on the low end." }, { "code": null, "e": 19281, "s": 18892, "text": "df_scale2 = df_scale.copy()kmeans_scale = KMeans(n_clusters=4, n_init=100, max_iter=400, init='k-means++', random_state=42).fit(df_scale2)print('KMeans Scaled Silhouette Score: {}'.format(silhouette_score(df_scale2, kmeans_scale.labels_, metric='euclidean')))labels_scale = kmeans_scale.labels_clusters_scale = pd.concat([df_scale2, pd.DataFrame({'cluster_scaled':labels_scale})], axis=1)" }, { "code": null, "e": 19696, "s": 19281, "text": "Using PCA to reduce the dataset into 3 principal components we can plot the KMeans derived clusters into 2D and 3D visuals. PCA visualizations tend to aggregate clusters around a central point which makes interpretation difficult but we can see clusters 1 and 3 to have some distinct structure compared to clusters 0 and 2. However, when we plot the clusters into a 3D space we can clearly distinct all 4 clusters." }, { "code": null, "e": 20070, "s": 19696, "text": "pca2 = PCA(n_components=3).fit(df_scale2)pca2d = pca2.transform(df_scale2)plt.figure(figsize = (10,10))sns.scatterplot(pca2d[:,0], pca2d[:,1], hue=labels_scale, palette='Set1', s=100, alpha=0.2).set_title('KMeans Clusters (4) Derived from Original Dataset', fontsize=15)plt.legend()plt.ylabel('PC2')plt.xlabel('PC1')plt.show()" }, { "code": null, "e": 20521, "s": 20070, "text": "Scene = dict(xaxis = dict(title = 'PC1'),yaxis = dict(title = 'PC2'),zaxis = dict(title = 'PC3'))labels = labels_scaletrace = go.Scatter3d(x=pca2d[:,0], y=pca2d[:,1], z=pca2d[:,2], mode='markers',marker=dict(color = labels, colorscale='Viridis', size = 10, line = dict(color = 'gray',width = 5)))layout = go.Layout(margin=dict(l=0,r=0),scene = Scene, height = 1000,width = 1000)data = [trace]fig = go.Figure(data = data, layout = layout)fig.show()" }, { "code": null, "e": 20841, "s": 20521, "text": "First, let’s determine what is the optimal number of principal components we need. By examining the amount of variance each principal component encompasses we can see that the first 3 principal components explain roughly 70% of the variance. Finally, we apply PCA again and reduce our dataset to 3 principal components." }, { "code": null, "e": 21165, "s": 20841, "text": "#n_components=7 because we have 7 features in the datasetpca = PCA(n_components=7)pca.fit(df_scale)variance = pca.explained_variance_ratio_var = np.cumsum(np.round(variance, 3)*100)plt.figure(figsize=(12,6))plt.ylabel('% Variance Explained')plt.xlabel('# of Features')plt.title('PCA Analysis')plt.ylim(0,100.5)plt.plot(var)" }, { "code": null, "e": 21333, "s": 21165, "text": "pca = PCA(n_components=3)pca_scale = pca.fit_transform(df_scale)pca_df_scale = pd.DataFrame(pca_scale, columns=['pc1','pc2','pc3'])print(pca.explained_variance_ratio_)" }, { "code": null, "e": 21725, "s": 21333, "text": "Now that we have reduced the original dataset of 7 features to just 3 principal components let’s apply the KMeans algorithm. We once again needed to determine what is the optimal number of clusters and again it seems 4 is the right choice. It is important to remember we are now using the 3 principal components instead of the original 7 features to determine the optimal number of clusters." }, { "code": null, "e": 22149, "s": 21725, "text": "sse = []k_list = range(1, 15)for k in k_list: km = KMeans(n_clusters=k) km.fit(pca_df_scale) sse.append([k, km.inertia_]) pca_results_scale = pd.DataFrame({'Cluster': range(1,15), 'SSE': sse})plt.figure(figsize=(12,6))plt.plot(pd.DataFrame(sse)[0], pd.DataFrame(sse)[1], marker='o')plt.title('Optimal Number of Clusters using Elbow Method (PCA_Scaled Data)')plt.xlabel('Number of clusters')plt.ylabel('Inertia')" }, { "code": null, "e": 22455, "s": 22149, "text": "Now we are ready to apply KMeans on the PCA principal components. We can see that we were able to increase our silhouette score from 0.25 to 0.36 by passing KMeans a lower dimensional dataset. Looking at the 2D and 3D scatter plots we can see a significant improvement in the distinction between clusters." }, { "code": null, "e": 22852, "s": 22455, "text": "kmeans_pca_scale = KMeans(n_clusters=4, n_init=100, max_iter=400, init='k-means++', random_state=42).fit(pca_df_scale)print('KMeans PCA Scaled Silhouette Score: {}'.format(silhouette_score(pca_df_scale, kmeans_pca_scale.labels_, metric='euclidean')))labels_pca_scale = kmeans_pca_scale.labels_clusters_pca_scale = pd.concat([pca_df_scale, pd.DataFrame({'pca_clusters':labels_pca_scale})], axis=1)" }, { "code": null, "e": 23097, "s": 22852, "text": "plt.figure(figsize = (10,10))sns.scatterplot(clusters_pca_scale.iloc[:,0],clusters_pca_scale.iloc[:,1], hue=labels_pca_scale, palette='Set1', s=100, alpha=0.2).set_title('KMeans Clusters (4) Derived from PCA', fontsize=15)plt.legend()plt.show()" }, { "code": null, "e": 23716, "s": 23097, "text": "We can see a definite improvement in KMeans ability to cluster our data when we reduce the number of dimensions to 3 principal components. In this section we will reduce our data once again using t-SNE and compare KMeans results to that of PCA KMeans. We will reduce down to 3 t-SNE components. Please keep in mind t-SNE is a computationally heavy algorithm. Computational time can be reduced using the ‘n_iter’ parameter. Furthermore, the code you see below is a result of dozens iterations of the ‘Perplexity’ parameter. Anything above a perplexity of 80 tended to aggregate our data into one large disperse cluster." }, { "code": null, "e": 24112, "s": 23716, "text": "tsne = TSNE(n_components=3, verbose=1, perplexity=80, n_iter=5000, learning_rate=200)tsne_scale_results = tsne.fit_transform(df_scale)tsne_df_scale = pd.DataFrame(tsne_scale_results, columns=['tsne1', 'tsne2', 'tsne3'])plt.figure(figsize = (10,10))plt.scatter(tsne_df_scale.iloc[:,0],tsne_df_scale.iloc[:,1],alpha=0.25, facecolor='lightslategray')plt.xlabel('tsne1')plt.ylabel('tsne2')plt.show()" }, { "code": null, "e": 24214, "s": 24112, "text": "Below is the result of reducing our original dataset into 3 t-SNE components plotted into a 2D space." }, { "code": null, "e": 24293, "s": 24214, "text": "Once again it seems 4 is the magic number of clusters for our KMeans analysis." }, { "code": null, "e": 24720, "s": 24293, "text": "sse = []k_list = range(1, 15)for k in k_list: km = KMeans(n_clusters=k) km.fit(tsne_df_scale) sse.append([k, km.inertia_]) tsne_results_scale = pd.DataFrame({'Cluster': range(1,15), 'SSE': sse})plt.figure(figsize=(12,6))plt.plot(pd.DataFrame(sse)[0], pd.DataFrame(sse)[1], marker='o')plt.title('Optimal Number of Clusters using Elbow Method (tSNE_Scaled Data)')plt.xlabel('Number of clusters')plt.ylabel('Inertia')" }, { "code": null, "e": 24982, "s": 24720, "text": "Applying KMeans to our 3 t-SNE derived components we were able to obtain a Silhouette score of 0.39. If you recall the Silhouette score obtained from KMeans on PCA’s 3 principal components was 0.36. A relatively small improvement but an improvement nonetheless." }, { "code": null, "e": 25390, "s": 24982, "text": "kmeans_tsne_scale = KMeans(n_clusters=4, n_init=100, max_iter=400, init='k-means++', random_state=42).fit(tsne_df_scale)print('KMeans tSNE Scaled Silhouette Score: {}'.format(silhouette_score(tsne_df_scale, kmeans_tsne_scale.labels_, metric='euclidean')))labels_tsne_scale = kmeans_tsne_scale.labels_clusters_tsne_scale = pd.concat([tsne_df_scale, pd.DataFrame({'tsne_clusters':labels_tsne_scale})], axis=1)" }, { "code": null, "e": 26499, "s": 25390, "text": "The interpretation of t-SNE can be slightly counterintuitive as the density of t-SNE clusters (ie. low dimensional space) is not proportionally related to the data relationships in the original (high dimensional space) dataset. In other words, we can have quality dense clusters as derived from KMeans but t-SNE might display them as very broad or even as multiple clusters, especially when perplexity is too low. Density, cluster size, the number of clusters (under the same KMeans cluster) and shape really have little meaning when it comes to reading t-SNE plots. We can have very broad, dense or even multiple clusters (especially when perplexity is too low) for the same KMeans cluster but that does not relate to the quality of the cluster. Rather, t-SNE’s major advantage is the distance and location of each KMeans cluster. Clusters which are close to each other will be more related to each other. However, that does not mean clusters which are far away from each are dissimilar proportionally. Finally, we want to see a certain degree of separation between KMeans clusters as displayed using t-SNE." }, { "code": null, "e": 26738, "s": 26499, "text": "plt.figure(figsize = (15,15))sns.scatterplot(clusters_tsne_scale.iloc[:,0],clusters_tsne_scale.iloc[:,1],hue=labels_tsne_scale, palette='Set1', s=100, alpha=0.6).set_title('Cluster Vis tSNE Scaled Data', fontsize=15)plt.legend()plt.show()" }, { "code": null, "e": 27259, "s": 26738, "text": "Scene = dict(xaxis = dict(title = 'tsne1'),yaxis = dict(title = 'tsne2'),zaxis = dict(title = 'tsne3'))labels = labels_tsne_scaletrace = go.Scatter3d(x=clusters_tsne_scale.iloc[:,0], y=clusters_tsne_scale.iloc[:,1], z=clusters_tsne_scale.iloc[:,2], mode='markers',marker=dict(color = labels, colorscale='Viridis', size = 10, line = dict(color = 'yellow',width = 5)))layout = go.Layout(margin=dict(l=0,r=0),scene = Scene, height = 1000,width = 1000)data = [trace]fig = go.Figure(data = data, layout = layout)fig.show()" }, { "code": null, "e": 27784, "s": 27259, "text": "Staring at PCA/t-SNE plots and comparing evaluation metrics such as the Silhouette score will give us a technical perspective on the clusters derived from KMeans. If we want to understand the clusters from a business perspective we need to examine the clusters against the original features. In other words, what types of employees make up the clusters we obtained from KMeans. Not only will this analysis help guide the business and potentially continued analysis but also give us insights into the quality of the clusters." }, { "code": null, "e": 27977, "s": 27784, "text": "Let’s first merge the KMeans clusters with the original unscaled features. We’ll create two separate data frames. One for the PCA derives KMeans clusters and one for the t-SNE KMeans clusters." }, { "code": null, "e": 28193, "s": 27977, "text": "cluster_tsne_profile = pd.merge(df, clusters_tsne_scale['tsne_clusters'], left_index=True, right_index=True )cluster_pca_profile = pd.merge(df, clusters_pca_scale['pca_clusters'], left_index=True, right_index=True )" }, { "code": null, "e": 28306, "s": 28193, "text": "Let’s begin with a univariate review of the clusters by comparing the clusters based on each individual feature." }, { "code": null, "e": 28426, "s": 28306, "text": "for c in cluster_pca_profile: grid = sns.FacetGrid(cluster_pca_profile, col='pca_clusters') grid.map(plt.hist, c)" }, { "code": null, "e": 28549, "s": 28426, "text": "for c in cluster_tsne_profile: grid = sns.FacetGrid(cluster_tsne_profile, col='tsne_clusters') grid.map(plt.hist, c)" }, { "code": null, "e": 28925, "s": 28549, "text": "Where the real fun begins when we examine the clusters from a bivariate perspective. When we examine employee satisfaction and last evaluation scores, we can see that KMeans clusters derived from our principal components are much more defined. We will focus our examination of this bivariate relationship between satisfaction and performance on the clusters derived from PCA." }, { "code": null, "e": 29322, "s": 28925, "text": "Cluster 0 represents the largest amount of employees (7488) who on average are relatively satisfied at work with a very wide range of performance scores. Since this cluster represents almost 50% of the population it is not surprising we are seeing this wide range of satisfaction and performance scores. There is also a smaller but visible cluster of very satisfied and high performing employees." }, { "code": null, "e": 30035, "s": 29322, "text": "Cluster 1 represents a critical part of the workforce as these are very high performing employees but unfortunately, have extremely low employee satisfaction. The fact cluster 1 represents 20% of the workforce only adds to the severity of the situation. Unsatisfied employees are at a much greater risk of voluntary turnover. Their high-performance scores indicate not only their proficiency but potential institutional knowledge. Losing these employees would create a significant reduction in organizational knowledge and performance. It would be interesting to see the organizational level (ie. mgr, director, executive) of these employees. Losing a large portion of senior management is a significant problem." }, { "code": null, "e": 31127, "s": 30035, "text": "Cluster 2 seems to represent low performing employees who are on the lower end of the satisfaction continuum. Once again dissatisfied employees are at a higher risk of voluntary turnover and due to their low-performance evaluation we might consider these employees as ‘constructive turnover’. In other words, the voluntary turnover of these employees might actually be a good thing for the organization. We have to look at these results from two different perspectives. First, these employees make up over 25% of the population. If a significant portion of these employees quit the organization might be hard-pressed to have enough employees to successfully perform its function. Secondly, such a large portion of the population being dissatisfied and poorly performing speaks volumes about the recruiting, management, and training function of the organization. These employees might be the result of poorly constructed organizational initiatives. The company would be doing itself an enormous service if they delved deeper into what makes these employees dissatisfied and poorly performing." }, { "code": null, "e": 31277, "s": 31127, "text": "Finally, cluster 3 contains only 2% of the population and has no discernible distribution. We need a larger dataset to fully explore these employees." }, { "code": null, "e": 31860, "s": 31277, "text": "plt.figure(figsize=(15,10))fig , (ax1, ax2) = plt.subplots(1,2, figsize=(20,15))sns.scatterplot(data=cluster_pca_profile, x='last_evaluation', y='satisfaction_level', hue='pca_clusters', s=85, alpha=0.4, palette='bright', ax=ax1).set_title( '(PCA) Clusters by satisfaction level and last_evaluation',fontsize=18)sns.scatterplot(data=cluster_tsne_profile, x='last_evaluation', y='satisfaction_level', hue='tsne_clusters', s=85, alpha=0.4, palette='bright', ax=ax2).set_title('(tSNE) Clusters by satisfaction level and last evaluation', fontsize=18)" }, { "code": null, "e": 32140, "s": 31860, "text": "Very interesting, the bivariate relationship between satisfaction and performance scores is almost identical to satisfaction and average monthly hours. Once again the KMeans clusters derived from PCA are significantly more distinct, let’s focus our attention on the PCA features." }, { "code": null, "e": 32407, "s": 32140, "text": "It seems the employees in PCA cluster 0 not only have a wide range of performance but also average monthly hours. Overall, these results are promising as the majority of the workforce is overall happy, performing admirably, and working a significant amount of hours." }, { "code": null, "e": 32834, "s": 32407, "text": "Cluster 1 employees are once again dissatisfied and working the largest average monthly hours. If you recall these were also the very high performing employees. These long hours could very well have an impact on their overall job satisfaction. Keep in mind there is a smaller yet emerging group of cluster 1 employees who are overall satisfied and very high performing. There could be more than just 4 clusters in our dataset." }, { "code": null, "e": 33045, "s": 32834, "text": "The cluster 2 employees are not only low performing but also working the lowest average monthly hours. Keep in mind this dataset might be a little skewed as working 160 hours in a month is considered full-time." }, { "code": null, "e": 33108, "s": 33045, "text": "Finally, cluster 3 again does not present itself in the plots." }, { "code": null, "e": 33716, "s": 33108, "text": "plt.figure(figsize=(15,10))fig , (ax1, ax2) = plt.subplots(1,2, figsize=(20,15))sns.scatterplot(data=cluster_pca_profile, x='average_montly_hours', y='satisfaction_level', hue='pca_clusters',s=85, alpha=0.4, palette='bright', ax=ax1).set_title( '(PCA) Clusters by Satisfaction Level and Average Monthly Hours',fontsize=18)sns.scatterplot(data=cluster_tsne_profile, x='average_montly_hours', y='satisfaction_level', hue='tsne_clusters', s=85, alpha=0.4, palette='bright', ax=ax2).set_title( '(tSNE) Clusters by Satisfaction Level and Average Monthly Hours', fontsize=18)" }, { "code": null, "e": 34486, "s": 33716, "text": "As we continue with our bivariate plots we compare satisfaction and time spent in company or tenure. To no surprise, KMeans clusters from PCA principal components are much more distinct. The t-SNE plot has a similar shape to the PCA plot but its clusters are much more scattered. Looking at the PCA plots we have made an important discovery regarding cluster 0 or the vast majority (50%) of the employees. The employees in cluster 0 have primarily been with the company between 2 and 4 years. This is a fairly common statistic as the number of employees with extended tenure (ie 5 years plus) will decrease as tenure increases. Furthermore, their overall high satisfaction points to a potential increase in average tenure as satisfied employees are less likely to quit." }, { "code": null, "e": 35177, "s": 34486, "text": "Cluster 1 is a little hard to describe as its data points are scattered around two distinct clusters. Overall, their tenure doesn’t vary much between 4 and 6 years of tenure, however, their satisfaction is the opposite of each other. There is a cluster is high job satisfaction and a larger cluster with very low job satisfaction. It would seem cluster 1 might encompass two distinct groups of employees. Those who are very happy and very dissatisfied with their jobs. That said, despite their differences in satisfaction, their job performance, average monthly hours and tenure are on the higher end. It seems cluster 1 are either happy or unhappy very hardworking and committed employees." }, { "code": null, "e": 35914, "s": 35177, "text": "Cluster 2 follows the same pattern as the plots above. Not only are they dissatisfied at work, but they have one of the lowest average tenures as well. However, it is important to recall these employees account for 26% of the organization. Losing a significant portion of these employees would create issues. Lastly, dissatisfied employees are less likely to engage in organizational citizenship behaviors such as altruism, conscientiousness, helpfulness, and more likely to engage in counterproductive work behavior which can create toxic cultures. Dissecting who are these employees in terms of tenure, company level, turnover rates, location, and job types would be very helpful in diagnosing the issue and developing an action plan." }, { "code": null, "e": 36101, "s": 35914, "text": "Finally, cluster 3 is yet again too scattered to provide us with any useful information. There simply aren’t enough employees which encompass this cluster to discern any useful patterns." }, { "code": null, "e": 36773, "s": 36101, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='time_spend_company', y='satisfaction_level', hue='pca_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='time_spend_company', y='satisfaction_level', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by satisfaction level and time_spend_company', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by satisfaction level and time_spend_company', fontsize=16)plt.close(1)plt.close(2)" }, { "code": null, "e": 37092, "s": 36773, "text": "PCA derived clusters once again outperformed t-SNE, however, only marginally. Cluster 0 has continued to follow a similar trend, overall happy employees with an average number of projects. Nothing to be overly excited or worried about. This might point to the ideal number of projects for the organization’s employees." }, { "code": null, "e": 37986, "s": 37092, "text": "Cluster 1 employees are also following their trend we have seen from previous plots. Very dissatisfied employees who are being worked extremely hard when looking at the number of projects. If you recall, this group was also working very long hours during the month. We are once again seeing a smaller but visible group of satisfied employees working on an average number of projects. This was the same trend we saw with satisfaction X tenure, average monthly hours, and last evaluation score. There is definitely yet another group of very satisfied and hard-working employees. Gaining a more in-depth understanding of these employees in terms of recruiting (ie. sources, recruiters), management practices, compensation, might lead to insights into successful recruiting and hiring practices. These insights might also help the organization understand how to convert lower-performing employees." }, { "code": null, "e": 38176, "s": 37986, "text": "Cluster 2 is following its trend as well. Less satisfied employees working on a very small number of projects. This trend has been seen across all bivariate relationships with satisfaction." }, { "code": null, "e": 38242, "s": 38176, "text": "Cluster 3 is simply too small to make out any discernible trends." }, { "code": null, "e": 38905, "s": 38242, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='number_project', y='satisfaction_level', hue='pca_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='number_project', y='satisfaction_level', hue='tsne_clusters', jitter=0.47, s=7,alpha=0.5, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Satisfaction Level and Number of Projects', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Satisfaction Level and Number of Projects', fontsize=16)plt.close(1)plt.close(2)" }, { "code": null, "e": 39111, "s": 38905, "text": "We can certainly continue examining the bivariate relationship between each cluster and our features but we are seeing a definitive trend. Below are the remaining relationship plots we urge you to examine." }, { "code": null, "e": 40021, "s": 39111, "text": "The purpose of this article was to examine the effects of different dimension reduction techniques (ie. PCA and t-SNE) will have on the quality of clusters produced by KMeans. We examined a relatively clean human resources dataset consisting of over 15,000 employees along with their job characteristics. From the original 7 features, we managed to reduce the dataset into 3 principal components and 3 t-SNE components. Our silhouette scores ranged from 0.25 (unreduced dataset) to 0.36 (PCA) and 0.39 (t-SNE). Upon visual inspection, both PCA and t-SNE derived KMeans clusters did a much better job clustering the data compared to the unreduced original 7 features. It wasn’t until we began to compare the PCA and t-SNE KMeans derived clusters in terms of employee job characteristics that we saw significant differences. The PCA KMeans extracted clusters seemed to produce much clearer and defined clusters." }, { "code": null, "e": 40147, "s": 40021, "text": "From a business perspective we would be doing the reader a disservice if the PCA KMeans clusters were not summarized as well." }, { "code": null, "e": 41172, "s": 40147, "text": "Cluster 0: This cluster encompassed the majority of the employees (50%) in the dataset. This cluster contains mostly the average employees. They maintain an average level of job satisfaction, their number of monthly worked hours has a very wide range but not extending to the extreme. The same is true regarding their performance as they mostly maintain satisfactory performance scores. The number of projects this cluster of employees is involved in also average between 3 and 5. The only outlier we saw for these employees is their relatively young tenure (2–4 yrs) with the company. These results are not uncommon as even organizations with enough employees will follow a Gaussian distribution on many factors. As we increase the sample size we will statistically have a higher probability of selecting employees that fall towards the middle of the distribution and the outliers will have less and less pull on the distribution (ie. regression to the mean). It is easy to see why KMeans created this cluster of employees." }, { "code": null, "e": 41714, "s": 41172, "text": "Cluster 1: There was a certain duality or juxtaposition to this group of employees at times. On one hand, we saw a very dissatisfied group of employees who achieved absolutely stunning performance scores, worked very long hours, managed an extreme number of projects, had an above-average tenure, and committing zero accidents. In other words, very hard working and valuable employees who were dissatisfied with the organization. The company would suffer a significant loss of productivity and knowledge if these employees began to turnover." }, { "code": null, "e": 42139, "s": 41714, "text": "On the other hand, we were seeing a smaller but visible cluster of very satisfied employees with amazing performance scores, above-average number of projects, monthly hours, and tenure. By all means, the model employee the organization was lucky to have. Satisfaction was definitely the splitting factor as the two unique groups tended to merge when we compare the group’s performance with tenure or even number of projects." }, { "code": null, "e": 42308, "s": 42139, "text": "It would seem there are additional clusters of employees KMeans did not identify. Perhaps 5 or even 6 clusters might have been better criteria for the KMeans algorithm." }, { "code": null, "e": 42715, "s": 42308, "text": "Cluster 2: Although this cluster was not as well defined as cluster 0, we were able to see a definite trend among the data. On average these employees were not overly satisfied with the organization. Their performance typically ranked towards the lower end of the scale. They worked the lowest number of monthly hours on the lowest number of projects. Their tenure hovered around 3 years which was average." }, { "code": null, "e": 42871, "s": 42715, "text": "Cluster 3: Finally, cluster 3 employees made up roughly 2% of the dataset which made it virtually impossible to identify any discernible trend in the data." }, { "code": null, "e": 43523, "s": 42871, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='Work_accident', y='satisfaction_level', hue='pca_clusters', jitter=0.47, s=7, alpha=0.3, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='Work_accident', y='satisfaction_level', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.3, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Satisfaction Level and Work Accident', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Satisfaction Level and Work Accident', fontsize=16)plt.close(1)plt.close(2)" }, { "code": null, "e": 44169, "s": 43523, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='number_project', y='last_evaluation', hue='pca_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='number_project', y='last_evaluation', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Last Evaluation and Number Projects', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Last Evaluation and Number Projects', fontsize=16)plt.close(1)plt.close(2)" }, { "code": null, "e": 44764, "s": 44169, "text": "plt.figure(figsize=(15,10))fig , (ax1, ax2) = plt.subplots(1,2, figsize=(20,15))sns.scatterplot(data=cluster_pca_profile, x='average_montly_hours', y='last_evaluation', hue='pca_clusters', s=85, alpha=0.3, palette='bright', ax=ax1).set_title( '(PCA) Clusters by Last Evaluation and Average Montly Hours',fontsize=18)sns.scatterplot(data=cluster_tsne_profile, x='average_montly_hours', y='last_evaluation', hue='tsne_clusters', s=85, alpha=0.3, palette='bright', ax=ax2).set_title( '(tSNE) Clusters by Last Evaluation and Average Montly Hours', fontsize=18)" }, { "code": null, "e": 45425, "s": 44764, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='time_spend_company', y='last_evaluation', hue='pca_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='time_spend_company', y='last_evaluation', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Last Evaluation and Time Spend Company', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Last Evaluation and Time Spend Company', fontsize=16)plt.close(1)plt.close(2)" }, { "code": null, "e": 46065, "s": 45425, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='Work_accident', y='last_evaluation', hue='pca_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='Work_accident', y='last_evaluation', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Last Evaluation and Work Accident', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Last Evaluation and Work Accident', fontsize=16)plt.close(1)plt.close(2)" }, { "code": null, "e": 46730, "s": 46065, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='number_project', y='average_montly_hours', hue='pca_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='number_project', y='average_montly_hours', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.5, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Number Project and Average Montly Hours', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Number Project and Average Montly Hours', fontsize=16)plt.close(1)plt.close(2)" }, { "code": null, "e": 47385, "s": 46730, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='number_project', y='time_spend_company', hue='pca_clusters', jitter=0.4, s=30, alpha=0.2, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='number_project', y='time_spend_company', hue='tsne_clusters', jitter=0.4, s=30, alpha=0.2, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Number Project and Time Spend Company', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Number Project and Time Spend Company', fontsize=16)plt.close(1)plt.close(2)" }, { "code": null, "e": 48022, "s": 47385, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='Work_accident', y='number_project', hue='pca_clusters', jitter=0.45, s=30, alpha=0.2, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='Work_accident', y='number_project', hue='tsne_clusters', jitter=0.45, s=30, alpha=0.2, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Number Project and Work Accident', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Number Project and Work Accident', fontsize=16)plt.close(1)plt.close(2)" }, { "code": null, "e": 48705, "s": 48022, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='time_spend_company', y='average_montly_hours', hue='pca_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='time_spend_company', y='average_montly_hours', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Time Spend Company and Average Monthly Hours', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Time Spend Company and Average Monthly Hours', fontsize=16)plt.close(1)plt.close(2)" }, { "code": null, "e": 49367, "s": 48705, "text": "plt.figure(figsize=(15,10))fig = plt.subplots(1,2, figsize=(20,15))ax1 = sns.catplot(data=cluster_pca_profile, x='Work_accident', y='average_montly_hours', hue='pca_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax2 = sns.catplot(data=cluster_tsne_profile, x='Work_accident', y='average_montly_hours', hue='tsne_clusters', jitter=0.47, s=7, alpha=0.4, height=8, aspect=1.5, palette='bright')ax1.fig.suptitle('(PCA) Clusters by Work Accident and Average Monthly Hours', fontsize=16)ax2.fig.suptitle('(t-SNE) Clusters by Work Accident and Average Monthly Hours', fontsize=16)plt.close(1)plt.close(2)" } ]
How to change a textView Style at runtime in android?
This example demonstrates how do I change a textView style in runtime in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Have a nice day!" android:textSize="36sp" android:layout_centerInParent="true"/> </RelativeLayout> Step 3 – Add the following code in res/values/styles.xml <resources> <style name="boldText"> <item name="android:textStyle">bold|italic</item> <item name="android:textColor">#FFFFFF</item> </style> <style name="normalText"> <item name="android:textStyle">normal</item> <item name="android:textColor">#C0C0C0</item> </style> </resources Step 4 – Add the following code in res/values/strings.xml <resources> <string name="app_name">Sample</string> <color name="highlightedTextViewColor">#000088</color> <color name="normalTextViewColor">#000044</color> </resources> Step 5 − Add the following code to src/MainActivity.java import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Build.VERSION.SDK_INT < 23) { textView.setTextAppearance(getApplicationContext(), R.style.boldText); } else { textView.setTextAppearance(R.style.boldText); } textView.setBackgroundResource(R.color.highlightedTextViewColor); } }); } } Step 6 – Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1144, "s": 1062, "text": "This example demonstrates how do I change a textView style in runtime in android." }, { "code": null, "e": 1273, "s": 1144, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1338, "s": 1273, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1877, "s": 1338, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Have a nice day!\"\n android:textSize=\"36sp\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 1934, "s": 1877, "text": "Step 3 – Add the following code in res/values/styles.xml" }, { "code": null, "e": 2225, "s": 1934, "text": "<resources>\n<style name=\"boldText\">\n <item name=\"android:textStyle\">bold|italic</item>\n <item name=\"android:textColor\">#FFFFFF</item>\n</style>\n<style name=\"normalText\">\n <item name=\"android:textStyle\">normal</item>\n <item name=\"android:textColor\">#C0C0C0</item>\n</style>\n</resources" }, { "code": null, "e": 2283, "s": 2225, "text": "Step 4 – Add the following code in res/values/strings.xml" }, { "code": null, "e": 2462, "s": 2283, "text": "<resources>\n <string name=\"app_name\">Sample</string>\n <color name=\"highlightedTextViewColor\">#000088</color>\n <color name=\"normalTextViewColor\">#000044</color>\n</resources>" }, { "code": null, "e": 2519, "s": 2462, "text": "Step 5 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3411, "s": 2519, "text": "import android.os.Build;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n textView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (Build.VERSION.SDK_INT < 23) {\n textView.setTextAppearance(getApplicationContext(), R.style.boldText);\n } else {\n textView.setTextAppearance(R.style.boldText);\n }\n textView.setBackgroundResource(R.color.highlightedTextViewColor);\n }\n });\n }\n}" }, { "code": null, "e": 3466, "s": 3411, "text": "Step 6 – Add the following code to androidManifest.xml" }, { "code": null, "e": 4136, "s": 3466, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4483, "s": 4136, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4524, "s": 4483, "text": "Click here to download the project code." } ]
SQLAlchemy Core - Using Set Operations
In the last chapter, we have learnt about various functions such as max(), min(), count(), etc., here, we will learn about set operations and their uses. Set operations such as UNION and INTERSECT are supported by standard SQL and most of its dialect. SQLAlchemy implements them with the help of following functions − While combining results of two or more SELECT statements, UNION eliminates duplicates from the resultset. The number of columns and datatype must be same in both the tables. The union() function returns a CompoundSelect object from multiple tables. Following example demonstrates its use − from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, union engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() conn = engine.connect() addresses = Table( 'addresses', meta, Column('id', Integer, primary_key = True), Column('st_id', Integer), Column('postal_add', String), Column('email_add', String) ) u = union(addresses.select().where(addresses.c.email_add.like('%@gmail.com addresses.select().where(addresses.c.email_add.like('%@yahoo.com')))) result = conn.execute(u) result.fetchall() The union construct translates to following SQL expression − SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? UNION SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? From our addresses table, following rows represent the union operation − [ (1, 1, 'Shivajinagar Pune', 'ravi@gmail.com'), (2, 1, 'ChurchGate Mumbai', 'kapoor@gmail.com'), (3, 3, 'Jubilee Hills Hyderabad', 'komal@gmail.com'), (4, 5, 'MG Road Bangaluru', 'as@yahoo.com') ] UNION ALL operation cannot remove the duplicates and cannot sort the data in the resultset. For example, in above query, UNION is replaced by UNION ALL to see the effect. u = union_all(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.email_add.like('%@yahoo.com'))) The corresponding SQL expression is as follows − SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? UNION ALL SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? The SQL EXCEPT clause/operator is used to combine two SELECT statements and return rows from the first SELECT statement that are not returned by the second SELECT statement. The except_() function generates a SELECT expression with EXCEPT clause. In the following example, the except_() function returns only those records from addresses table that have ‘gmail.com’ in email_add field but excludes those which have ‘Pune’ as part of postal_add field. u = except_(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.postal_add.like('%Pune'))) Result of the above code is the following SQL expression − SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? EXCEPT SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.postal_add LIKE ? Assuming that addresses table contains data used in earlier examples, it will display following output − [(2, 1, 'ChurchGate Mumbai', 'kapoor@gmail.com'), (3, 3, 'Jubilee Hills Hyderabad', 'komal@gmail.com')] Using INTERSECT operator, SQL displays common rows from both the SELECT statements. The intersect() function implements this behaviour. In following examples, two SELECT constructs are parameters to intersect() function. One returns rows containing ‘gmail.com’ as part of email_add column, and other returns rows having ‘Pune’ as part of postal_add column. The result will be common rows from both resultsets. u = intersect(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.postal_add.like('%Pune'))) In effect, this is equivalent to following SQL statement − SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.email_add LIKE ? INTERSECT SELECT addresses.id, addresses.st_id, addresses.postal_add, addresses.email_add FROM addresses WHERE addresses.postal_add LIKE ? The two bound parameters ‘%gmail.com’ and ‘%Pune’ generate a single row from original data in addresses table as shown below − [(1, 1, 'Shivajinagar Pune', 'ravi@gmail.com')] 21 Lectures 1.5 hours Jack Chan Print Add Notes Bookmark this page
[ { "code": null, "e": 2494, "s": 2340, "text": "In the last chapter, we have learnt about various functions such as max(), min(), count(), etc., here, we will learn about set operations and their uses." }, { "code": null, "e": 2658, "s": 2494, "text": "Set operations such as UNION and INTERSECT are supported by standard SQL and most of its dialect. SQLAlchemy implements them with the help of following functions −" }, { "code": null, "e": 2832, "s": 2658, "text": "While combining results of two or more SELECT statements, UNION eliminates duplicates from the resultset. The number of columns and datatype must be same in both the tables." }, { "code": null, "e": 2948, "s": 2832, "text": "The union() function returns a CompoundSelect object from multiple tables. Following example demonstrates its use −" }, { "code": null, "e": 3513, "s": 2948, "text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, union\nengine = create_engine('sqlite:///college.db', echo = True)\n\nmeta = MetaData()\nconn = engine.connect()\naddresses = Table(\n 'addresses', meta, \n Column('id', Integer, primary_key = True), \n Column('st_id', Integer), \n Column('postal_add', String), \n Column('email_add', String)\n)\n\nu = union(addresses.select().where(addresses.c.email_add.like('%@gmail.com addresses.select().where(addresses.c.email_add.like('%@yahoo.com'))))\n\nresult = conn.execute(u)\nresult.fetchall()" }, { "code": null, "e": 3574, "s": 3513, "text": "The union construct translates to following SQL expression −" }, { "code": null, "e": 3860, "s": 3574, "text": "SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ? UNION SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ?" }, { "code": null, "e": 3933, "s": 3860, "text": "From our addresses table, following rows represent the union operation −" }, { "code": null, "e": 4144, "s": 3933, "text": "[\n (1, 1, 'Shivajinagar Pune', 'ravi@gmail.com'),\n (2, 1, 'ChurchGate Mumbai', 'kapoor@gmail.com'),\n (3, 3, 'Jubilee Hills Hyderabad', 'komal@gmail.com'),\n (4, 5, 'MG Road Bangaluru', 'as@yahoo.com')\n]\n" }, { "code": null, "e": 4315, "s": 4144, "text": "UNION ALL operation cannot remove the duplicates and cannot sort the data in the resultset. For example, in above query, UNION is replaced by UNION ALL to see the effect." }, { "code": null, "e": 4467, "s": 4315, "text": "u = union_all(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.email_add.like('%@yahoo.com')))" }, { "code": null, "e": 4516, "s": 4467, "text": "The corresponding SQL expression is as follows −" }, { "code": null, "e": 4806, "s": 4516, "text": "SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ? UNION ALL SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ?" }, { "code": null, "e": 5053, "s": 4806, "text": "The SQL EXCEPT clause/operator is used to combine two SELECT statements and return rows from the first SELECT statement that are not returned by the second SELECT statement. The except_() function generates a SELECT expression with EXCEPT clause." }, { "code": null, "e": 5257, "s": 5053, "text": "In the following example, the except_() function returns only those records from addresses table that have ‘gmail.com’ in email_add field but excludes those which have ‘Pune’ as part of postal_add field." }, { "code": null, "e": 5402, "s": 5257, "text": "u = except_(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.postal_add.like('%Pune')))" }, { "code": null, "e": 5461, "s": 5402, "text": "Result of the above code is the following SQL expression −" }, { "code": null, "e": 5749, "s": 5461, "text": "SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ? EXCEPT SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.postal_add LIKE ?" }, { "code": null, "e": 5854, "s": 5749, "text": "Assuming that addresses table contains data used in earlier examples, it will display following output −" }, { "code": null, "e": 5962, "s": 5854, "text": "[(2, 1, 'ChurchGate Mumbai', 'kapoor@gmail.com'),\n (3, 3, 'Jubilee Hills Hyderabad', 'komal@gmail.com')]\n" }, { "code": null, "e": 6098, "s": 5962, "text": "Using INTERSECT operator, SQL displays common rows from both the SELECT statements. The intersect() function implements this behaviour." }, { "code": null, "e": 6372, "s": 6098, "text": "In following examples, two SELECT constructs are parameters to intersect() function. One returns rows containing ‘gmail.com’ as part of email_add column, and other returns rows having ‘Pune’ as part of postal_add column. The result will be common rows from both resultsets." }, { "code": null, "e": 6519, "s": 6372, "text": "u = intersect(addresses.select().where(addresses.c.email_add.like('%@gmail.com')), addresses.select().where(addresses.c.postal_add.like('%Pune')))" }, { "code": null, "e": 6578, "s": 6519, "text": "In effect, this is equivalent to following SQL statement −" }, { "code": null, "e": 6869, "s": 6578, "text": "SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.email_add LIKE ? INTERSECT SELECT addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM addresses\nWHERE addresses.postal_add LIKE ?" }, { "code": null, "e": 6996, "s": 6869, "text": "The two bound parameters ‘%gmail.com’ and ‘%Pune’ generate a single row from original data in addresses table as shown below −" }, { "code": null, "e": 7045, "s": 6996, "text": "[(1, 1, 'Shivajinagar Pune', 'ravi@gmail.com')]\n" }, { "code": null, "e": 7080, "s": 7045, "text": "\n 21 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7091, "s": 7080, "text": " Jack Chan" }, { "code": null, "e": 7098, "s": 7091, "text": " Print" }, { "code": null, "e": 7109, "s": 7098, "text": " Add Notes" } ]
DAX Information - LOOKUPVALUE function
Returns the value in result_columnName for the row that meets all criteria specified by search_columnName and search_value. LOOKUPVALUE ( <result_columnName>, <search_columnName>, <search_value>, [<search_columnName>, <search_value>] ... ) result_columnName The fully qualified name of a column that contains the value you want to return. It cannot be an expression. search_columnName The fully qualified name of a column, in the same table as result_columnName, or in a related table, over which the lookup is performed. It cannot be an expression. search_value A scalar expression that does not refer to any column in the same table being searched. The value of result_column at the row where all pairs of search_column and search_value have a match. The value of result_column at the row where all pairs of search_column and search_value have a match. If there is no match that satisfies all the search values, a BLANK is returned. In other words, the function will not return a lookup value if only some of the criteria match. If there is no match that satisfies all the search values, a BLANK is returned. In other words, the function will not return a lookup value if only some of the criteria match. If multiple rows match the search values and in all cases result_column values are identical then that value is returned. However, if result_column returns different values an error is returned. If multiple rows match the search values and in all cases result_column values are identical then that value is returned. However, if result_column returns different values an error is returned. = LOOKUPVALUE([Sport], [EventID],"E962") This DAX formula returns the Sport corresponding to the EventID – E962. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2125, "s": 2001, "text": "Returns the value in result_columnName for the row that meets all criteria specified by search_columnName and search_value." }, { "code": null, "e": 2249, "s": 2125, "text": "LOOKUPVALUE (\n <result_columnName>, <search_columnName>, <search_value>, \n [<search_columnName>, <search_value>] ...\n)\n" }, { "code": null, "e": 2267, "s": 2249, "text": "result_columnName" }, { "code": null, "e": 2348, "s": 2267, "text": "The fully qualified name of a column that contains the value you want to return." }, { "code": null, "e": 2376, "s": 2348, "text": "It cannot be an expression." }, { "code": null, "e": 2394, "s": 2376, "text": "search_columnName" }, { "code": null, "e": 2531, "s": 2394, "text": "The fully qualified name of a column, in the same table as result_columnName, or in a related table, over which the lookup is performed." }, { "code": null, "e": 2559, "s": 2531, "text": "It cannot be an expression." }, { "code": null, "e": 2572, "s": 2559, "text": "search_value" }, { "code": null, "e": 2660, "s": 2572, "text": "A scalar expression that does not refer to any column in the same table being searched." }, { "code": null, "e": 2762, "s": 2660, "text": "The value of result_column at the row where all pairs of search_column and search_value have a match." }, { "code": null, "e": 2864, "s": 2762, "text": "The value of result_column at the row where all pairs of search_column and search_value have a match." }, { "code": null, "e": 3040, "s": 2864, "text": "If there is no match that satisfies all the search values, a BLANK is returned. In other words, the function will not return a lookup value if only some of the criteria match." }, { "code": null, "e": 3216, "s": 3040, "text": "If there is no match that satisfies all the search values, a BLANK is returned. In other words, the function will not return a lookup value if only some of the criteria match." }, { "code": null, "e": 3411, "s": 3216, "text": "If multiple rows match the search values and in all cases result_column values are identical then that value is returned. However, if result_column returns different values an error is returned." }, { "code": null, "e": 3606, "s": 3411, "text": "If multiple rows match the search values and in all cases result_column values are identical then that value is returned. However, if result_column returns different values an error is returned." }, { "code": null, "e": 3648, "s": 3606, "text": "= LOOKUPVALUE([Sport], [EventID],\"E962\") " }, { "code": null, "e": 3720, "s": 3648, "text": "This DAX formula returns the Sport corresponding to the EventID – E962." }, { "code": null, "e": 3755, "s": 3720, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3769, "s": 3755, "text": " Abhay Gadiya" }, { "code": null, "e": 3802, "s": 3769, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3816, "s": 3802, "text": " Randy Minder" }, { "code": null, "e": 3851, "s": 3816, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3865, "s": 3851, "text": " Randy Minder" }, { "code": null, "e": 3872, "s": 3865, "text": " Print" }, { "code": null, "e": 3883, "s": 3872, "text": " Add Notes" } ]
How to perform arithmetic across columns of a MySQL table using Python?
The arithmetic operations as the name suggests are used to perform the operations such as additon, subtraction,division, multiplication or modulus. The arithmetic operations are operated on the numeric data in your table. To perform addition SELECT op1+op2 FROM table_name Here, the op1 and op2 are the column names or the numeric values. If the op1 and op2 are the numeric values, then FROM clause are not required. The + in the above syntax can be replaced by -,*,%,/ to perform other arithmetic operations. import MySQL connector import MySQL connector establish connection with the connector using connect() establish connection with the connector using connect() create the cursor object using cursor() method create the cursor object using cursor() method create a query using the appropriate mysql statements create a query using the appropriate mysql statements execute the SQL query using execute() method execute the SQL query using execute() method close the connection close the connection Suppose we have the following table named “Sales” +------------+---------+ | sale_price | tax | +------------+---------+ | 1000 | 200 | | 500 | 100 | | 50 | 50 | | 180 | 180 | +------------+---------+ We need to calculate amount adding both the column values including sale_price and the tax. import mysql.connector db=mysql.connector.connect(host="your host", user="your username", password="your password",database="database_name") cursor=db.cursor() query="SELECT sale_price,tax, concat(sale_price+tax) AS amount FROM Sales" cursor.execute(query) rows=cursor.fetchall() for row in rows: print(row) db.close() ( ‘sale_price’ , ‘tax’ , ‘amount’ ) (1000,200,1200) (500,100,600) (100,50,150) (700,180,880) The arithmetic addition is operated on the two columns in the table. Similarly, other arithmetic operations can be performed based on need.
[ { "code": null, "e": 1210, "s": 1062, "text": "The arithmetic operations as the name suggests are used to perform the operations such as additon, subtraction,division, multiplication or modulus." }, { "code": null, "e": 1284, "s": 1210, "text": "The arithmetic operations are operated on the numeric data in your table." }, { "code": null, "e": 1304, "s": 1284, "text": "To perform addition" }, { "code": null, "e": 1335, "s": 1304, "text": "SELECT op1+op2 FROM table_name" }, { "code": null, "e": 1479, "s": 1335, "text": "Here, the op1 and op2 are the column names or the numeric values. If the op1 and op2 are the numeric values, then FROM clause are not required." }, { "code": null, "e": 1572, "s": 1479, "text": "The + in the above syntax can be replaced by -,*,%,/ to perform other arithmetic operations." }, { "code": null, "e": 1595, "s": 1572, "text": "import MySQL connector" }, { "code": null, "e": 1618, "s": 1595, "text": "import MySQL connector" }, { "code": null, "e": 1674, "s": 1618, "text": "establish connection with the connector using connect()" }, { "code": null, "e": 1730, "s": 1674, "text": "establish connection with the connector using connect()" }, { "code": null, "e": 1777, "s": 1730, "text": "create the cursor object using cursor() method" }, { "code": null, "e": 1824, "s": 1777, "text": "create the cursor object using cursor() method" }, { "code": null, "e": 1878, "s": 1824, "text": "create a query using the appropriate mysql statements" }, { "code": null, "e": 1932, "s": 1878, "text": "create a query using the appropriate mysql statements" }, { "code": null, "e": 1977, "s": 1932, "text": "execute the SQL query using execute() method" }, { "code": null, "e": 2022, "s": 1977, "text": "execute the SQL query using execute() method" }, { "code": null, "e": 2043, "s": 2022, "text": "close the connection" }, { "code": null, "e": 2064, "s": 2043, "text": "close the connection" }, { "code": null, "e": 2114, "s": 2064, "text": "Suppose we have the following table named “Sales”" }, { "code": null, "e": 2314, "s": 2114, "text": "+------------+---------+\n| sale_price | tax |\n+------------+---------+\n| 1000 | 200 |\n| 500 | 100 |\n| 50 | 50 |\n| 180 | 180 |\n+------------+---------+" }, { "code": null, "e": 2406, "s": 2314, "text": "We need to calculate amount adding both the column values including sale_price and the tax." }, { "code": null, "e": 2733, "s": 2406, "text": "import mysql.connector\ndb=mysql.connector.connect(host=\"your host\", user=\"your username\", password=\"your\npassword\",database=\"database_name\")\n\ncursor=db.cursor()\n\nquery=\"SELECT sale_price,tax, concat(sale_price+tax) AS amount FROM Sales\"\ncursor.execute(query)\n\nrows=cursor.fetchall()\n\nfor row in rows:\n print(row)\n\ndb.close()" }, { "code": null, "e": 2826, "s": 2733, "text": "( ‘sale_price’ , ‘tax’ , ‘amount’ )\n(1000,200,1200)\n(500,100,600)\n(100,50,150)\n(700,180,880)" }, { "code": null, "e": 2966, "s": 2826, "text": "The arithmetic addition is operated on the two columns in the table. Similarly, other arithmetic operations can be performed based on need." } ]
How can I change root username in MySQL?
To change the root username in MySQL, you need to use UPDATE and SET command. The syntax is as follows − UPDATE user set user = ’yourNewUserName’ WHERE user = ’root’; To understand the above syntax, let us switch the database to MySQL using USE command. The query is as follows to switch the database. mysql> use mysql; Database changed Now list all the users from MySQL.user table. The query is as follows − mysql> select user from MySQL.user; The following is the output − +------------------+ | user | +------------------+ | Manish | | User2 | | mysql.infoschema | | mysql.session | | mysql.sys | | root | | Adam Smith | | User1 | | am | +------------------+ 9 rows in set (0.04 sec) Look at the sample output, we have username ‘root’. Change the username root to some other name using UPDATE command. Let us change the username ‘root’ to ‘myRoot’. The query is as follows − mysql> update user set user = 'myRoot' where user = 'root'; Query OK, 0 rows affected (0.00 sec) Rows matched: 0 Changed: 0 Warnings: 0 List all users from MySQL.user table to see the username ‘root’ have been changed to ‘myRoot’. The query is as follows to list all users from MySQL.user table. mysql> select user from MySQL.user; The following is the output − +------------------+ | user | +------------------+ | Manish | | User2 | | myRoot | | mysql.infoschema | | mysql.session | | mysql.sys | | Adam Smith | | User1 | | am | +------------------+ 9 rows in set (0.00 sec) Look at the above table, ‘root’ username has been changed to ‘myRoot’.
[ { "code": null, "e": 1167, "s": 1062, "text": "To change the root username in MySQL, you need to use UPDATE and SET command. The syntax is as follows −" }, { "code": null, "e": 1229, "s": 1167, "text": "UPDATE user set user = ’yourNewUserName’ WHERE user = ’root’;" }, { "code": null, "e": 1316, "s": 1229, "text": "To understand the above syntax, let us switch the database to MySQL using USE command." }, { "code": null, "e": 1364, "s": 1316, "text": "The query is as follows to switch the database." }, { "code": null, "e": 1399, "s": 1364, "text": "mysql> use mysql;\nDatabase changed" }, { "code": null, "e": 1471, "s": 1399, "text": "Now list all the users from MySQL.user table. The query is as follows −" }, { "code": null, "e": 1507, "s": 1471, "text": "mysql> select user from MySQL.user;" }, { "code": null, "e": 1537, "s": 1507, "text": "The following is the output −" }, { "code": null, "e": 1835, "s": 1537, "text": "+------------------+\n| user |\n+------------------+\n| Manish |\n| User2 |\n| mysql.infoschema |\n| mysql.session |\n| mysql.sys |\n| root |\n| Adam Smith |\n| User1 |\n| am |\n+------------------+\n9 rows in set (0.04 sec)" }, { "code": null, "e": 1953, "s": 1835, "text": "Look at the sample output, we have username ‘root’. Change the username root to some other name using UPDATE command." }, { "code": null, "e": 2026, "s": 1953, "text": "Let us change the username ‘root’ to ‘myRoot’. The query is as follows −" }, { "code": null, "e": 2162, "s": 2026, "text": "mysql> update user set user = 'myRoot' where user = 'root';\nQuery OK, 0 rows affected (0.00 sec)\nRows matched: 0 Changed: 0 Warnings: 0" }, { "code": null, "e": 2322, "s": 2162, "text": "List all users from MySQL.user table to see the username ‘root’ have been changed to ‘myRoot’. The query is as follows to list all users from MySQL.user table." }, { "code": null, "e": 2358, "s": 2322, "text": "mysql> select user from MySQL.user;" }, { "code": null, "e": 2388, "s": 2358, "text": "The following is the output −" }, { "code": null, "e": 2686, "s": 2388, "text": "+------------------+\n| user |\n+------------------+\n| Manish |\n| User2 |\n| myRoot |\n| mysql.infoschema |\n| mysql.session |\n| mysql.sys |\n| Adam Smith |\n| User1 |\n| am |\n+------------------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 2757, "s": 2686, "text": "Look at the above table, ‘root’ username has been changed to ‘myRoot’." } ]
Laravel - Session
Sessions are used to store information about the user across the requests. Laravel provides various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used because it is lightweight. Session can be configured in the file stored at config/session.php. To access the session data, we need an instance of session which can be accessed via HTTP request. After getting the instance, we can use the get() method, which will take one argument, “key”, to get the session data. $value = $request->session()->get('key'); You can use all() method to get all session data instead of get() method. Data can be stored in session using the put() method. The put() method will take two arguments, the “key” and the “value”. $request->session()->put('key', 'value'); The forget() method is used to delete an item from the session. This method will take “key” as the argument. $request->session()->forget('key'); Use flush() method instead of forget() method to delete all session data. Use the pull() method to retrieve data from session and delete it afterwards. The pull() method will also take key as the argument. The difference between the forget() and the pull() method is that forget() method will not return the value of the session and pull() method will return it and delete that value from session. Step 1 − Create a controller called SessionController by executing the following command. php artisan make:controller SessionController --plain Step 2 − After successful execution, you will receive the following output − Step 3 − Copy the following code in a file at app/Http/Controllers/SessionController.php. app/Http/Controllers/SessionController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class SessionController extends Controller { public function accessSessionData(Request $request) { if($request->session()->has('my_name')) echo $request->session()->get('my_name'); else echo 'No data in the session'; } public function storeSessionData(Request $request) { $request->session()->put('my_name','Virat Gandhi'); echo "Data has been added to session"; } public function deleteSessionData(Request $request) { $request->session()->forget('my_name'); echo "Data has been removed from session."; } } Step 4 − Add the following lines at app/Http/routes.php file. app/Http/routes.php Route::get('session/get','SessionController@accessSessionData'); Route::get('session/set','SessionController@storeSessionData'); Route::get('session/remove','SessionController@deleteSessionData'); Step 5 − Visit the following URL to set data in session. http://localhost:8000/session/set Step 6 − The output will appear as shown in the following image. Step 7 − Visit the following URL to get data from session. http://localhost:8000/session/get Step 8 − The output will appear as shown in the following image. Step 9 − Visit the following URL to remove session data. http://localhost:8000/session/remove Step 10 − You will see a message as shown in the following image. 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2793, "s": 2472, "text": "Sessions are used to store information about the user across the requests. Laravel provides various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used because it is lightweight. Session can be configured in the file stored at config/session.php." }, { "code": null, "e": 3011, "s": 2793, "text": "To access the session data, we need an instance of session which can be accessed via HTTP request. After getting the instance, we can use the get() method, which will take one argument, “key”, to get the session data." }, { "code": null, "e": 3054, "s": 3011, "text": "$value = $request->session()->get('key');\n" }, { "code": null, "e": 3128, "s": 3054, "text": "You can use all() method to get all session data instead of get() method." }, { "code": null, "e": 3251, "s": 3128, "text": "Data can be stored in session using the put() method. The put() method will take two arguments, the “key” and the “value”." }, { "code": null, "e": 3294, "s": 3251, "text": "$request->session()->put('key', 'value');\n" }, { "code": null, "e": 3403, "s": 3294, "text": "The forget() method is used to delete an item from the session. This method will take “key” as the argument." }, { "code": null, "e": 3440, "s": 3403, "text": "$request->session()->forget('key');\n" }, { "code": null, "e": 3838, "s": 3440, "text": "Use flush() method instead of forget() method to delete all session data. Use the pull() method to retrieve data from session and delete it afterwards. The pull() method will also take key as the argument. The difference between the forget() and the pull() method is that forget() method will not return the value of the session and pull() method will return it and delete that value from session." }, { "code": null, "e": 3928, "s": 3838, "text": "Step 1 − Create a controller called SessionController by executing the following command." }, { "code": null, "e": 3983, "s": 3928, "text": "php artisan make:controller SessionController --plain\n" }, { "code": null, "e": 4060, "s": 3983, "text": "Step 2 − After successful execution, you will receive the following output −" }, { "code": null, "e": 4106, "s": 4060, "text": "Step 3 − Copy the following code in a file at" }, { "code": null, "e": 4150, "s": 4106, "text": "app/Http/Controllers/SessionController.php." }, { "code": null, "e": 4193, "s": 4150, "text": "app/Http/Controllers/SessionController.php" }, { "code": null, "e": 4902, "s": 4193, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass SessionController extends Controller {\n public function accessSessionData(Request $request) {\n if($request->session()->has('my_name'))\n echo $request->session()->get('my_name');\n else\n echo 'No data in the session';\n }\n public function storeSessionData(Request $request) {\n $request->session()->put('my_name','Virat Gandhi');\n echo \"Data has been added to session\";\n }\n public function deleteSessionData(Request $request) {\n $request->session()->forget('my_name');\n echo \"Data has been removed from session.\";\n }\n}" }, { "code": null, "e": 4964, "s": 4902, "text": "Step 4 − Add the following lines at app/Http/routes.php file." }, { "code": null, "e": 4984, "s": 4964, "text": "app/Http/routes.php" }, { "code": null, "e": 5182, "s": 4984, "text": "Route::get('session/get','SessionController@accessSessionData');\nRoute::get('session/set','SessionController@storeSessionData');\nRoute::get('session/remove','SessionController@deleteSessionData');\n" }, { "code": null, "e": 5239, "s": 5182, "text": "Step 5 − Visit the following URL to set data in session." }, { "code": null, "e": 5274, "s": 5239, "text": "http://localhost:8000/session/set\n" }, { "code": null, "e": 5339, "s": 5274, "text": "Step 6 − The output will appear as shown in the following image." }, { "code": null, "e": 5398, "s": 5339, "text": "Step 7 − Visit the following URL to get data from session." }, { "code": null, "e": 5433, "s": 5398, "text": "http://localhost:8000/session/get\n" }, { "code": null, "e": 5498, "s": 5433, "text": "Step 8 − The output will appear as shown in the following image." }, { "code": null, "e": 5555, "s": 5498, "text": "Step 9 − Visit the following URL to remove session data." }, { "code": null, "e": 5593, "s": 5555, "text": "http://localhost:8000/session/remove\n" }, { "code": null, "e": 5659, "s": 5593, "text": "Step 10 − You will see a message as shown in the following image." }, { "code": null, "e": 5692, "s": 5659, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 5712, "s": 5692, "text": " Sebastian Sulinski" }, { "code": null, "e": 5747, "s": 5712, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5761, "s": 5747, "text": " Antonio Papa" }, { "code": null, "e": 5795, "s": 5761, "text": "\n 7 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5815, "s": 5795, "text": " Sebastian Sulinski" }, { "code": null, "e": 5848, "s": 5815, "text": "\n 42 Lectures \n 1 hours \n" }, { "code": null, "e": 5868, "s": 5848, "text": " Skillbakerystudios" }, { "code": null, "e": 5903, "s": 5868, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 5926, "s": 5903, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 5961, "s": 5926, "text": "\n 116 Lectures \n 13 hours \n" }, { "code": null, "e": 5981, "s": 5961, "text": " Hafizullah Masoudi" }, { "code": null, "e": 5988, "s": 5981, "text": " Print" }, { "code": null, "e": 5999, "s": 5988, "text": " Add Notes" } ]
Another JupyterLab Extension You Should Know About | by Roman Orac | Towards Data Science
It’s really an exciting time to be a part of the Data Science community with all the new JupyterLab extensions that are coming out. They make Data Science much more enjoyable by minimizing the tedious work. I remember the old days where we had to rely on numpy and matplotlib as our main tools for Exploratory Data Analysis in Python. Luckily for us, those days are long gone. You’ll see what I mean by “long gone”, with the JupyterLab extension that is the main topic of this article. In case you’ve missed other articles about Mito: Mito — A Spreadsheet that Generates Python Mito is a free JupyterLab extension that enables exploring and transforming datasets with the ease of Excel. Mito is a missing pandas extension that we were waiting for years When you start Mito, it shows a spreadsheet view of a pandas Dataframe. With a few clicks, you can perform any CRUD operation. CRUD stands for Create, Read, Update, Delete To load your data with Mito and show the spreadsheet view is as simple as: import mitosheetimport pandas as pdurl = 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv'iris = pd.read_csv(url)mitosheet.sheet(iris) Mito opens a powerful spreadsheet viewer, which enables filtering, sorting and editing the data. And it doesn’t just stop with basic editing capabilities... With just a few clicks, Mito can create a pivot table. It supports many common aggregations, like sum, median, mean, count, unique, etc. What’s a pivot table? (from Wikipedia) A pivot table is a table of grouped values that aggregates the individual items of a more extensive table within one or more discrete categories. If pivoting tables didn’t impress you enough to give Mito a try, I’m quite confident that the following features will. Dynamic formulas are Excel's killer feature. Excel makes it easy to create complex spreadsheets for those who’re not familiar with programming. What if I told you that Mito supports dynamic formulas in an “Excel way”. This feature really surprised me as the team behind Mito had spent a lot of development time to implement it. Take a look at the GIF below to see Mito’s sum formula in action: We, Data Scientists, appreciate the tools that simplify data visualization. At first, pandas made a huge leap from using barebones matplotlib — a powerful python package for data visualization. Then came seaborn and plotly, which can make stunning visualizations in Python with just a few commands... a giant leap again. ... and then came Mito, which can visualize your data without writing a line of code. Mito supports bar charts, box plots, histograms, and scatter plots. In the GIF below, I make a bar plot with sepal width on the x-axis and species on the y-axis. Mito transforms each operation that you make into pandas code, which you can then share with your colleagues. The main intention of this feature is to repeat the analysis on another dataset. It’s like a pandas macro. This is also a great feature for less experienced Data Scientists as they can learn “the pandas way” of doing Data Analysis. I did some clicking and Mito produced the following code snippet: Mito requires a Python 3.6 or above. First, you need to download Mito's installer with: python -m pip install mitoinstaller Then to install it, simply run: python -m mitoinstaller install In case you have some installation errors, take a look at Mito's Common Installation Issues. It amazes me how far has JupyterLab’s extension ecosystem came. The initial extensions were clunky, error-prone and hard to install. The times have changed and JupyterLab’s extensions are maturing. Mito is a great example of this trend. I’ve taken Mito to a test drive and after a couple of hours, I didn’t see the degraded performance (or some strange error). I will add Mito to my Data Science toolbox. I plan to use it for the initial Exploratory Data Analysis — to get the feel of the data. Typing the same set of commands over and over gets tedious. In case you’d like to learn more about Mito, it has well-written documentation (and many tutorials), which is always a good sign with such extensions. If you enjoy reading these stories, why not become a Medium paying member? It is $5 per month, and you will get unlimited access to 10000s of stories and writers. If you sign up using my link, I will earn a small commission.
[ { "code": null, "e": 379, "s": 172, "text": "It’s really an exciting time to be a part of the Data Science community with all the new JupyterLab extensions that are coming out. They make Data Science much more enjoyable by minimizing the tedious work." }, { "code": null, "e": 549, "s": 379, "text": "I remember the old days where we had to rely on numpy and matplotlib as our main tools for Exploratory Data Analysis in Python. Luckily for us, those days are long gone." }, { "code": null, "e": 658, "s": 549, "text": "You’ll see what I mean by “long gone”, with the JupyterLab extension that is the main topic of this article." }, { "code": null, "e": 707, "s": 658, "text": "In case you’ve missed other articles about Mito:" }, { "code": null, "e": 750, "s": 707, "text": "Mito — A Spreadsheet that Generates Python" }, { "code": null, "e": 859, "s": 750, "text": "Mito is a free JupyterLab extension that enables exploring and transforming datasets with the ease of Excel." }, { "code": null, "e": 925, "s": 859, "text": "Mito is a missing pandas extension that we were waiting for years" }, { "code": null, "e": 1052, "s": 925, "text": "When you start Mito, it shows a spreadsheet view of a pandas Dataframe. With a few clicks, you can perform any CRUD operation." }, { "code": null, "e": 1097, "s": 1052, "text": "CRUD stands for Create, Read, Update, Delete" }, { "code": null, "e": 1172, "s": 1097, "text": "To load your data with Mito and show the spreadsheet view is as simple as:" }, { "code": null, "e": 1330, "s": 1172, "text": "import mitosheetimport pandas as pdurl = 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv'iris = pd.read_csv(url)mitosheet.sheet(iris)" }, { "code": null, "e": 1427, "s": 1330, "text": "Mito opens a powerful spreadsheet viewer, which enables filtering, sorting and editing the data." }, { "code": null, "e": 1487, "s": 1427, "text": "And it doesn’t just stop with basic editing capabilities..." }, { "code": null, "e": 1624, "s": 1487, "text": "With just a few clicks, Mito can create a pivot table. It supports many common aggregations, like sum, median, mean, count, unique, etc." }, { "code": null, "e": 1663, "s": 1624, "text": "What’s a pivot table? (from Wikipedia)" }, { "code": null, "e": 1809, "s": 1663, "text": "A pivot table is a table of grouped values that aggregates the individual items of a more extensive table within one or more discrete categories." }, { "code": null, "e": 1928, "s": 1809, "text": "If pivoting tables didn’t impress you enough to give Mito a try, I’m quite confident that the following features will." }, { "code": null, "e": 2072, "s": 1928, "text": "Dynamic formulas are Excel's killer feature. Excel makes it easy to create complex spreadsheets for those who’re not familiar with programming." }, { "code": null, "e": 2256, "s": 2072, "text": "What if I told you that Mito supports dynamic formulas in an “Excel way”. This feature really surprised me as the team behind Mito had spent a lot of development time to implement it." }, { "code": null, "e": 2322, "s": 2256, "text": "Take a look at the GIF below to see Mito’s sum formula in action:" }, { "code": null, "e": 2398, "s": 2322, "text": "We, Data Scientists, appreciate the tools that simplify data visualization." }, { "code": null, "e": 2516, "s": 2398, "text": "At first, pandas made a huge leap from using barebones matplotlib — a powerful python package for data visualization." }, { "code": null, "e": 2643, "s": 2516, "text": "Then came seaborn and plotly, which can make stunning visualizations in Python with just a few commands... a giant leap again." }, { "code": null, "e": 2729, "s": 2643, "text": "... and then came Mito, which can visualize your data without writing a line of code." }, { "code": null, "e": 2797, "s": 2729, "text": "Mito supports bar charts, box plots, histograms, and scatter plots." }, { "code": null, "e": 2891, "s": 2797, "text": "In the GIF below, I make a bar plot with sepal width on the x-axis and species on the y-axis." }, { "code": null, "e": 3001, "s": 2891, "text": "Mito transforms each operation that you make into pandas code, which you can then share with your colleagues." }, { "code": null, "e": 3108, "s": 3001, "text": "The main intention of this feature is to repeat the analysis on another dataset. It’s like a pandas macro." }, { "code": null, "e": 3233, "s": 3108, "text": "This is also a great feature for less experienced Data Scientists as they can learn “the pandas way” of doing Data Analysis." }, { "code": null, "e": 3299, "s": 3233, "text": "I did some clicking and Mito produced the following code snippet:" }, { "code": null, "e": 3336, "s": 3299, "text": "Mito requires a Python 3.6 or above." }, { "code": null, "e": 3387, "s": 3336, "text": "First, you need to download Mito's installer with:" }, { "code": null, "e": 3423, "s": 3387, "text": "python -m pip install mitoinstaller" }, { "code": null, "e": 3455, "s": 3423, "text": "Then to install it, simply run:" }, { "code": null, "e": 3487, "s": 3455, "text": "python -m mitoinstaller install" }, { "code": null, "e": 3580, "s": 3487, "text": "In case you have some installation errors, take a look at Mito's Common Installation Issues." }, { "code": null, "e": 3713, "s": 3580, "text": "It amazes me how far has JupyterLab’s extension ecosystem came. The initial extensions were clunky, error-prone and hard to install." }, { "code": null, "e": 3817, "s": 3713, "text": "The times have changed and JupyterLab’s extensions are maturing. Mito is a great example of this trend." }, { "code": null, "e": 3941, "s": 3817, "text": "I’ve taken Mito to a test drive and after a couple of hours, I didn’t see the degraded performance (or some strange error)." }, { "code": null, "e": 4135, "s": 3941, "text": "I will add Mito to my Data Science toolbox. I plan to use it for the initial Exploratory Data Analysis — to get the feel of the data. Typing the same set of commands over and over gets tedious." }, { "code": null, "e": 4286, "s": 4135, "text": "In case you’d like to learn more about Mito, it has well-written documentation (and many tutorials), which is always a good sign with such extensions." } ]
Fixed Length and Variable Length Subnet Mask Numericals - GeeksforGeeks
29 May, 2020 Before starting off with this article make sure you know the basics of Subnetting and Classless Addressing. 1. Fixed-Length Subnet Mask :When a block of addresses is divided into subnets all having an equal number of addresses, the type of subnetting is said to be Fixed Length Subnetting. The subnet masks used here will be the same for all the subnets as the number of addresses is equal for each subnet. Example –Consider an address block 121.37.10.64 /26.Find the first and last addresses for each subnet, if the number of equal sized subnets required is as given in the input. Input : Number of subnets required = 4 Output : Subnet-1: First Address: 121.37.10.64 /28 Last Address: 121.37.10.79 /28 Subnet-2: First Address: 121.37.10.80 /28 Last Address: 121.37.10.95 /28 Subnet-3: First Address: 121.37.10.96 /28 Last Address: 121.37.10.111 /28 Subnet-4: First Address: 121.37.10.112 /28 Last Address: 121.37.10.127 /28 Since 4 subnets are required, we need 2 bits to identify each subnet. Thus the subnet mask now becomes (/28).. Number of variable bits left = 32 -28 = 4 bits. Thus the total number of addresses in each subnet= 24= 16. There are two ways of approaching the solution:Method-1: To find the First Address, understand that the first 26 bits will be the same as the address given because they were fixed. As discussed above the next 2 bits will also be fixed.Out of the 16 addresses of that a subnet holds, to point its first address it is required that all the 4 (non-fixed) bits are 0.So the first address of the 1st subnet =121.37.10. 01 00 0 0 0 0 /28 = 121.37.10.64/28.For the 2nd subnet =121.37.10. 01 01 0 0 0 0 /28 = 121.37.10.80/28and so on.To find the last address, add (the number of addresses in the subnet -1) to the first address of that subnet. In this case, add (16-1) to the first address of each subnet. So the last address of the 1st subnet is 121.37.10.79/28. To find the First Address, understand that the first 26 bits will be the same as the address given because they were fixed. As discussed above the next 2 bits will also be fixed. Out of the 16 addresses of that a subnet holds, to point its first address it is required that all the 4 (non-fixed) bits are 0. So the first address of the 1st subnet =121.37.10. 01 00 0 0 0 0 /28 = 121.37.10.64/28.For the 2nd subnet =121.37.10. 01 01 0 0 0 0 /28 = 121.37.10.80/28and so on. 121.37.10. 01 00 0 0 0 0 /28 = 121.37.10.64/28. For the 2nd subnet = 121.37.10. 01 01 0 0 0 0 /28 = 121.37.10.80/28 and so on. To find the last address, add (the number of addresses in the subnet -1) to the first address of that subnet. In this case, add (16-1) to the first address of each subnet. So the last address of the 1st subnet is 121.37.10.79/28. 121.37.10.79/28. Method -2 (shortcut): To find the first address of the 1st subnet, carryout AND operation between the address given and the subnet mask of the 1st subnet.Performing AND operation : 01111001 00100101 00001010 01000000/26 AND 11111111 11111111 11111111 11110000/28 ------------------------------------------------------------------------- 01111001 00100101 00001010 01000000 /28 Thus, first Address of the 1st subnet= 01111001 00100101 00001010 01000000 /28 = 121.37.10.64 /28 To find the last address of a subnet, perform OR operation between the first address of the subnet and the complement of the subnet mask.First address of 1st subnet,= 01111001 00100101 00001010 01000000 /28 Complement of the subnet mask,= 00000000 00000000 0000000 00001111 / 28 Performing OR operation we get the last address of the 1st subnet= 01111001 00100101 00001010 00001111 / 28 = 121.37.10.79 /28 Add 1 to the last address of the previous subnet to find the first address of the next subnet. To find the first address of the 1st subnet, carryout AND operation between the address given and the subnet mask of the 1st subnet.Performing AND operation : 01111001 00100101 00001010 01000000/26 AND 11111111 11111111 11111111 11110000/28 ------------------------------------------------------------------------- 01111001 00100101 00001010 01000000 /28 Thus, first Address of the 1st subnet= 01111001 00100101 00001010 01000000 /28 = 121.37.10.64 /28 01111001 00100101 00001010 01000000/26 AND 11111111 11111111 11111111 11110000/28 ------------------------------------------------------------------------- 01111001 00100101 00001010 01000000 /28 Thus, first Address of the 1st subnet = 01111001 00100101 00001010 01000000 /28 = 121.37.10.64 /28 To find the last address of a subnet, perform OR operation between the first address of the subnet and the complement of the subnet mask.First address of 1st subnet,= 01111001 00100101 00001010 01000000 /28 Complement of the subnet mask,= 00000000 00000000 0000000 00001111 / 28 Performing OR operation we get the last address of the 1st subnet= 01111001 00100101 00001010 00001111 / 28 = 121.37.10.79 /28 = 01111001 00100101 00001010 01000000 /28 Complement of the subnet mask, = 00000000 00000000 0000000 00001111 / 28 Performing OR operation we get the last address of the 1st subnet = 01111001 00100101 00001010 00001111 / 28 = 121.37.10.79 /28 Add 1 to the last address of the previous subnet to find the first address of the next subnet. Note –When the number of subnets required cannot be computed in the powers of 2, then divide address space in a way that the number of subnets is closest to a number that can solely be represented as a power of 2. For example, if we need 14 subnets, then since 14 cannot be represented solely in the powers of 2, so we divide address space into 16 equal subnets. Now the respective addresses can be found using the above-mentioned method. 2. Variable Length Subnet Masks :When a block of addresses is divided into subnets containing different numbers of addresses, type of subnetting is said to be Variable-Length Subnetting.The subnet masks used here might not be the same for different subnets. Example:Consider a block of address with starting address 112.78.0.0/16. Find the first and last addresses for each group, if the number and size of the subnets required by them are as given in the input. Input: Group-1: 256 subnets, each needs 128 addresses Group-2: 1024 subnets, each requiring 4 addresses Group-1: 128 subnets, each consisting of 16 addresses Output: Group-1: First Address : 112.78.0.0 /17 Last Address : 112.78.127.255 /17 Group-2: First Address : 112.78.128.0 /20 Last Address : 112.78.143.255 / 20 Group-3: First Address : 112.78.144.0 /21 Last Address : 112.78.151.255 /21 To understand such problems, it is important to understand the procedure to fix the bits in the subnet ID and find the subnet mask for each group of subnets. Given the Total addresses in the address block, = 232-16 = 65,536 Understanding the division of address space, Group-1: Number of addresses = 256 x 128 = 32, 768 Thus, group 1 occupies 1/2 of the addresses in the block. So, 1 bit is fixed to identify this half and the Subnet Mask becomes /17. Similarly for Group-2, a total of 4 bits are fixed and the Subnet Mask becomes /20. And, for Group-3, a total of 5 bits are fixed and subnet mask becomes /21. Then using Method 2 mentioned above, the respective starting and ending addresses can be found. For the sake of understanding the problem, let the block of addresses be represented by a big square which can be further divided into the required subnets. Since the total number of addresses in the block = 65, 536, it can be deduced that the square is made up of 256 x 256 addresses. Observe the division of the address space and fixing of the initial bits in the subnet ID of the address space carefully. The blanks along with 8 more blanks together will be the host ID. Once the address space is appropriately divided and respective subnet masks found, use the methods above to find the required addresses. Computer Networks-Network Layer Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Stop and Wait ARQ Multiple Access Protocols in Computer Network Introduction and IPv4 Datagram Header ACID Properties in DBMS Normal Forms in DBMS Types of Operating Systems Page Replacement Algorithms in Operating Systems Semaphores in Process Synchronization
[ { "code": null, "e": 24430, "s": 24402, "text": "\n29 May, 2020" }, { "code": null, "e": 24538, "s": 24430, "text": "Before starting off with this article make sure you know the basics of Subnetting and Classless Addressing." }, { "code": null, "e": 24837, "s": 24538, "text": "1. Fixed-Length Subnet Mask :When a block of addresses is divided into subnets all having an equal number of addresses, the type of subnetting is said to be Fixed Length Subnetting. The subnet masks used here will be the same for all the subnets as the number of addresses is equal for each subnet." }, { "code": null, "e": 25014, "s": 24837, "text": "Example –Consider an address block 121.37.10.64 /26.Find the first and last addresses for each subnet, if the number of equal sized subnets required is as given in the input. " }, { "code": null, "e": 25022, "s": 25014, "text": "Input :" }, { "code": null, "e": 25054, "s": 25022, "text": "Number of subnets required = 4 " }, { "code": null, "e": 25063, "s": 25054, "text": "Output :" }, { "code": null, "e": 25362, "s": 25063, "text": "Subnet-1:\nFirst Address: 121.37.10.64 /28\nLast Address: 121.37.10.79 /28\n\nSubnet-2:\nFirst Address: 121.37.10.80 /28\nLast Address: 121.37.10.95 /28\n\nSubnet-3:\nFirst Address: 121.37.10.96 /28\nLast Address: 121.37.10.111 /28\n\nSubnet-4:\nFirst Address: 121.37.10.112 /28\nLast Address: 121.37.10.127 /28 " }, { "code": null, "e": 25580, "s": 25362, "text": "Since 4 subnets are required, we need 2 bits to identify each subnet. Thus the subnet mask now becomes (/28).. Number of variable bits left = 32 -28 = 4 bits. Thus the total number of addresses in each subnet= 24= 16." }, { "code": null, "e": 25637, "s": 25580, "text": "There are two ways of approaching the solution:Method-1:" }, { "code": null, "e": 26346, "s": 25637, "text": "To find the First Address, understand that the first 26 bits will be the same as the address given because they were fixed. As discussed above the next 2 bits will also be fixed.Out of the 16 addresses of that a subnet holds, to point its first address it is required that all the 4 (non-fixed) bits are 0.So the first address of the 1st subnet =121.37.10. 01 00 0 0 0 0 /28 = 121.37.10.64/28.For the 2nd subnet =121.37.10. 01 01 0 0 0 0 /28 = 121.37.10.80/28and so on.To find the last address, add (the number of addresses in the subnet -1) to the first address of that subnet. In this case, add (16-1) to the first address of each subnet. So the last address of the 1st subnet is 121.37.10.79/28." }, { "code": null, "e": 26525, "s": 26346, "text": "To find the First Address, understand that the first 26 bits will be the same as the address given because they were fixed. As discussed above the next 2 bits will also be fixed." }, { "code": null, "e": 26654, "s": 26525, "text": "Out of the 16 addresses of that a subnet holds, to point its first address it is required that all the 4 (non-fixed) bits are 0." }, { "code": null, "e": 26828, "s": 26654, "text": "So the first address of the 1st subnet =121.37.10. 01 00 0 0 0 0 /28 = 121.37.10.64/28.For the 2nd subnet =121.37.10. 01 01 0 0 0 0 /28 = 121.37.10.80/28and so on." }, { "code": null, "e": 26881, "s": 26828, "text": "121.37.10. 01 00 0 0 0 0 /28 = 121.37.10.64/28." }, { "code": null, "e": 26902, "s": 26881, "text": "For the 2nd subnet =" }, { "code": null, "e": 26954, "s": 26902, "text": "121.37.10. 01 01 0 0 0 0 /28 = 121.37.10.80/28" }, { "code": null, "e": 26965, "s": 26954, "text": "and so on." }, { "code": null, "e": 27195, "s": 26965, "text": "To find the last address, add (the number of addresses in the subnet -1) to the first address of that subnet. In this case, add (16-1) to the first address of each subnet. So the last address of the 1st subnet is 121.37.10.79/28." }, { "code": null, "e": 27213, "s": 27195, "text": " 121.37.10.79/28." }, { "code": null, "e": 27235, "s": 27213, "text": "Method -2 (shortcut):" }, { "code": null, "e": 28223, "s": 27235, "text": "To find the first address of the 1st subnet, carryout AND operation between the address given and the subnet mask of the 1st subnet.Performing AND operation : 01111001 00100101 00001010 01000000/26\nAND 11111111 11111111 11111111 11110000/28\n-------------------------------------------------------------------------\n 01111001 00100101 00001010 01000000 /28 Thus, first Address of the 1st subnet= 01111001 00100101 00001010 01000000 /28 = 121.37.10.64 /28 To find the last address of a subnet, perform OR operation between the first address of the subnet and the complement of the subnet mask.First address of 1st subnet,= 01111001 00100101 00001010 01000000 /28 Complement of the subnet mask,= 00000000 00000000 0000000 00001111 / 28 Performing OR operation we get the last address of the 1st subnet= 01111001 00100101 00001010 00001111 / 28 = 121.37.10.79 /28 Add 1 to the last address of the previous subnet to find the first address of the next subnet." }, { "code": null, "e": 28706, "s": 28223, "text": "To find the first address of the 1st subnet, carryout AND operation between the address given and the subnet mask of the 1st subnet.Performing AND operation : 01111001 00100101 00001010 01000000/26\nAND 11111111 11111111 11111111 11110000/28\n-------------------------------------------------------------------------\n 01111001 00100101 00001010 01000000 /28 Thus, first Address of the 1st subnet= 01111001 00100101 00001010 01000000 /28 = 121.37.10.64 /28 " }, { "code": null, "e": 28929, "s": 28706, "text": " 01111001 00100101 00001010 01000000/26\nAND 11111111 11111111 11111111 11110000/28\n-------------------------------------------------------------------------\n 01111001 00100101 00001010 01000000 /28 " }, { "code": null, "e": 28967, "s": 28929, "text": "Thus, first Address of the 1st subnet" }, { "code": null, "e": 29033, "s": 28967, "text": "= 01111001 00100101 00001010 01000000 /28 = 121.37.10.64 /28 " }, { "code": null, "e": 29445, "s": 29033, "text": "To find the last address of a subnet, perform OR operation between the first address of the subnet and the complement of the subnet mask.First address of 1st subnet,= 01111001 00100101 00001010 01000000 /28 Complement of the subnet mask,= 00000000 00000000 0000000 00001111 / 28 Performing OR operation we get the last address of the 1st subnet= 01111001 00100101 00001010 00001111 / 28 = 121.37.10.79 /28 " }, { "code": null, "e": 29489, "s": 29445, "text": "= 01111001 00100101 00001010 01000000 /28 " }, { "code": null, "e": 29520, "s": 29489, "text": "Complement of the subnet mask," }, { "code": null, "e": 29563, "s": 29520, "text": "= 00000000 00000000 0000000 00001111 / 28 " }, { "code": null, "e": 29629, "s": 29563, "text": "Performing OR operation we get the last address of the 1st subnet" }, { "code": null, "e": 29696, "s": 29629, "text": "= 01111001 00100101 00001010 00001111 / 28 = 121.37.10.79 /28 " }, { "code": null, "e": 29791, "s": 29696, "text": "Add 1 to the last address of the previous subnet to find the first address of the next subnet." }, { "code": null, "e": 30005, "s": 29791, "text": "Note –When the number of subnets required cannot be computed in the powers of 2, then divide address space in a way that the number of subnets is closest to a number that can solely be represented as a power of 2." }, { "code": null, "e": 30230, "s": 30005, "text": "For example, if we need 14 subnets, then since 14 cannot be represented solely in the powers of 2, so we divide address space into 16 equal subnets. Now the respective addresses can be found using the above-mentioned method." }, { "code": null, "e": 30488, "s": 30230, "text": "2. Variable Length Subnet Masks :When a block of addresses is divided into subnets containing different numbers of addresses, type of subnetting is said to be Variable-Length Subnetting.The subnet masks used here might not be the same for different subnets." }, { "code": null, "e": 30693, "s": 30488, "text": "Example:Consider a block of address with starting address 112.78.0.0/16. Find the first and last addresses for each group, if the number and size of the subnets required by them are as given in the input." }, { "code": null, "e": 30700, "s": 30693, "text": "Input:" }, { "code": null, "e": 30854, "s": 30700, "text": "Group-1:\n256 subnets, each needs 128 addresses\n\nGroup-2:\n1024 subnets, each requiring 4 addresses\n\nGroup-1:\n128 subnets, each consisting of 16 addresses " }, { "code": null, "e": 30862, "s": 30854, "text": "Output:" }, { "code": null, "e": 31094, "s": 30862, "text": "Group-1:\nFirst Address : 112.78.0.0 /17\nLast Address : 112.78.127.255 /17 \n\nGroup-2:\nFirst Address : 112.78.128.0 /20\nLast Address : 112.78.143.255 / 20 \n\nGroup-3:\nFirst Address : 112.78.144.0 /21\nLast Address : 112.78.151.255 /21 " }, { "code": null, "e": 31252, "s": 31094, "text": "To understand such problems, it is important to understand the procedure to fix the bits in the subnet ID and find the subnet mask for each group of subnets." }, { "code": null, "e": 31300, "s": 31252, "text": "Given the Total addresses in the address block," }, { "code": null, "e": 31319, "s": 31300, "text": "= 232-16 = 65,536 " }, { "code": null, "e": 31364, "s": 31319, "text": "Understanding the division of address space," }, { "code": null, "e": 31418, "s": 31364, "text": "Group-1:\nNumber of addresses = 256 x 128 = 32, 768 " }, { "code": null, "e": 31550, "s": 31418, "text": "Thus, group 1 occupies 1/2 of the addresses in the block. So, 1 bit is fixed to identify this half and the Subnet Mask becomes /17." }, { "code": null, "e": 31634, "s": 31550, "text": "Similarly for Group-2, a total of 4 bits are fixed and the Subnet Mask becomes /20." }, { "code": null, "e": 31709, "s": 31634, "text": "And, for Group-3, a total of 5 bits are fixed and subnet mask becomes /21." }, { "code": null, "e": 31805, "s": 31709, "text": "Then using Method 2 mentioned above, the respective starting and ending addresses can be found." }, { "code": null, "e": 32279, "s": 31805, "text": "For the sake of understanding the problem, let the block of addresses be represented by a big square which can be further divided into the required subnets. Since the total number of addresses in the block = 65, 536, it can be deduced that the square is made up of 256 x 256 addresses. Observe the division of the address space and fixing of the initial bits in the subnet ID of the address space carefully. The blanks along with 8 more blanks together will be the host ID." }, { "code": null, "e": 32416, "s": 32279, "text": "Once the address space is appropriately divided and respective subnet masks found, use the methods above to find the required addresses." }, { "code": null, "e": 32448, "s": 32416, "text": "Computer Networks-Network Layer" }, { "code": null, "e": 32466, "s": 32448, "text": "Computer Networks" }, { "code": null, "e": 32474, "s": 32466, "text": "GATE CS" }, { "code": null, "e": 32492, "s": 32474, "text": "Computer Networks" }, { "code": null, "e": 32590, "s": 32492, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32599, "s": 32590, "text": "Comments" }, { "code": null, "e": 32612, "s": 32599, "text": "Old Comments" }, { "code": null, "e": 32647, "s": 32612, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 32680, "s": 32647, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 32698, "s": 32680, "text": "Stop and Wait ARQ" }, { "code": null, "e": 32744, "s": 32698, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 32782, "s": 32744, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 32806, "s": 32782, "text": "ACID Properties in DBMS" }, { "code": null, "e": 32827, "s": 32806, "text": "Normal Forms in DBMS" }, { "code": null, "e": 32854, "s": 32827, "text": "Types of Operating Systems" }, { "code": null, "e": 32903, "s": 32854, "text": "Page Replacement Algorithms in Operating Systems" } ]
Report Expression
Report expressions are the powerful features of JasperReports, which allow us to display calculated data on a report. Calculated data is the data that is not a static data and is not specifically passed as a report parameter or datasource field. Report expressions are built from combining report parameters, fields, and static data. The Java language is used for writing report expressions by default. Other scripting languages for report expressions like Groovy scripting language, JavaScript, or BeanShell script are supported by JasperReports compilers. This chapter will explain you − how do report expressions work, assuming that they have been written using the Java language only. In a JRXML report template, there are several elements that define expressions as − <variableExpression> <initialValueExpression> <groupExpression> <printWhenExpression> <imageExpression> <textFieldExpression> Basically, all report expressions are Java expressions, which can reference the report fields, report variables, and report parameters. To use a report field reference in an expression, the name of the field must be put between $F{and} character sequences, as shown below − <textfieldexpression> $F{Name} </textfieldexpression> Following is a piece of code from our existing JRXML file (chapter Report Designs) − <textFieldExpression class = "java.lang.String"> <![CDATA[$F{country}]]> </textFieldExpression> To reference a variable in an expression, we must put the name of the variable between $V{and} as shown in the example given below − <textfieldexpression> "Total height : " + $V{SumOfHeight} + " ft." </textfieldexpression> To reference a parameter in an expression, the name of the parameter should be put between $P{and} as shown in the example given below − <textfieldexpression> "ReportTitle : " + $P{Title} </textfieldexpression> Following is a piece of code from our existing JRXML file, which demonstrates the referencing of parameter in an expression. (JRXML from chapter Report Designs) − <textField isBlankWhenNull = "true" bookmarkLevel = "1"> <reportElement x = "0" y = "10" width = "515" height = "30"/> <textElement textAlignment = "Center"> <font size = "22"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{ReportTitle}]]> </textFieldExpression> <anchorNameExpression> <![CDATA["Title"]]> </anchorNameExpression> </textField> <textField isBlankWhenNull = "true"> <reportElement x = "0" y = "40" width = "515" height = "20"/> <textElement textAlignment = "Center"> <font size = "10"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{Author}]]> </textFieldExpression> </textField> As you have seen above, the parameter, field, and variable references are in fact real Java objects. Knowing their class from the parameter, field, or variable declaration made in the report template, we can even call methods on those object references in the expressions. The following example shows − how to extract and display the first letter from java.lang.String report field "Name" − <textFieldExpression> $F{Name}.substring(0, 1) </textFieldExpression> To reference a resource in an expression, the key should be put between $R{and} as shown in the example given below − <textfieldexpression> $R{report.title} </textfieldexpression> Based on the runtime-supplied locale and the report.title key, the resource bundle associated with the report template is loaded. Hence, the title of report is displayed by extracting the String value from the resource bundle. More on internationalization can be found in the chapter Internationalization. Calculator is an entity in JasperReports, which evaluates expressions and increments variables or datasets at report-filling time. During compiling process, the information is produced and stored in the compile report by the compiler. This information is used during the report-filling time to build an instance of the net.sf.jasperreports.engine.fill.JRCalculator class. Java source file is generated and compiled by Java-based report compilers on the fly. This generated class is a subclass of the JRCalculator, and the bytecode produced by compiling it is stored inside the JasperReport object. This bytcode is loaded at the report filling time and the resulting class is instantiated to obtain the calculator object needed for expression evaluation. JasperReports doesn't support if-else statements when defining variable expressions. Instead, you can use the ternary operators {cond} ? {statement 1} : {statement 2}. This operator can be nested inside a Java expression to obtain the desired output based on multiple conditions. Let's modify existing report template (Chapter Report Designs) and add a conditional expression for the field country. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory − <?xml version = "1.0"?> <!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"> <jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name = "jasper_report_template" pageWidth = "595" pageHeight = "842" columnWidth = "515" leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50"> <parameter name = "ReportTitle" class = "java.lang.String"/> <parameter name = "Author" class = "java.lang.String"/> <queryString> <![CDATA[]]> </queryString> <field name = "country" class = "java.lang.String"> <fieldDescription><![CDATA[country]]></fieldDescription> </field> <field name = "name" class = "java.lang.String"> <fieldDescription><![CDATA[name]]></fieldDescription> </field> <sortField name = "country" order = "Descending"/> <sortField name = "name"/> <title> <band height = "70"> <line> <reportElement x = "0" y = "0" width = "515" height = "1"/> </line> <textField isBlankWhenNull = "true" bookmarkLevel = "1"> <reportElement x = "0" y = "10" width = "515" height = "30"/> <textElement textAlignment = "Center"> <font size = "22"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{ReportTitle}]]> </textFieldExpression> <anchorNameExpression> <![CDATA["Title"]]> </anchorNameExpression> </textField> <textField isBlankWhenNull = "true"> <reportElement x = "0" y = "40" width = "515" height = "20"/> <textElement textAlignment = "Center"> <font size = "10"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{Author}]]> </textFieldExpression> </textField> </band> </title> <columnHeader> <band height = "23"> <staticText> <reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15" backcolor = "#70A9A9" /> <box> <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" /> </box> <textElement /> <text> <![CDATA[]]> </text> </staticText> <staticText> <reportElement x = "414" y = "3" width = "121" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font isBold = "true" /> </textElement> <text><![CDATA[Country]]></text> </staticText> <staticText> <reportElement x = "0" y = "3" width = "136" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font isBold = "true" /> </textElement> <text><![CDATA[Name]]></text> </staticText> </band> </columnHeader> <detail> <band height = "16"> <staticText> <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14" backcolor = "#E5ECF9" /> <box> <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" /> </box> <textElement /> <text> <![CDATA[]]> </text> </staticText> <textField> <reportElement x = "414" y = "0" width = "121" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font size = "9" /> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{country}.isEmpty() ? "NO COUNTRY" : $F{country}]]> </textFieldExpression> </textField> <textField> <reportElement x = "0" y = "0" width = "136" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle" /> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{name}]]> </textFieldExpression> </textField> </band> </detail> </jasperReport> The java codes for report filling are as follows. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as − package com.tutorialspoint; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; public class JasperReportFill { @SuppressWarnings("unchecked") public static void main(String[] args) { String sourceFileName = "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper"; DataBeanList DataBeanList = new DataBeanList(); ArrayList<DataBean> dataList = DataBeanList.getDataBeanList(); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList); Map parameters = new HashMap(); /** * Passing ReportTitle and Author as parameters */ parameters.put("ReportTitle", "List of Contacts"); parameters.put("Author", "Prepared By Manisha"); try { JasperFillManager.fillReportToFile( sourceFileName, parameters, beanColDataSource); } catch (JRException e) { e.printStackTrace(); } } } The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as − package com.tutorialspoint; public class DataBean { private String name; private String country; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } We will add a new record with country field as empty in our Java bean List. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as − package com.tutorialspoint; import java.util.ArrayList; public class DataBeanList { public ArrayList<DataBean> getDataBeanList() { ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>(); dataBeanList.add(produce("Manisha", "India")); dataBeanList.add(produce("Dennis Ritchie", "USA")); dataBeanList.add(produce("V.Anand", "India")); dataBeanList.add(produce("Shrinath", "California")); dataBeanList.add(produce("Tanmay", "")); return dataBeanList; } /** * This method returns a DataBean object, * with name and country set in it. */ private DataBean produce(String name, String country) { DataBean dataBean = new DataBean(); dataBean.setName(name); dataBean.setCountry(country); return dataBean; } } We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are given below. The import file - baseBuild.xml is picked from chapter the Environment Setup and should be placed in the same directory as the build.xml. <?xml version = "1.0" encoding = "UTF-8"?> <project name = "JasperReportTest" default = "viewFillReport" basedir = "."> <import file = "baseBuild.xml" /> <target name = "viewFillReport" depends = "compile,compilereportdesing,run" description = "Launches the report viewer to preview the report stored in the .JRprint file."> <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true"> <arg value = "-F${file.name}.JRprint" /> <classpath refid = "classpath" /> </java> </target> <target name = "compilereportdesing" description = "Compiles the JXML file and produces the .jasper file."> <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask"> <classpath refid = "classpath" /> </taskdef> <jrc destdir = "."> <src> <fileset dir = "."> <include name = "*.jrxml" /> </fileset> </src> <classpath refid = "classpath" /> </jrc> </target> </project> Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class = com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as − C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml clean-sample: [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint compile: [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds [javac] Compiling 3 source files to C:\tools\jasperreports-5.0.1\test\classes compilereportdesing: [jrc] Compiling 1 report design files. [jrc] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory). [jrc] log4j:WARN Please initialize the log4j system properly. [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK. run: [echo] Runnin class : com.tutorialspoint.JasperReportFill [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. viewFillReport: [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. BUILD SUCCESSFUL Total time: 5 minutes 5 seconds C:\tools\jasperreports-5.0.1\test> As a result of above compilation, a JasperViewer window opens up as shown in the screen given below − Here, we can see, for the last record, we had not passed any data for the field country, "NO COUNTRY" is being printed. Print Add Notes Bookmark this page
[ { "code": null, "e": 2812, "s": 2254, "text": "Report expressions are the powerful features of JasperReports, which allow us to display calculated data on a report. Calculated data is the data that is not a static data and is not specifically passed as a report parameter or datasource field. Report expressions are built from combining report parameters, fields, and static data. The Java language is used for writing report expressions by default. Other scripting languages for report expressions like Groovy scripting language, JavaScript, or BeanShell script are supported by JasperReports compilers." }, { "code": null, "e": 3027, "s": 2812, "text": "This chapter will explain you − how do report expressions work, assuming that they have been written using the Java language only. In a JRXML report template, there are several elements that define expressions as −" }, { "code": null, "e": 3048, "s": 3027, "text": "<variableExpression>" }, { "code": null, "e": 3073, "s": 3048, "text": "<initialValueExpression>" }, { "code": null, "e": 3091, "s": 3073, "text": "<groupExpression>" }, { "code": null, "e": 3113, "s": 3091, "text": "<printWhenExpression>" }, { "code": null, "e": 3131, "s": 3113, "text": "<imageExpression>" }, { "code": null, "e": 3153, "s": 3131, "text": "<textFieldExpression>" }, { "code": null, "e": 3289, "s": 3153, "text": "Basically, all report expressions are Java expressions, which can reference the report fields, report variables, and report parameters." }, { "code": null, "e": 3427, "s": 3289, "text": "To use a report field reference in an expression, the name of the field must be put between $F{and} character sequences, as shown below −" }, { "code": null, "e": 3484, "s": 3427, "text": "<textfieldexpression>\n $F{Name}\n</textfieldexpression>" }, { "code": null, "e": 3569, "s": 3484, "text": "Following is a piece of code from our existing JRXML file (chapter Report Designs) −" }, { "code": null, "e": 3668, "s": 3569, "text": "<textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}]]>\n</textFieldExpression>" }, { "code": null, "e": 3801, "s": 3668, "text": "To reference a variable in an expression, we must put the name of the variable between $V{and} as shown in the example given below −" }, { "code": null, "e": 3894, "s": 3801, "text": "<textfieldexpression>\n \"Total height : \" + $V{SumOfHeight} + \" ft.\"\n</textfieldexpression>" }, { "code": null, "e": 4031, "s": 3894, "text": "To reference a parameter in an expression, the name of the parameter should be put between $P{and} as shown in the example given below −" }, { "code": null, "e": 4108, "s": 4031, "text": "<textfieldexpression>\n \"ReportTitle : \" + $P{Title}\n</textfieldexpression>" }, { "code": null, "e": 4271, "s": 4108, "text": "Following is a piece of code from our existing JRXML file, which demonstrates the referencing of parameter in an expression. (JRXML from chapter Report Designs) −" }, { "code": null, "e": 5013, "s": 4271, "text": "<textField isBlankWhenNull = \"true\" bookmarkLevel = \"1\">\n <reportElement x = \"0\" y = \"10\" width = \"515\" height = \"30\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"22\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{ReportTitle}]]>\n </textFieldExpression>\n \n <anchorNameExpression>\n <![CDATA[\"Title\"]]>\n </anchorNameExpression>\n</textField>\n\n<textField isBlankWhenNull = \"true\">\n <reportElement x = \"0\" y = \"40\" width = \"515\" height = \"20\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"10\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{Author}]]>\n </textFieldExpression>\n</textField>" }, { "code": null, "e": 5286, "s": 5013, "text": "As you have seen above, the parameter, field, and variable references are in fact real Java objects. Knowing their class from the parameter, field, or variable declaration made in the report template, we can even call methods on those object references in the expressions." }, { "code": null, "e": 5404, "s": 5286, "text": "The following example shows − how to extract and display the first letter from java.lang.String report field \"Name\" −" }, { "code": null, "e": 5477, "s": 5404, "text": "<textFieldExpression>\n $F{Name}.substring(0, 1)\n</textFieldExpression>" }, { "code": null, "e": 5595, "s": 5477, "text": "To reference a resource in an expression, the key should be put between $R{and} as shown in the example given below −" }, { "code": null, "e": 5660, "s": 5595, "text": "<textfieldexpression>\n $R{report.title}\n</textfieldexpression>" }, { "code": null, "e": 5966, "s": 5660, "text": "Based on the runtime-supplied locale and the report.title key, the resource bundle associated with the report template is loaded. Hence, the title of report is displayed by extracting the String value from the resource bundle. More on internationalization can be found in the chapter Internationalization." }, { "code": null, "e": 6339, "s": 5966, "text": "Calculator is an entity in JasperReports, which evaluates expressions and increments variables or datasets at report-filling time. During compiling process, the information is produced and stored in the compile report by the compiler. This information is used during the report-filling time to build an instance of the net.sf.jasperreports.engine.fill.JRCalculator class." }, { "code": null, "e": 6721, "s": 6339, "text": "Java source file is generated and compiled by Java-based report compilers on the fly. This generated class is a subclass of the JRCalculator, and the bytecode produced by compiling it is stored inside the JasperReport object. This bytcode is loaded at the report filling time and the resulting class is instantiated to obtain the calculator object needed for expression evaluation." }, { "code": null, "e": 7001, "s": 6721, "text": "JasperReports doesn't support if-else statements when defining variable expressions. Instead, you can use the ternary operators {cond} ? {statement 1} : {statement 2}. This operator can be nested inside a Java expression to obtain the desired output based on multiple conditions." }, { "code": null, "e": 7251, "s": 7001, "text": "Let's modify existing report template (Chapter Report Designs) and add a conditional expression for the field country. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\\tools\\jasperreports-5.0.1\\test directory −" }, { "code": null, "e": 12084, "s": 7251, "text": "<?xml version = \"1.0\"?>\n<!DOCTYPE jasperReport PUBLIC\n \"//JasperReports//DTD Report Design//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd\">\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation = \n \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\" \n name = \"jasper_report_template\" pageWidth = \"595\" pageHeight = \"842\" \n columnWidth = \"515\" leftMargin = \"40\" rightMargin = \"40\" \n topMargin = \"50\" bottomMargin = \"50\">\n\n <parameter name = \"ReportTitle\" class = \"java.lang.String\"/>\n <parameter name = \"Author\" class = \"java.lang.String\"/>\n \n <queryString>\n <![CDATA[]]>\n </queryString>\n \n <field name = \"country\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[country]]></fieldDescription>\n </field>\n \n <field name = \"name\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[name]]></fieldDescription>\n </field>\n \n <sortField name = \"country\" order = \"Descending\"/>\n <sortField name = \"name\"/>\n \n <title>\n <band height = \"70\">\n \n <line>\n <reportElement x = \"0\" y = \"0\" width = \"515\" height = \"1\"/>\n </line>\n \n <textField isBlankWhenNull = \"true\" bookmarkLevel = \"1\">\n <reportElement x = \"0\" y = \"10\" width = \"515\" height = \"30\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"22\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{ReportTitle}]]>\n </textFieldExpression>\n \n <anchorNameExpression>\n <![CDATA[\"Title\"]]>\n </anchorNameExpression>\n </textField>\n \n <textField isBlankWhenNull = \"true\">\n <reportElement x = \"0\" y = \"40\" width = \"515\" height = \"20\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"10\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{Author}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </title>\n \n <columnHeader>\n <band height = \"23\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"3\" width = \"535\" height = \"15\"\n backcolor = \"#70A9A9\" />\n \n <box>\n <bottomPen lineWidth = \"1.0\" lineColor = \"#CCCCCC\" />\n </box>\n \n <textElement />\n <text>\n <![CDATA[]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"414\" y = \"3\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n\t\t\t\t\n <text><![CDATA[Country]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"3\" width = \"136\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Name]]></text>\n </staticText>\n \n </band>\n </columnHeader>\n\n <detail>\n <band height = \"16\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"0\" width = \"535\" height = \"14\"\n backcolor = \"#E5ECF9\" />\n \n <box>\n <bottomPen lineWidth = \"0.25\" lineColor = \"#CCCCCC\" />\n </box>\n\t\t\t\t\n <textElement />\n <text>\n <![CDATA[]]>\n </text>\n </staticText>\n \n <textField>\n <reportElement x = \"414\" y = \"0\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font size = \"9\" />\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}.isEmpty() ? \"NO COUNTRY\" : $F{country}]]>\n </textFieldExpression>\n </textField>\n \n <textField>\n <reportElement x = \"0\" y = \"0\" width = \"136\" height = \"15\" />\n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\" />\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{name}]]>\n </textFieldExpression>\n </textField>\n\t\t\t\n </band>\n </detail>\n\t\n</jasperReport>" }, { "code": null, "e": 12247, "s": 12084, "text": "The java codes for report filling are as follows. The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\JasperReportFill.java are as −" }, { "code": null, "e": 13381, "s": 12247, "text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperFillManager;\nimport net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;\n\npublic class JasperReportFill {\n @SuppressWarnings(\"unchecked\")\n public static void main(String[] args) {\n String sourceFileName =\n \"C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper\";\n\n DataBeanList DataBeanList = new DataBeanList();\n ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();\n\n JRBeanCollectionDataSource beanColDataSource =\n new JRBeanCollectionDataSource(dataList);\n\n Map parameters = new HashMap();\n /**\n * Passing ReportTitle and Author as parameters\n */\n parameters.put(\"ReportTitle\", \"List of Contacts\");\n parameters.put(\"Author\", \"Prepared By Manisha\");\n\n try {\n JasperFillManager.fillReportToFile(\n sourceFileName, parameters, beanColDataSource);\n } catch (JRException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 13491, "s": 13381, "text": "The contents of the POJO file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBean.java are as −" }, { "code": null, "e": 13859, "s": 13491, "text": "package com.tutorialspoint;\n\npublic class DataBean {\n private String name;\n private String country;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n}" }, { "code": null, "e": 14044, "s": 13859, "text": "We will add a new record with country field as empty in our Java bean List. The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBeanList.java are as −" }, { "code": null, "e": 14861, "s": 14044, "text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\n\npublic class DataBeanList {\n public ArrayList<DataBean> getDataBeanList() {\n ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();\n\n dataBeanList.add(produce(\"Manisha\", \"India\"));\n dataBeanList.add(produce(\"Dennis Ritchie\", \"USA\"));\n dataBeanList.add(produce(\"V.Anand\", \"India\"));\n dataBeanList.add(produce(\"Shrinath\", \"California\"));\n dataBeanList.add(produce(\"Tanmay\", \"\"));\n \n return dataBeanList;\n }\n\n /**\n * This method returns a DataBean object,\n * with name and country set in it.\n */\n private DataBean produce(String name, String country) {\n DataBean dataBean = new DataBean();\n dataBean.setName(name);\n dataBean.setCountry(country);\n \n return dataBean;\n }\n}" }, { "code": null, "e": 15051, "s": 14861, "text": "We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\\tools\\jasperreports-5.0.1\\test) are given below." }, { "code": null, "e": 15189, "s": 15051, "text": "The import file - baseBuild.xml is picked from chapter the Environment Setup and should be placed in the same directory as the build.xml." }, { "code": null, "e": 16265, "s": 15189, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewFillReport\" basedir = \".\">\n <import file = \"baseBuild.xml\" />\n \n <target name = \"viewFillReport\" depends = \"compile,compilereportdesing,run\"\n description = \"Launches the report viewer to preview\n the report stored in the .JRprint file.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.JRprint\" />\n <classpath refid = \"classpath\" />\n </java>\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\" classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n \n </target>\n\t\n</project>" }, { "code": null, "e": 16481, "s": 16265, "text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class = com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −" }, { "code": null, "e": 18202, "s": 16481, "text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jasper\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrprint\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28:\n warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last;\n set to false for repeatable builds\n [javac] Compiling 3 source files to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See\n http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nviewFillReport:\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nBUILD SUCCESSFUL\nTotal time: 5 minutes 5 seconds\n\nC:\\tools\\jasperreports-5.0.1\\test>\n" }, { "code": null, "e": 18304, "s": 18202, "text": "As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −" }, { "code": null, "e": 18424, "s": 18304, "text": "Here, we can see, for the last record, we had not passed any data for the field country, \"NO COUNTRY\" is being printed." }, { "code": null, "e": 18431, "s": 18424, "text": " Print" }, { "code": null, "e": 18442, "s": 18431, "text": " Add Notes" } ]
C program to find if the given number is perfect number or not
Perfect number is the number; whose sum of factors is equal to 2*number. An algorithm is explained below − START Step 1: declare int variables and initialized result=0. Step 2: read number at runtime. Step 3: for loop i=1;i<=number;i++ Condition satisfies i. if(number%i==0) ii. result=result+i; Step 4: checking the sum of factors. i. if(result==2*number) ii. print perfect number iii. else print not perfect number STOP Following is the C program to find if the given number is perfect number or not − Live Demo #include<stdio.h> int main(){ int number,i,result=0;//declare variables and initialize result to 0 printf("enter the number:"); scanf("%d",&number); for(i=1;i<=number;i++){ if(number%i==0) result=result+i; } if(result==2*number) //checking the sum of factors==2*number printf("perfect number"); else printf("not perfect number"); } The output is given below − enter the number:28 perfect number enter the number:46 not perfect number
[ { "code": null, "e": 1135, "s": 1062, "text": "Perfect number is the number; whose sum of factors is equal to 2*number." }, { "code": null, "e": 1169, "s": 1135, "text": "An algorithm is explained below −" }, { "code": null, "e": 1499, "s": 1169, "text": "START\nStep 1: declare int variables and initialized result=0.\nStep 2: read number at runtime.\nStep 3: for loop i=1;i<=number;i++\nCondition satisfies\n i. if(number%i==0)\n ii. result=result+i;\nStep 4: checking the sum of factors.\n i. if(result==2*number)\n ii. print perfect number\n iii. else print not perfect number\nSTOP" }, { "code": null, "e": 1581, "s": 1499, "text": "Following is the C program to find if the given number is perfect number or not −" }, { "code": null, "e": 1592, "s": 1581, "text": " Live Demo" }, { "code": null, "e": 1972, "s": 1592, "text": "#include<stdio.h>\nint main(){\n int number,i,result=0;//declare variables and initialize result to 0\n printf(\"enter the number:\");\n scanf(\"%d\",&number);\n for(i=1;i<=number;i++){\n if(number%i==0)\n result=result+i;\n }\n if(result==2*number) //checking the sum of factors==2*number\n printf(\"perfect number\");\n else\n printf(\"not perfect number\");\n}" }, { "code": null, "e": 2000, "s": 1972, "text": "The output is given below −" }, { "code": null, "e": 2074, "s": 2000, "text": "enter the number:28\nperfect number\nenter the number:46\nnot perfect number" } ]
How to use “window.print()” function to print a page?
To print a page in JavaScript, use the window.print() method. It opens up the standard dialog box, through which you can easily set the printing options like which printer to select for printing. You can try to run the following code to learn how to print a page − Live Demo <!DOCTYPE html> <html> <body> <button onclick="display()">Click to Print</button> <script> function display() { window.print(); } </script> </body> </html>
[ { "code": null, "e": 1258, "s": 1062, "text": "To print a page in JavaScript, use the window.print() method. It opens up the standard dialog box, through which you can easily set the printing options like which printer to select for printing." }, { "code": null, "e": 1327, "s": 1258, "text": "You can try to run the following code to learn how to print a page −" }, { "code": null, "e": 1337, "s": 1327, "text": "Live Demo" }, { "code": null, "e": 1547, "s": 1337, "text": "<!DOCTYPE html>\n<html>\n <body>\n <button onclick=\"display()\">Click to Print</button>\n <script>\n function display() {\n window.print();\n }\n </script>\n </body>\n</html>" } ]
HTML5 Semantics
The HTML5 Semantics refers to the semantic tags that provide meaning to an HTML page. In HTML5 the tags are divided into two categories - semantic and non-semantic. HTML5 brings several new semantic tags to the HTML. Some HTML5 Semantic tags are − Let us see an example of HTML5 Semantics − Live Demo <!DOCTYPE html> <html> <style> * { box-sizing: border-box; } body { color: #000; background-color: #8BC6EC; background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%); text-align: center; } header { background-color: #000; padding: 20px; text-align: center; color: white; } nav { float: left; width: 20%; height: 200px; background: #282828; padding: 60px 10px; } nav ul { list-style-type: none; padding: 0; } nav ul li a { text-decoration: none; color: #fff; } article { float: left; padding: 80px 10px; width: 80%; background-color: #fff; height: 200px; text-align: center; } section:after { content: ""; display: table; clear: both; } footer { background-color: #000; padding: 20px; text-align: center; color: white; } </style> <body> <h1>HTML Semantics Demo</h1> <header>This is Header</header> <section> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> <article>This is an article element.</article> </section> <footer>This is Footer</footer> </body> </html>
[ { "code": null, "e": 1279, "s": 1062, "text": "The HTML5 Semantics refers to the semantic tags that provide meaning to an HTML page. In HTML5 the tags are divided into two categories - semantic and non-semantic. HTML5 brings several new semantic tags to the HTML." }, { "code": null, "e": 1310, "s": 1279, "text": "Some HTML5 Semantic tags are −" }, { "code": null, "e": 1353, "s": 1310, "text": "Let us see an example of HTML5 Semantics −" }, { "code": null, "e": 1364, "s": 1353, "text": " Live Demo" }, { "code": null, "e": 2645, "s": 1364, "text": "<!DOCTYPE html>\n<html>\n<style>\n * {\n box-sizing: border-box;\n }\n body {\n color: #000;\n background-color: #8BC6EC;\n background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%);\n text-align: center;\n }\n header {\n background-color: #000;\n padding: 20px;\n text-align: center;\n color: white;\n }\n nav {\n float: left;\n width: 20%;\n height: 200px;\n background: #282828;\n padding: 60px 10px;\n }\n nav ul {\n list-style-type: none;\n padding: 0;\n }\n nav ul li a {\n text-decoration: none;\n color: #fff;\n }\n article {\n float: left;\n padding: 80px 10px;\n width: 80%;\n background-color: #fff;\n height: 200px;\n text-align: center;\n }\n section:after {\n content: \"\";\n display: table;\n clear: both;\n }\n footer {\n background-color: #000;\n padding: 20px;\n text-align: center;\n color: white;\n }\n</style>\n<body>\n<h1>HTML Semantics Demo</h1>\n<header>This is Header</header>\n<section>\n<nav>\n<ul>\n<li><a href=\"#\">Home</a></li>\n<li><a href=\"#\">About</a></li>\n<li><a href=\"#\">Contact</a></li>\n</ul>\n</nav>\n<article>This is an article element.</article>\n</section>\n<footer>This is Footer</footer>\n</body>\n</html>" } ]
How to set a minimum and maximum value for an input element in HTML5 ? - GeeksforGeeks
17 Mar, 2021 In this article, we are going to learn how to set a minimum and maximum value for an input element by using the HTML <input> min and max attribute. This prevents the input element from accepting values that are lower than the minimum value or higher than the maximum. Approach: This can be implemented by using the min and max attributes: min: This attribute accepts a minimum value for the input element. max: This attribute accepts a minimum value for the input element. These parameters together can be used to specify a range of numbers that can be accepted as input. Note that these attributes only work on the input type of number and date. Syntax: <input type="number" min="min_value" max="max_value"> Example: In this example, we have used two inputs with different input types, one is a number type and the other is the date type. The minimum and maximum range of the number is from 1 to 100 and the dates are from 01-01-2020 to 01-01-2021. HTML <html><head> <style type="text/css"> label { font: 18px; } input { margin: 7px; padding: 2px } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <h3>Set a minimum and maximum value</h3> <form> <label for="Number"> Enter Number (between 1 and 100): </label> <input type="number" id="Number" name="Number" min="1" max="100"> <br> <label for="datemin">Enter a date after 01-01-2020 and before 01-01-2021: </label> <input type="date" id="datemin" name="datemin" min="2020-01-01" max="2021-01-01"> <br> <input type="submit"> </form></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. HTML-Questions HTML5 Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery How to auto-resize an image to fit a div container using CSS? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 24894, "s": 24866, "text": "\n17 Mar, 2021" }, { "code": null, "e": 25162, "s": 24894, "text": "In this article, we are going to learn how to set a minimum and maximum value for an input element by using the HTML <input> min and max attribute. This prevents the input element from accepting values that are lower than the minimum value or higher than the maximum." }, { "code": null, "e": 25233, "s": 25162, "text": "Approach: This can be implemented by using the min and max attributes:" }, { "code": null, "e": 25300, "s": 25233, "text": "min: This attribute accepts a minimum value for the input element." }, { "code": null, "e": 25367, "s": 25300, "text": "max: This attribute accepts a minimum value for the input element." }, { "code": null, "e": 25541, "s": 25367, "text": "These parameters together can be used to specify a range of numbers that can be accepted as input. Note that these attributes only work on the input type of number and date." }, { "code": null, "e": 25549, "s": 25541, "text": "Syntax:" }, { "code": null, "e": 25603, "s": 25549, "text": "<input type=\"number\" min=\"min_value\" max=\"max_value\">" }, { "code": null, "e": 25844, "s": 25603, "text": "Example: In this example, we have used two inputs with different input types, one is a number type and the other is the date type. The minimum and maximum range of the number is from 1 to 100 and the dates are from 01-01-2020 to 01-01-2021." }, { "code": null, "e": 25849, "s": 25844, "text": "HTML" }, { "code": "<html><head> <style type=\"text/css\"> label { font: 18px; } input { margin: 7px; padding: 2px } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h3>Set a minimum and maximum value</h3> <form> <label for=\"Number\"> Enter Number (between 1 and 100): </label> <input type=\"number\" id=\"Number\" name=\"Number\" min=\"1\" max=\"100\"> <br> <label for=\"datemin\">Enter a date after 01-01-2020 and before 01-01-2021: </label> <input type=\"date\" id=\"datemin\" name=\"datemin\" min=\"2020-01-01\" max=\"2021-01-01\"> <br> <input type=\"submit\"> </form></body></html>", "e": 26506, "s": 25849, "text": null }, { "code": null, "e": 26514, "s": 26506, "text": "Output:" }, { "code": null, "e": 26651, "s": 26514, "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": 26666, "s": 26651, "text": "HTML-Questions" }, { "code": null, "e": 26672, "s": 26666, "text": "HTML5" }, { "code": null, "e": 26679, "s": 26672, "text": "Picked" }, { "code": null, "e": 26684, "s": 26679, "text": "HTML" }, { "code": null, "e": 26701, "s": 26684, "text": "Web Technologies" }, { "code": null, "e": 26706, "s": 26701, "text": "HTML" }, { "code": null, "e": 26804, "s": 26706, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26813, "s": 26804, "text": "Comments" }, { "code": null, "e": 26826, "s": 26813, "text": "Old Comments" }, { "code": null, "e": 26850, "s": 26826, "text": "REST API (Introduction)" }, { "code": null, "e": 26887, "s": 26850, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26907, "s": 26887, "text": "Angular File Upload" }, { "code": null, "e": 26936, "s": 26907, "text": "Form validation using jQuery" }, { "code": null, "e": 26998, "s": 26936, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 27040, "s": 26998, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27073, "s": 27040, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27116, "s": 27073, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27161, "s": 27116, "text": "Convert a string to an integer in JavaScript" } ]
How to create Custom Cursor using CSS
We can create a custom cursor image with extensions like .cur (for Internet Explorer), .gif and .png (for Chrome, Firefox, Safari) and apply it to an element using the CSS cursor property and setting it to a url and in addition a generic cursor value such as auto,default, pointer, etc. Selector { cursor: url("/*path to custom cursor file*/"), generic cursor; } Let’s see how to create custom cursor with an example − Live Demo <!DOCTYPE html> <html> <head> <title>Custom Cursor Using CSS</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } input[type="button"] { border-radius: 10px; } #tech1 { cursor: url("https://www.tutorialspoint.com/images/dbms.png"), auto; } #tech2 { cursor: url("https://www.tutorialspoint.com/images/Python.png"), auto; } </style> </head> <body> <form> <fieldset> <legend>Custom Cursor Using CSS</legend> <h1>Learn</h1> <input type="button" id="tech1" value="DBMS"> <input type="button" id="tech2" value="Python"> </fieldset> </form> </body></html> Following is the output for the above code − Hovering over ‘DBMS’ button − Hovering over ‘Python’ button −
[ { "code": null, "e": 1349, "s": 1062, "text": "We can create a custom cursor image with extensions like .cur (for Internet Explorer), .gif and .png (for Chrome, Firefox, Safari) and apply it to an element using the CSS cursor property and setting it to a url and in addition a generic cursor value such as auto,default, pointer, etc." }, { "code": null, "e": 1428, "s": 1349, "text": "Selector {\n cursor: url(\"/*path to custom cursor file*/\"), generic cursor;\n}" }, { "code": null, "e": 1484, "s": 1428, "text": "Let’s see how to create custom cursor with an example −" }, { "code": null, "e": 1495, "s": 1484, "text": " Live Demo" }, { "code": null, "e": 2119, "s": 1495, "text": "<!DOCTYPE html>\n<html>\n<head>\n<title>Custom Cursor Using CSS</title>\n<style>\nform {\n width:70%;\n margin: 0 auto;\n text-align: center;\n}\n* {\n padding: 2px;\n margin:5px;\n}\ninput[type=\"button\"] {\n border-radius: 10px;\n}\n#tech1 {\n cursor: url(\"https://www.tutorialspoint.com/images/dbms.png\"), auto;\n}\n#tech2 {\n cursor: url(\"https://www.tutorialspoint.com/images/Python.png\"), auto;\n}\n</style>\n</head>\n<body>\n<form>\n<fieldset>\n<legend>Custom Cursor Using CSS</legend>\n<h1>Learn</h1>\n<input type=\"button\" id=\"tech1\" value=\"DBMS\">\n<input type=\"button\" id=\"tech2\" value=\"Python\">\n</fieldset>\n</form>\n</body></html>" }, { "code": null, "e": 2164, "s": 2119, "text": "Following is the output for the above code −" }, { "code": null, "e": 2194, "s": 2164, "text": "Hovering over ‘DBMS’ button −" }, { "code": null, "e": 2226, "s": 2194, "text": "Hovering over ‘Python’ button −" } ]
68–95–99.7 — The Three-Sigma Rule of Thumb Used in Power BI. | by Sebastian Zolg 🤝 | Towards Data Science
Even in the smallest of all data projects, one of the most important steps is detecting abnormal values, outliers or anomalies within your data structure. In this brief guide, I will show you the most basic way of detecting such values using no code at all. Besides the many ways to achieve this in Power BI, this is the most straight forward and UI-driven one, and still very helpful. A common method to define outliers is the “3 times the standard deviation” rule, often referred to as the three-sigma rule of thumb. Want more background? Find it on Wikipedia. Suppose we have a column with values in our dataset, and we want to detect if it contains outliers or not. Todo so we look at|value — average|, to measure how far away the value is from the average. If this absolute value is more than 3 times the standard deviation of our values, then we can consider the value as an outlier or anomaly. The approach works best on data that follows a standard normal distribution. But even for non-normally distributed variables, the three-sigma rule tells us that at least 88.8% of cases should fall within properly calculated three-sigma intervals. To work along this guide take any of your own datasets or download my dataset filled with 5000 random values as per the standard normal distribution. Concretely, it is filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1. github.com Want to know how to create such data with python? See the bonus section at the end of this guide. Let’s extract our data from randoms.csv file inside the repository and load it into Power BI. Open Power BI and click Get Data. Select Text/CSV, click Connect and select the previously downloaded randoms.csv file. Review the data and make sure that it is loaded correctly. Click Transform Data to extract it into Power BI. We want to have a custom column that allows us to easily filter for outliers. To identify outliers we first need to calculate the Average (mean) and the Standard Deviation of all our data. To do so we duplicate our initial query two times. Select the initial query, right-click it and choose Duplicate from the context menu. Repeat this step a second time so you have a total of 3 queries. Now we quickly rename our duplicated queries to Mean and Standard Deviation so it reflects our intent. Right-click both queries and click Rename from the context menu. Now that we have named our queries properly we can go ahead and do a quick calculation on our Randoms column for both the Mean and the Standard Deviation query. Select the Mean query and click the header of the Randoms column. Now select the Transform tab in the control ribbon and watch out for Statistics. Open the context menu of Statistics and choose Average from the list. This immediately turns the query into a single decimal number representing the Mean value of our Randoms column. Repeat this step for the Standard Deviation query but this time select Standard Deviation from the context menu of Statistics. Again, this will turn the query into a single decimal value representing the Standard Deviation of our Randoms column. Now that we quickly calculated the Mean and Standard Deviation without a single line of code, we can now do the math to detect outliers. We want to filter outliers with a dedicated column. Jump over to the Add Column ribbon tab and click Custom Column. This immediately brings up the power query formulas editor where we can calculate the values of this new column. Name the column something like IsOutlier. Now we have to translate our knowledge of the three-sigma rule into a Power BI formula. Here is the final formula which is easy to read and understand. Number.Abs([Randoms] — Mean) > (3 * #”Standard Deviation”) Let’s break it down. First, we take each value in the column [Random] and subtract the overall Mean which is the result of our query Mean. Surround this calculation with the function Number.Abs() which returns the absolute number of the calculation. Now we verify if the result is greater three times the Standard Deviation. We do this by > (3 * #"Standard Deviation") where again Standard Deviation is the result of our Standard Deviation query. That’s it! Click OK and you’re ready to filter outliers and detect anomalies. Back in the editor, you can watch the newly created column and its values being calculated based on our formula. Let’s filter our IsOutlier column to TRUE by clicking the arrow down icon next to the column header. Working with my dataset we detected 19 outliers. As you can see from the numbers these outliers indeed represent the outer edges of our random range. Congratulations! You successfully detected outliers in your dataset. Feel free to invert the filter and work with the data that is not an outlier. This will give you statistically better results. Make it so. — Sebastian Using the snippet below you can quickly generate your own random numbers and play around with it. Learn more about the function used to generate it by following this link.
[ { "code": null, "e": 327, "s": 172, "text": "Even in the smallest of all data projects, one of the most important steps is detecting abnormal values, outliers or anomalies within your data structure." }, { "code": null, "e": 558, "s": 327, "text": "In this brief guide, I will show you the most basic way of detecting such values using no code at all. Besides the many ways to achieve this in Power BI, this is the most straight forward and UI-driven one, and still very helpful." }, { "code": null, "e": 691, "s": 558, "text": "A common method to define outliers is the “3 times the standard deviation” rule, often referred to as the three-sigma rule of thumb." }, { "code": null, "e": 735, "s": 691, "text": "Want more background? Find it on Wikipedia." }, { "code": null, "e": 934, "s": 735, "text": "Suppose we have a column with values in our dataset, and we want to detect if it contains outliers or not. Todo so we look at|value — average|, to measure how far away the value is from the average." }, { "code": null, "e": 1073, "s": 934, "text": "If this absolute value is more than 3 times the standard deviation of our values, then we can consider the value as an outlier or anomaly." }, { "code": null, "e": 1150, "s": 1073, "text": "The approach works best on data that follows a standard normal distribution." }, { "code": null, "e": 1320, "s": 1150, "text": "But even for non-normally distributed variables, the three-sigma rule tells us that at least 88.8% of cases should fall within properly calculated three-sigma intervals." }, { "code": null, "e": 1599, "s": 1320, "text": "To work along this guide take any of your own datasets or download my dataset filled with 5000 random values as per the standard normal distribution. Concretely, it is filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1." }, { "code": null, "e": 1610, "s": 1599, "text": "github.com" }, { "code": null, "e": 1708, "s": 1610, "text": "Want to know how to create such data with python? See the bonus section at the end of this guide." }, { "code": null, "e": 1802, "s": 1708, "text": "Let’s extract our data from randoms.csv file inside the repository and load it into Power BI." }, { "code": null, "e": 1836, "s": 1802, "text": "Open Power BI and click Get Data." }, { "code": null, "e": 1922, "s": 1836, "text": "Select Text/CSV, click Connect and select the previously downloaded randoms.csv file." }, { "code": null, "e": 2031, "s": 1922, "text": "Review the data and make sure that it is loaded correctly. Click Transform Data to extract it into Power BI." }, { "code": null, "e": 2220, "s": 2031, "text": "We want to have a custom column that allows us to easily filter for outliers. To identify outliers we first need to calculate the Average (mean) and the Standard Deviation of all our data." }, { "code": null, "e": 2421, "s": 2220, "text": "To do so we duplicate our initial query two times. Select the initial query, right-click it and choose Duplicate from the context menu. Repeat this step a second time so you have a total of 3 queries." }, { "code": null, "e": 2589, "s": 2421, "text": "Now we quickly rename our duplicated queries to Mean and Standard Deviation so it reflects our intent. Right-click both queries and click Rename from the context menu." }, { "code": null, "e": 2750, "s": 2589, "text": "Now that we have named our queries properly we can go ahead and do a quick calculation on our Randoms column for both the Mean and the Standard Deviation query." }, { "code": null, "e": 2967, "s": 2750, "text": "Select the Mean query and click the header of the Randoms column. Now select the Transform tab in the control ribbon and watch out for Statistics. Open the context menu of Statistics and choose Average from the list." }, { "code": null, "e": 3080, "s": 2967, "text": "This immediately turns the query into a single decimal number representing the Mean value of our Randoms column." }, { "code": null, "e": 3207, "s": 3080, "text": "Repeat this step for the Standard Deviation query but this time select Standard Deviation from the context menu of Statistics." }, { "code": null, "e": 3326, "s": 3207, "text": "Again, this will turn the query into a single decimal value representing the Standard Deviation of our Randoms column." }, { "code": null, "e": 3463, "s": 3326, "text": "Now that we quickly calculated the Mean and Standard Deviation without a single line of code, we can now do the math to detect outliers." }, { "code": null, "e": 3579, "s": 3463, "text": "We want to filter outliers with a dedicated column. Jump over to the Add Column ribbon tab and click Custom Column." }, { "code": null, "e": 3734, "s": 3579, "text": "This immediately brings up the power query formulas editor where we can calculate the values of this new column. Name the column something like IsOutlier." }, { "code": null, "e": 3886, "s": 3734, "text": "Now we have to translate our knowledge of the three-sigma rule into a Power BI formula. Here is the final formula which is easy to read and understand." }, { "code": null, "e": 3945, "s": 3886, "text": "Number.Abs([Randoms] — Mean) > (3 * #”Standard Deviation”)" }, { "code": null, "e": 4195, "s": 3945, "text": "Let’s break it down. First, we take each value in the column [Random] and subtract the overall Mean which is the result of our query Mean. Surround this calculation with the function Number.Abs() which returns the absolute number of the calculation." }, { "code": null, "e": 4392, "s": 4195, "text": "Now we verify if the result is greater three times the Standard Deviation. We do this by > (3 * #\"Standard Deviation\") where again Standard Deviation is the result of our Standard Deviation query." }, { "code": null, "e": 4470, "s": 4392, "text": "That’s it! Click OK and you’re ready to filter outliers and detect anomalies." }, { "code": null, "e": 4684, "s": 4470, "text": "Back in the editor, you can watch the newly created column and its values being calculated based on our formula. Let’s filter our IsOutlier column to TRUE by clicking the arrow down icon next to the column header." }, { "code": null, "e": 4834, "s": 4684, "text": "Working with my dataset we detected 19 outliers. As you can see from the numbers these outliers indeed represent the outer edges of our random range." }, { "code": null, "e": 5030, "s": 4834, "text": "Congratulations! You successfully detected outliers in your dataset. Feel free to invert the filter and work with the data that is not an outlier. This will give you statistically better results." }, { "code": null, "e": 5042, "s": 5030, "text": "Make it so." }, { "code": null, "e": 5054, "s": 5042, "text": "— Sebastian" } ]
MySQL query to delete all rows older than 30 days?
To delete all rows older than 30 days, you need to use the DELETE with INTERVAL. Use < now() i.e. less than operator to get all the records before the current date. Let us first create a table − mysql> create table DemoTable -> ( -> UserMessage text, -> UserMessageSentDate date -> ); Query OK, 0 rows affected (0.59 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('Hi','2019-06-01'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Hello','2019-07-02'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Awesome','2019-05-04'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Good','2019-01-10'); Query OK, 1 row affected (0.35 sec) Display all records from the table using select statement − mysql> select *from DemoTable; +-------------+---------------------+ | UserMessage | UserMessageSentDate | +-------------+---------------------+ | Hi | 2019-06-01 | | Hello | 2019-07-02 | | Awesome | 2019-05-04 | | Good | 2019-01-10 | +-------------+---------------------+ 4 rows in set (0.00 sec) Following is the query to delete all rows older than 30 days − mysql> delete from DemoTable where UserMessageSentDate < now() - interval 30 DAY; Query OK, 3 rows affected (0.11 sec) Let us check table records once again − mysql> select *from DemoTable; +-------------+---------------------+ | UserMessage | UserMessageSentDate | +-------------+---------------------+ | Hello | 2019-07-02 | +-------------+---------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1227, "s": 1062, "text": "To delete all rows older than 30 days, you need to use the DELETE with INTERVAL. Use < now() i.e. less than operator to get all the records before the current date." }, { "code": null, "e": 1257, "s": 1227, "text": "Let us first create a table −" }, { "code": null, "e": 1396, "s": 1257, "text": "mysql> create table DemoTable\n -> (\n -> UserMessage text,\n -> UserMessageSentDate date\n -> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1452, "s": 1396, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1833, "s": 1452, "text": "mysql> insert into DemoTable values('Hi','2019-06-01');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DemoTable values('Hello','2019-07-02');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values('Awesome','2019-05-04');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DemoTable values('Good','2019-01-10');\nQuery OK, 1 row affected (0.35 sec)" }, { "code": null, "e": 1893, "s": 1833, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1924, "s": 1893, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2253, "s": 1924, "text": "+-------------+---------------------+\n| UserMessage | UserMessageSentDate |\n+-------------+---------------------+\n| Hi | 2019-06-01 |\n| Hello | 2019-07-02 |\n| Awesome | 2019-05-04 |\n| Good | 2019-01-10 |\n+-------------+---------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2316, "s": 2253, "text": "Following is the query to delete all rows older than 30 days −" }, { "code": null, "e": 2435, "s": 2316, "text": "mysql> delete from DemoTable where UserMessageSentDate < now() - interval 30 DAY;\nQuery OK, 3 rows affected (0.11 sec)" }, { "code": null, "e": 2475, "s": 2435, "text": "Let us check table records once again −" }, { "code": null, "e": 2506, "s": 2475, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2720, "s": 2506, "text": "+-------------+---------------------+\n| UserMessage | UserMessageSentDate |\n+-------------+---------------------+\n| Hello | 2019-07-02 |\n+-------------+---------------------+\n1 row in set (0.00 sec)" } ]
How to Add and Subtract Days to and from Date in R ? - GeeksforGeeks
21 Apr, 2021 R Programming Language provides a variety of ways for dealing with both date and date/time data. The built-in framework as.Date function is responsible for the handling of dates alone, the library chron in R handles both dates and times, without any support for time zones; whereas the POSIXct and POSIXlt classes provide the support for handling datetime objects as well as timezones. Easy conversion of date-time objects can be performed to other date-related objects. Method 1: Using as.Date() method The date objects are stored as the number of days calculated starting January 1, 1970, where negative numbers are used to refer to earlier dates. The Date objects support basic arithmetic directly, where in the integers are added or subtracted directly from the Dates. N number of days are added or subtracted directly and the standard date format is returned as an output. The Date object can also specify different formats to contain the dates. The as.Date() method takes as input a string date object and converts it to a Date object. as.Date(character date object) The following R snippet illustrates the usage of Date objects : R # declaring a date objectdate <- as.Date("2020/12/11")print ("Original Date")print (date) # subtracting 3 days from date # objectn = 3 # subtracting days new_sub_date <- date - nprint ("Subtracted Date")print (new_sub_date) # adding daysnew_add_date <- date + nprint ("Added Date")print (new_add_date) Output: [1] "Original Date" [1] "2020-12-11" [1] "Subtracted Date" [1] "2020-12-08" [1] "Added Date" [1] "2020-12-14" Method 2: lubridate package in R Lubridate is an R package to simulate working easily with dates and time objects. It gives a wide range of functions to perform modifications on the day objects. ymd() method in R is used to extract the Date portion from the date-time object, which is converted into standard years, months, and days formats. days() method accepts an integer as an argument and performs arithmetic on the Date objects using mathematical operators, directly. Syntax: ymd(date) Arguments : date – String date object Returns : Date object in ymd format Code: R # using required librarieslibrary(lubridate) # declaring a date objectdate <- "2009-10-01"print ("Original Date")print (date) # subtracting 3 days from date# objectn = 3 # subtracting days new_sub_date <- date - nprint ("Subtracted Date")print (new_sub_date) # adding daysnew_add_date <- date + nprint ("Added Date")print (new_add_date) Output: [1] "Original Date" [1] "2009-10-01" [1] "Subtracted Date" [1] "2009-09-25" [1] "Added Date" [1] "2009-10-07" The same arithmetic can also be performed using the days() function in R, which takes as argument the integer value corresponding to the number of days : R # using required librarieslibrary(lubridate) # declaring a date objectdate <- "2009-10-01"print ("Original Date")print (date) # subtracting daysn = 6sub_date <- ymd(date) - days(6)print ("Subtracted Date")print (sub_date) # adding daysnew_add_date <- ymd(date) + days(0)print ("Added Date")print (new_add_date) Output: [1] "Original Date" [1] "2009-10-01" [1] "Subtracted Date" [1] "2009-09-25" [1] "Added Date" [1] "2009-10-01" 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 Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Time Series Analysis in R R - if statement
[ { "code": null, "e": 25242, "s": 25214, "text": "\n21 Apr, 2021" }, { "code": null, "e": 25713, "s": 25242, "text": "R Programming Language provides a variety of ways for dealing with both date and date/time data. The built-in framework as.Date function is responsible for the handling of dates alone, the library chron in R handles both dates and times, without any support for time zones; whereas the POSIXct and POSIXlt classes provide the support for handling datetime objects as well as timezones. Easy conversion of date-time objects can be performed to other date-related objects." }, { "code": null, "e": 25746, "s": 25713, "text": "Method 1: Using as.Date() method" }, { "code": null, "e": 26285, "s": 25746, "text": "The date objects are stored as the number of days calculated starting January 1, 1970, where negative numbers are used to refer to earlier dates. The Date objects support basic arithmetic directly, where in the integers are added or subtracted directly from the Dates. N number of days are added or subtracted directly and the standard date format is returned as an output. The Date object can also specify different formats to contain the dates. The as.Date() method takes as input a string date object and converts it to a Date object. " }, { "code": null, "e": 26316, "s": 26285, "text": "as.Date(character date object)" }, { "code": null, "e": 26381, "s": 26316, "text": "The following R snippet illustrates the usage of Date objects : " }, { "code": null, "e": 26383, "s": 26381, "text": "R" }, { "code": "# declaring a date objectdate <- as.Date(\"2020/12/11\")print (\"Original Date\")print (date) # subtracting 3 days from date # objectn = 3 # subtracting days new_sub_date <- date - nprint (\"Subtracted Date\")print (new_sub_date) # adding daysnew_add_date <- date + nprint (\"Added Date\")print (new_add_date)", "e": 26688, "s": 26383, "text": null }, { "code": null, "e": 26696, "s": 26688, "text": "Output:" }, { "code": null, "e": 26806, "s": 26696, "text": "[1] \"Original Date\"\n[1] \"2020-12-11\"\n[1] \"Subtracted Date\"\n[1] \"2020-12-08\"\n[1] \"Added Date\"\n[1] \"2020-12-14\"" }, { "code": null, "e": 26839, "s": 26806, "text": "Method 2: lubridate package in R" }, { "code": null, "e": 27281, "s": 26839, "text": "Lubridate is an R package to simulate working easily with dates and time objects. It gives a wide range of functions to perform modifications on the day objects. ymd() method in R is used to extract the Date portion from the date-time object, which is converted into standard years, months, and days formats. days() method accepts an integer as an argument and performs arithmetic on the Date objects using mathematical operators, directly. " }, { "code": null, "e": 27299, "s": 27281, "text": "Syntax: ymd(date)" }, { "code": null, "e": 27337, "s": 27299, "text": "Arguments : date – String date object" }, { "code": null, "e": 27374, "s": 27337, "text": "Returns : Date object in ymd format " }, { "code": null, "e": 27380, "s": 27374, "text": "Code:" }, { "code": null, "e": 27382, "s": 27380, "text": "R" }, { "code": "# using required librarieslibrary(lubridate) # declaring a date objectdate <- \"2009-10-01\"print (\"Original Date\")print (date) # subtracting 3 days from date# objectn = 3 # subtracting days new_sub_date <- date - nprint (\"Subtracted Date\")print (new_sub_date) # adding daysnew_add_date <- date + nprint (\"Added Date\")print (new_add_date)", "e": 27723, "s": 27382, "text": null }, { "code": null, "e": 27731, "s": 27723, "text": "Output:" }, { "code": null, "e": 27846, "s": 27731, "text": "[1] \"Original Date\" \n[1] \"2009-10-01\" \n[1] \"Subtracted Date\" \n[1] \"2009-09-25\" \n[1] \"Added Date\" \n[1] \"2009-10-07\"" }, { "code": null, "e": 28001, "s": 27846, "text": "The same arithmetic can also be performed using the days() function in R, which takes as argument the integer value corresponding to the number of days : " }, { "code": null, "e": 28003, "s": 28001, "text": "R" }, { "code": "# using required librarieslibrary(lubridate) # declaring a date objectdate <- \"2009-10-01\"print (\"Original Date\")print (date) # subtracting daysn = 6sub_date <- ymd(date) - days(6)print (\"Subtracted Date\")print (sub_date) # adding daysnew_add_date <- ymd(date) + days(0)print (\"Added Date\")print (new_add_date)", "e": 28317, "s": 28003, "text": null }, { "code": null, "e": 28325, "s": 28317, "text": "Output:" }, { "code": null, "e": 28436, "s": 28325, "text": "[1] \"Original Date\"\n[1] \"2009-10-01\"\n[1] \"Subtracted Date\"\n[1] \"2009-09-25\"\n[1] \"Added Date\" \n[1] \"2009-10-01\"" }, { "code": null, "e": 28443, "s": 28436, "text": "Picked" }, { "code": null, "e": 28454, "s": 28443, "text": "R-DateTime" }, { "code": null, "e": 28465, "s": 28454, "text": "R Language" }, { "code": null, "e": 28563, "s": 28465, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28615, "s": 28563, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28653, "s": 28615, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28688, "s": 28653, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28746, "s": 28688, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28795, "s": 28746, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28832, "s": 28795, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28882, "s": 28832, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28925, "s": 28882, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28951, "s": 28925, "text": "Time Series Analysis in R" } ]
Data Mining Graphs and Networks - GeeksforGeeks
29 Dec, 2021 Data mining is the process of collecting and processing data from a heap of unprocessed data. When the patterns are established, various relationships between the datasets can be identified and they can be presented in a summarized format which helps in statistical analysis in various industries. Among the other data structures, the graph is widely used in modeling advanced structures and patterns. In data mining, the graph is used to find subgraph patterns for discrimination, classification, clustering of data, etc. The graph is used in network analysis. By linking the various nodes, graphs form network-like communications, web and computer networks, social networks, etc. In multi-relational data mining, graphs or networks is used because of the varied interconnected relationship between the datasets in a relational database. Graph mining is a process in which the mining techniques are used in finding a pattern or relationship in the given real-world collection of graphs. By mining the graph, frequent substructures and relationships can be identified which helps in clustering the graph sets, finding a relationship between graph sets, or discriminating or characterizing graphs. Predicting these patterning trends can help in building models for the enhancement of any application that is used in real-time. To implement the process of graph mining, one must learn to mine frequent subgraphs. Let us consider a graph h with an edge set E(h) and a vertex set V(h). Let us consider the existence of subgraph isomorphism from h to h’ in such a way that h is a subgraph of h’. A label function is a function that plots either the edges or vertices to a label. Let us consider a labeled graph dataset, Let us consider s(h) as the support which means the percentage of graphs in F where h is a subgraph. A frequent graph has support that will be no less than the minimum support threshold. Let us denote it as min_support. Steps in finding frequent subgraphs: There are two steps in finding frequent subgraphs. The first step is to create frequent substructure candidates. The second step is to find the support of each and every candidate. We must optimize and enhance the first step because the second step is an NP-completed set where the computational complexity is accurate and high. There are two methods for frequent substructure mining. The Apriori-based approach: The approach to find the frequent graphs begin from the graph with a small size. The approach advances in a bottom-up way by creating candidates with extra vertex or edge. This algorithm is called an Apriori Graph. Let us consider Qk as the frequent sub-structure set with a size of k. This approach acquires a level-wise mining technique. Before the Apriori Graph technique, the generation of candidates must be done. This is done by combining two same but slightly varied frequent subgraphs. After the formation of new substructures, the frequency of the graph is checked. Out of that, the graphs found frequently are used to create the next candidate. This step to generate frequent substructure candidates is a complex step. But, when it comes to generating candidates in itemset, it is easy and effortless. Let’s consider an example of having two itemsets of size three such that and So, the itemset derived using join would be pqrs. But when it comes to substructures, there is more than one method to join two substructures. Algorithm: This approach is based on frequent substructure mining. Input: F= a graph data set. min_support= minimum support threshold Output: Q1,Q2,Q3,....QK, a frequent substructure set graphs with the size range from 1 to k. Q1 <- all the frequent 1 subgraphs in F; k <- 2; while Qk-1 ≠ ∅ do Qk <- ∅; Gk <- candidate_generation(Qk-1); foreach candidate l ∈ Gk do l.count <- 0; foreach Fi ∈ F do if isomerism_subgraph(l,Fi) then l.count <- l.count+1; end end if l.count ≥ min_support(F) ∧ l∉Qk then Qk = Qk U l; end end k <- k+1; end It is an iterative method in which the first candidate generation takes place followed by the support computation. The subgraphs are generated using subgraph isomorphism. Thus frequent subgraphs are generated by efficiently using this approach which helps in FSM. Apriori approach uses BFS(Breadth-First Search) due to the iterative level-wise generation of candidates. This is necessary because if you want to mine the k+1 graph, you should have already mined till k subgraphs. The Pattern- growth approach: This pattern-growth approach can use both BFS and DFS(Depth First Search). DFS is preferred for this approach due to its less memory consumption nature. Let us consider a graph h. A new graph can be formed by adding an edge e. The edge can introduce a vertex but it is not a need. If it introduces a vertex, it can be done in two ways, forward and backward. The Pattern-growth graph is easy but it is not that efficient. Because there is a possibility of creating a similar graph that is already created which leads to computation inefficiency. The duplicate graphs generated can be removed but it increases the time and work. To avoid the creation of duplicate graphs, the frequent graphs should be introduced very carefully and conservatively which calls the need for other algorithms. Algorithm: The below algorithm is a pattern-growth-based frequent substructure mining with a simplistic approach. If you need to search without duplicating, you must go with a different algorithm with gSpan. Input: q= a frequent graph F= a graph data set. min_support= minimum support threshold Output: P = the frequent graph set P <- ∅; Call patterngrow_graph(q, F, min_support, P); procedure patterngrow_graph(q, F, min_support, P) if q ∈ P then return; else insert q into P; scan F once, find all the edges e such that q can be extended to q -> e; for each frequent q -> e do PatternGrowthGraph(q -> e, D, min_support, P); return; An edge e is used to extend a new graph from the old one q. The newly extend graph is denoted as The extension can either be backward or forward. According to the request of the user, the constraints described changes in the mining process. But, if we generalize and categorize them into specific constraints, the mining process would be handled easily by pushing them into the given frameworks. constraint-pushing strategy is used in pattern growth mining tasks. Let’s see some important constraint categories. Subgraph containment constraint: When a user requests a pattern with specified subgraphs, this constraint is used. This constraint is also called a set containment constraint. The given set of subgraphs is taken as a query and then mining is done based on the chosen data by extending the patterns from the subgraph sets. This technique can be used to mine when the user requests patterns with specific sets of edges or vertices. Value- sum constraint: Here, the constraint is the sum of weights on the edges. There are two ranges high and low. The two constraints are designated as and The first condition is called monotonic constraint because once the condition is satisfied, still the extension can take place by adding edges until the next condition is satisfied. But the latter condition is called anti-monotonic constraint because once the condition becomes satisfied, further no more extension can be made. By this method, the constraint-pushing technique will work out well. Geometric Constraint: In this constraint, the angle between pair of edges within a given range that is connected is taken. Let us consider a graph h, such that where E1, E2 are the edges connected at the vertex V and connected to the other two vertices at the other two ends V1, V2. Ah is called the anti-monotonic constraint because if any one of the angles formed by combining two edges didn’t satisfy, it does not move to the next level and it will never satisfy Ah. It can be pushed to the edge extension process and eliminate any extension that doesn’t satisfy Ah. In the concept of network analysis, the relationship between the units is called links in a graph. From the data mining outlook, this is called link mining or link analysis. The network is a diversional dataset with a multi-relational concept in form of a graph. The graph is very large with nodes as objects, edges as links which in turn denote the relationship between the nodes or objects. Telephone networking systems, WWW( World Wide Web) are very good examples. It also helps in filtering the datasets and providing customer-preferred services. Every network consists of numerous nodes. The datasets are widely enormous. Thus by studying and mining useful information from a wide group of datasets would help in solving problems and effective transmission of data. There are some conventional methods of machine learning in which taking homogeneous objects from one relationship is taken. But in networks, this is not applicable due to a large number of nodes and its multi-relational, heterogeneous nature. Thus the link mining has appeared as a new field after many types of research. Link mining is the convergence of multiple research held in graph mining, networks, hypertexts, logic programming, link analysis, predictive analysis, and modeling. Links are nothing but the relationship between nodes in a network. With the help of links, the mining process can be held efficiently. This calls for the various functions to be done. Link-based object classification: In link mining, only attributes are not enough. Here the links and the traits of the linked nodes are also necessary. One best example is Web-based classification. In web-based classification, the system predicts the categorization of a webpage based on the presence of that specified word which means the searched word occurs on that page. Anchor text is which the person clicks the hyperlink that opens while searching. These two things act as attributes in web-based classification. The attributes can be anything that relates to the link and network pages. Link type prediction: According to the resources of the object involved, the system predicts the motive of that link. In organizations, it helps in suggesting interactive communication sessions between employees if needed. In the online retail market, it helps predict what a customer prefers to buy which can increase sales and recommendations. Object type prediction: Here the prediction is based on the type of the object involved, its attributes and properties, links and traits of the object linked to it. For example in the restaurant domain, a similar method is done to predict if a customer prefers ordering food or directly visiting the restaurant. It also helps in predicting the method of communication a customer prefers whether by phone or mail. Link Cardinality estimation: In this task, there are two types of estimation. The first one is predicting the number of links linked to an object. For example, the percentage of the authority of a web page can be calculated by finding the number of links linked to it which is called in-links. Web pages that act as a hub which means a set of web pages denotes other links which come under the same topic can be identified using out-links. For example, when a pandemic strikes, finding the links of the affected patient can lead us to the other patients which helps in the control of the transmission. The second one is done by predicting the number of objects outreaching along a route from an object. This method is crucial in estimating the object number returned as output by a query. Predicting link existence: In link type prediction, the type of the link is predicted. But, here the system predicts whether a link exists between two objects. For an instance, this task is used to predict if a link exists between two web pages. Object Reconciliation: In this method, the function is to predict if any two objects are the same on the basis of their attributes or traits or links. This method is also called identity uncertainty or record linkage. This task has it’s the same procedure in the matching of citation, extraction of details, getting rid of duplicates, consolidating objects. For an instance, this task is to help if one website is reflecting the other website like a mirror to each other. Statistical compared to logical dependencies: The logical relationship between objects is denoted by graph-link structures. The statistical relationship is denoted by probabilistic dependencies. The rational handling of these two dependencies is difficult in data mining which is multi-relational. One must be careful enough to find the logical dependencies between objects along with probabilistic relationships between attributes. These dependencies take a large amount of space which complicates the mathematical model deployed. Collective classification and consolidation: Let us consider a training model based on objects that are class-labeled. In conventional classification, classification is only done based on the attribute. If there is a chance that classification occurs after giving training with unlabeled objects, the model becomes incapable of classification due to the complications of the correlations of the objects. This calls for the need for another supplementary iterative step which consolidates the labels of objects based on the labels of objects linked to it. Here collective classification takes place. Constructive use of labeled and unlabeled data: One emerging technique is to merge both labeled and unlabeled data. Unlabeled data assist in identifying the distribution of attributes. The links that are present in unlabeled data help us in extracting the linked object’s attributes. The links that are present between unlabeled and labeled data help in establishing dependencies which increases the efficiency in interference. Open compared to closed-world assumptions: In the conventional method, it is assumed that we know all the possible objects/ entities present in the domain which is closed-world assumptions. But, closed world assumption is impractical in the application of reality. This calls for the introduction of specific language for probability distributions with respect to relational objects that contains a varied set of objects. Network analysis includes the finding of objects which are in groups that share similar attributes. This process is known as community mining. In the web page linkage, the introduction of community where a group of web pages is made which follow a common theme. Many community mining algorithms decide that there is only one network and it tries to establish a homogeneous relationship. But in the real world web pages, there are multiple networks with heterogeneous relationships. This proves the need for multi-relational community mining. surinderdawra388 datamining Picked Data Mining Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Complex Data Types in Data Mining Market Basket Analysis in Data Mining Backpropagation in Data Mining Clustering High-Dimensional Data in Data Mining Feature extraction in Data Mining CLIQUE Algorithm in Data Mining Data Mining - Time-Series, Symbolic and Biological Sequences Data Principal Components Analysis in Data Mining Generalized Sequential Pattern (GSP) Mining in Data Mining How Neural Networks Can Be Used For Data Mining?
[ { "code": null, "e": 24506, "s": 24478, "text": "\n29 Dec, 2021" }, { "code": null, "e": 25346, "s": 24506, "text": "Data mining is the process of collecting and processing data from a heap of unprocessed data. When the patterns are established, various relationships between the datasets can be identified and they can be presented in a summarized format which helps in statistical analysis in various industries. Among the other data structures, the graph is widely used in modeling advanced structures and patterns. In data mining, the graph is used to find subgraph patterns for discrimination, classification, clustering of data, etc. The graph is used in network analysis. By linking the various nodes, graphs form network-like communications, web and computer networks, social networks, etc. In multi-relational data mining, graphs or networks is used because of the varied interconnected relationship between the datasets in a relational database. " }, { "code": null, "e": 25918, "s": 25346, "text": "Graph mining is a process in which the mining techniques are used in finding a pattern or relationship in the given real-world collection of graphs. By mining the graph, frequent substructures and relationships can be identified which helps in clustering the graph sets, finding a relationship between graph sets, or discriminating or characterizing graphs. Predicting these patterning trends can help in building models for the enhancement of any application that is used in real-time. To implement the process of graph mining, one must learn to mine frequent subgraphs." }, { "code": null, "e": 26442, "s": 25918, "text": "Let us consider a graph h with an edge set E(h) and a vertex set V(h). Let us consider the existence of subgraph isomorphism from h to h’ in such a way that h is a subgraph of h’. A label function is a function that plots either the edges or vertices to a label. Let us consider a labeled graph dataset, Let us consider s(h) as the support which means the percentage of graphs in F where h is a subgraph. A frequent graph has support that will be no less than the minimum support threshold. Let us denote it as min_support." }, { "code": null, "e": 26479, "s": 26442, "text": "Steps in finding frequent subgraphs:" }, { "code": null, "e": 26531, "s": 26479, "text": "There are two steps in finding frequent subgraphs. " }, { "code": null, "e": 26593, "s": 26531, "text": "The first step is to create frequent substructure candidates." }, { "code": null, "e": 26809, "s": 26593, "text": "The second step is to find the support of each and every candidate. We must optimize and enhance the first step because the second step is an NP-completed set where the computational complexity is accurate and high." }, { "code": null, "e": 26865, "s": 26809, "text": "There are two methods for frequent substructure mining." }, { "code": null, "e": 27927, "s": 26865, "text": "The Apriori-based approach: The approach to find the frequent graphs begin from the graph with a small size. The approach advances in a bottom-up way by creating candidates with extra vertex or edge. This algorithm is called an Apriori Graph. Let us consider Qk as the frequent sub-structure set with a size of k. This approach acquires a level-wise mining technique. Before the Apriori Graph technique, the generation of candidates must be done. This is done by combining two same but slightly varied frequent subgraphs. After the formation of new substructures, the frequency of the graph is checked. Out of that, the graphs found frequently are used to create the next candidate. This step to generate frequent substructure candidates is a complex step. But, when it comes to generating candidates in itemset, it is easy and effortless. Let’s consider an example of having two itemsets of size three such that and So, the itemset derived using join would be pqrs. But when it comes to substructures, there is more than one method to join two substructures." }, { "code": null, "e": 27939, "s": 27927, "text": "Algorithm: " }, { "code": null, "e": 27995, "s": 27939, "text": "This approach is based on frequent substructure mining." }, { "code": null, "e": 28498, "s": 27995, "text": "Input:\nF= a graph data set.\nmin_support= minimum support threshold\nOutput:\nQ1,Q2,Q3,....QK,\n a frequent substructure set graphs with the size range from 1 to k.\nQ1 <- all the frequent 1 subgraphs in F;\nk <- 2;\nwhile Qk-1 ≠ ∅ do\n Qk <- ∅;\n Gk <- candidate_generation(Qk-1);\n foreach candidate l ∈ Gk do\n l.count <- 0;\n foreach Fi ∈ F do\n if isomerism_subgraph(l,Fi) then\n l.count <- l.count+1;\n end\n end\n if l.count ≥ min_support(F) ∧ l∉Qk then\n Qk = Qk U l;\n end\n end\n k <- k+1;\nend" }, { "code": null, "e": 28980, "s": 28498, "text": "It is an iterative method in which the first candidate generation takes place followed by the support computation. The subgraphs are generated using subgraph isomorphism. Thus frequent subgraphs are generated by efficiently using this approach which helps in FSM. Apriori approach uses BFS(Breadth-First Search) due to the iterative level-wise generation of candidates. This is necessary because if you want to mine the k+1 graph, you should have already mined till k subgraphs. " }, { "code": null, "e": 29799, "s": 28980, "text": "The Pattern- growth approach: This pattern-growth approach can use both BFS and DFS(Depth First Search). DFS is preferred for this approach due to its less memory consumption nature. Let us consider a graph h. A new graph can be formed by adding an edge e. The edge can introduce a vertex but it is not a need. If it introduces a vertex, it can be done in two ways, forward and backward. The Pattern-growth graph is easy but it is not that efficient. Because there is a possibility of creating a similar graph that is already created which leads to computation inefficiency. The duplicate graphs generated can be removed but it increases the time and work. To avoid the creation of duplicate graphs, the frequent graphs should be introduced very carefully and conservatively which calls the need for other algorithms. " }, { "code": null, "e": 29810, "s": 29799, "text": "Algorithm:" }, { "code": null, "e": 30007, "s": 29810, "text": "The below algorithm is a pattern-growth-based frequent substructure mining with a simplistic approach. If you need to search without duplicating, you must go with a different algorithm with gSpan." }, { "code": null, "e": 30440, "s": 30007, "text": "Input:\nq= a frequent graph\nF= a graph data set.\nmin_support= minimum support threshold\nOutput: \nP = the frequent graph set\nP <- ∅;\nCall patterngrow_graph(q, F, min_support, P);\nprocedure patterngrow_graph(q, F, min_support, P)\n if q ∈ P then return;\n else insert q into P;\n scan F once, find all the edges e such that q can be extended to q -> e;\n for each frequent q -> e do\n PatternGrowthGraph(q -> e, D, min_support, P);\n return;" }, { "code": null, "e": 30588, "s": 30440, "text": "An edge e is used to extend a new graph from the old one q. The newly extend graph is denoted as The extension can either be backward or forward. " }, { "code": null, "e": 30955, "s": 30588, "text": "According to the request of the user, the constraints described changes in the mining process. But, if we generalize and categorize them into specific constraints, the mining process would be handled easily by pushing them into the given frameworks. constraint-pushing strategy is used in pattern growth mining tasks. Let’s see some important constraint categories." }, { "code": null, "e": 31385, "s": 30955, "text": "Subgraph containment constraint: When a user requests a pattern with specified subgraphs, this constraint is used. This constraint is also called a set containment constraint. The given set of subgraphs is taken as a query and then mining is done based on the chosen data by extending the patterns from the subgraph sets. This technique can be used to mine when the user requests patterns with specific sets of edges or vertices." }, { "code": null, "e": 31940, "s": 31385, "text": "Value- sum constraint: Here, the constraint is the sum of weights on the edges. There are two ranges high and low. The two constraints are designated as and The first condition is called monotonic constraint because once the condition is satisfied, still the extension can take place by adding edges until the next condition is satisfied. But the latter condition is called anti-monotonic constraint because once the condition becomes satisfied, further no more extension can be made. By this method, the constraint-pushing technique will work out well." }, { "code": null, "e": 32510, "s": 31940, "text": "Geometric Constraint: In this constraint, the angle between pair of edges within a given range that is connected is taken. Let us consider a graph h, such that where E1, E2 are the edges connected at the vertex V and connected to the other two vertices at the other two ends V1, V2. Ah is called the anti-monotonic constraint because if any one of the angles formed by combining two edges didn’t satisfy, it does not move to the next level and it will never satisfy Ah. It can be pushed to the edge extension process and eliminate any extension that doesn’t satisfy Ah." }, { "code": null, "e": 33281, "s": 32510, "text": "In the concept of network analysis, the relationship between the units is called links in a graph. From the data mining outlook, this is called link mining or link analysis. The network is a diversional dataset with a multi-relational concept in form of a graph. The graph is very large with nodes as objects, edges as links which in turn denote the relationship between the nodes or objects. Telephone networking systems, WWW( World Wide Web) are very good examples. It also helps in filtering the datasets and providing customer-preferred services. Every network consists of numerous nodes. The datasets are widely enormous. Thus by studying and mining useful information from a wide group of datasets would help in solving problems and effective transmission of data." }, { "code": null, "e": 33953, "s": 33281, "text": "There are some conventional methods of machine learning in which taking homogeneous objects from one relationship is taken. But in networks, this is not applicable due to a large number of nodes and its multi-relational, heterogeneous nature. Thus the link mining has appeared as a new field after many types of research. Link mining is the convergence of multiple research held in graph mining, networks, hypertexts, logic programming, link analysis, predictive analysis, and modeling. Links are nothing but the relationship between nodes in a network. With the help of links, the mining process can be held efficiently. This calls for the various functions to be done. " }, { "code": null, "e": 34548, "s": 33953, "text": "Link-based object classification: In link mining, only attributes are not enough. Here the links and the traits of the linked nodes are also necessary. One best example is Web-based classification. In web-based classification, the system predicts the categorization of a webpage based on the presence of that specified word which means the searched word occurs on that page. Anchor text is which the person clicks the hyperlink that opens while searching. These two things act as attributes in web-based classification. The attributes can be anything that relates to the link and network pages." }, { "code": null, "e": 34894, "s": 34548, "text": "Link type prediction: According to the resources of the object involved, the system predicts the motive of that link. In organizations, it helps in suggesting interactive communication sessions between employees if needed. In the online retail market, it helps predict what a customer prefers to buy which can increase sales and recommendations." }, { "code": null, "e": 35307, "s": 34894, "text": "Object type prediction: Here the prediction is based on the type of the object involved, its attributes and properties, links and traits of the object linked to it. For example in the restaurant domain, a similar method is done to predict if a customer prefers ordering food or directly visiting the restaurant. It also helps in predicting the method of communication a customer prefers whether by phone or mail." }, { "code": null, "e": 36096, "s": 35307, "text": "Link Cardinality estimation: In this task, there are two types of estimation. The first one is predicting the number of links linked to an object. For example, the percentage of the authority of a web page can be calculated by finding the number of links linked to it which is called in-links. Web pages that act as a hub which means a set of web pages denotes other links which come under the same topic can be identified using out-links. For example, when a pandemic strikes, finding the links of the affected patient can lead us to the other patients which helps in the control of the transmission. The second one is done by predicting the number of objects outreaching along a route from an object. This method is crucial in estimating the object number returned as output by a query." }, { "code": null, "e": 36342, "s": 36096, "text": "Predicting link existence: In link type prediction, the type of the link is predicted. But, here the system predicts whether a link exists between two objects. For an instance, this task is used to predict if a link exists between two web pages." }, { "code": null, "e": 36814, "s": 36342, "text": "Object Reconciliation: In this method, the function is to predict if any two objects are the same on the basis of their attributes or traits or links. This method is also called identity uncertainty or record linkage. This task has it’s the same procedure in the matching of citation, extraction of details, getting rid of duplicates, consolidating objects. For an instance, this task is to help if one website is reflecting the other website like a mirror to each other." }, { "code": null, "e": 37346, "s": 36814, "text": "Statistical compared to logical dependencies: The logical relationship between objects is denoted by graph-link structures. The statistical relationship is denoted by probabilistic dependencies. The rational handling of these two dependencies is difficult in data mining which is multi-relational. One must be careful enough to find the logical dependencies between objects along with probabilistic relationships between attributes. These dependencies take a large amount of space which complicates the mathematical model deployed." }, { "code": null, "e": 37945, "s": 37346, "text": "Collective classification and consolidation: Let us consider a training model based on objects that are class-labeled. In conventional classification, classification is only done based on the attribute. If there is a chance that classification occurs after giving training with unlabeled objects, the model becomes incapable of classification due to the complications of the correlations of the objects. This calls for the need for another supplementary iterative step which consolidates the labels of objects based on the labels of objects linked to it. Here collective classification takes place." }, { "code": null, "e": 38373, "s": 37945, "text": "Constructive use of labeled and unlabeled data: One emerging technique is to merge both labeled and unlabeled data. Unlabeled data assist in identifying the distribution of attributes. The links that are present in unlabeled data help us in extracting the linked object’s attributes. The links that are present between unlabeled and labeled data help in establishing dependencies which increases the efficiency in interference." }, { "code": null, "e": 38795, "s": 38373, "text": "Open compared to closed-world assumptions: In the conventional method, it is assumed that we know all the possible objects/ entities present in the domain which is closed-world assumptions. But, closed world assumption is impractical in the application of reality. This calls for the introduction of specific language for probability distributions with respect to relational objects that contains a varied set of objects." }, { "code": null, "e": 39337, "s": 38795, "text": "Network analysis includes the finding of objects which are in groups that share similar attributes. This process is known as community mining. In the web page linkage, the introduction of community where a group of web pages is made which follow a common theme. Many community mining algorithms decide that there is only one network and it tries to establish a homogeneous relationship. But in the real world web pages, there are multiple networks with heterogeneous relationships. This proves the need for multi-relational community mining." }, { "code": null, "e": 39354, "s": 39337, "text": "surinderdawra388" }, { "code": null, "e": 39365, "s": 39354, "text": "datamining" }, { "code": null, "e": 39372, "s": 39365, "text": "Picked" }, { "code": null, "e": 39384, "s": 39372, "text": "Data Mining" }, { "code": null, "e": 39482, "s": 39384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39491, "s": 39482, "text": "Comments" }, { "code": null, "e": 39504, "s": 39491, "text": "Old Comments" }, { "code": null, "e": 39538, "s": 39504, "text": "Complex Data Types in Data Mining" }, { "code": null, "e": 39576, "s": 39538, "text": "Market Basket Analysis in Data Mining" }, { "code": null, "e": 39607, "s": 39576, "text": "Backpropagation in Data Mining" }, { "code": null, "e": 39655, "s": 39607, "text": "Clustering High-Dimensional Data in Data Mining" }, { "code": null, "e": 39689, "s": 39655, "text": "Feature extraction in Data Mining" }, { "code": null, "e": 39721, "s": 39689, "text": "CLIQUE Algorithm in Data Mining" }, { "code": null, "e": 39787, "s": 39721, "text": "Data Mining - Time-Series, Symbolic and Biological Sequences Data" }, { "code": null, "e": 39832, "s": 39787, "text": "Principal Components Analysis in Data Mining" }, { "code": null, "e": 39891, "s": 39832, "text": "Generalized Sequential Pattern (GSP) Mining in Data Mining" } ]
An implementation guide to Word2Vec using NumPy and Google Sheets | by Derek Chia | Towards Data Science
This article is an implementation guide to Word2Vec using NumPy and Google Sheets. If you you have trouble reading this, consider subscribing to Medium Membership here! Word2Vec is touted as one of the biggest, most recent breakthrough in the field of Natural Language Processing (NLP). The concept is simple, elegant and (relatively) easy to grasp. A quick Google search returns multiple results on how to use them with standard libraries such as Gensim and TensorFlow. Also, for the curious minds, check out the original implementation using C by Tomas Mikolov. The original paper can be found here too. The main focus on this article is to present Word2Vec in detail. For that, I implemented Word2Vec on Python using NumPy (with much help from other tutorials) and also prepared a Google Sheet to showcase the calculations. Here are the links to the code and Google Sheet. The objective of Word2Vec is to generate vector representations of words that carry semantic meanings for further NLP tasks. Each word vector is typically several hundred dimensions and each unique word in the corpus is assigned a vector in the space. For example, the word “happy” can be represented as a vector of 4 dimensions [0.24, 0.45, 0.11, 0.49] and “sad” has a vector of [0.88, 0.78, 0.45, 0.91]. The transformation from words to vectors is also known as word embedding. The reason for this transformation is so that machine learning algorithm can perform linear algebra operations on numbers (in vectors) instead of words. To implement Word2Vec, there are two flavors to choose from — Continuous Bag-Of-Words (CBOW) or continuous Skip-gram (SG). In short, CBOW attempts to guess the output (target word) from its neighbouring words (context words) whereas continuous Skip-Gram guesses the context words from a target word. Effectively, Word2Vec is based on distributional hypothesis where the context for each word is in its nearby words. Hence, by looking at its neighbouring words, we can attempt to predict the target word. According to Mikolov (quoted in this article), here is the difference between Skip-gram and CBOW: Skip-gram: works well with small amount of the training data, represents well even rare words or phrases CBOW: several times faster to train than the skip-gram, slightly better accuracy for the frequent words To elaborate further, since Skip-gram learns to predict the context words from a given word, in case where two words (one appearing infrequently and the other more frequently) are placed side-by-side, both will have the same treatment when it comes to minimising loss since each word will be treated as both the target word and context word. Comparing that to CBOW, the infrequent word will only be part of a collection of context words used to predict the target word. Therefore, the model will assign the infrequent word a low probability. In this article, we will be implementing the Skip-gram architecture. The content is broken down into the following parts for easy reading: Data Preparation — Define corpus, clean, normalise and tokenise wordsHyperparameters — Learning rate, epochs, window size, embedding sizeGenerate Training Data — Build vocabulary, one-hot encoding for words, build dictionaries that map id to word and vice versaModel Training — Pass encoded words through forward pass, calculate error rate, adjust weights using backpropagation and compute lossInference — Get word vector and find similar wordsFurther improvements — Speeding up training time with Skip-gram Negative Sampling (SGNS) and Hierarchical Softmax Data Preparation — Define corpus, clean, normalise and tokenise words Hyperparameters — Learning rate, epochs, window size, embedding size Generate Training Data — Build vocabulary, one-hot encoding for words, build dictionaries that map id to word and vice versa Model Training — Pass encoded words through forward pass, calculate error rate, adjust weights using backpropagation and compute loss Inference — Get word vector and find similar words Further improvements — Speeding up training time with Skip-gram Negative Sampling (SGNS) and Hierarchical Softmax To begin, we start with the following corpus: natural language processing and machine learning is fun and exciting For simplicity, we have chosen a sentence without punctuation and capitalisation. Also, we did not remove stop words “and” and “is”. In reality, text data are unstructured and can be “dirty”. Cleaning them will involve steps such as removing stop words, punctuations, convert text to lowercase (actually depends on your use-case), replacing digits, etc. KDnuggets has an excellent article on this process. Alternatively, Gensim also provides a function to perform simple text preprocessing using gensim.utils.simple_preprocess where it converts a document into a list of lowercase tokens, ignoring tokens that are too short or too long. After preprocessing, we then move on to tokenising the corpus. Here, we tokenise our corpus on whitespace and the result is a list of words: [“natural”, “language”, “processing”, “ and”, “ machine”, “ learning”, “ is”, “ fun”, “and”, “ exciting”] Before we jump into the actual implementation, let us define some of the hyperparameters we need later. [window_size]: As mentioned above, context words are words that are neighbouring the target word. But how far or near should these words be in order to be considered neighbour? This is where we define the window_sizeto be 2 which means that words that are 2 to the left and right of the target words are considered context words. Referencing Figure 3 below, notice that each of the word in the corpus will be a target word as the window slides. [n]: This is the dimension of the word embedding and it typically ranges from 100 to 300 depending on your vocabulary size. Dimension size beyond 300 tends to have diminishing benefit (see page 1538 Figure 2 (a)). Do note that the dimension is also the size of the hidden layer. [epochs]: This is the number of training epochs. In each epoch, we cycle through all training samples. [learning_rate]: The learning rate controls the amount of adjustment made to the weights with respect to the loss gradient. In this section, our main objective is to turn our corpus into a one-hot encoded representation for the Word2Vec model to train on. From our corpus, Figure 4 zooms into each of the 10 windows (#1 to #10) as shown below. Each window consists of both the target word and its context words, highlighted in orange and green respectively. Example of the first and last element in the first and last training window is shown below: # 1 [Target (natural)], [Context (language, processing)][list([1, 0, 0, 0, 0, 0, 0, 0, 0]) list([[0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0]])] *****#2 to #9 removed**** #10 [Target (exciting)], [Context (fun, and)][list([0, 0, 0, 0, 0, 0, 0, 0, 1]) list([[0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0]])] To generate the one-hot training data, we first initialise the word2vec() object and then using the object w2v to call the function generate_training_data by passing settings and corpus as arguments. Inside the function generate_training_data, we performed the following operations: self.v_count — Length of vocabulary (note that vocabulary refers to the number of unique words in the corpus)self.words_list — List of words in vocabularyself.word_index — Dictionary with each key as word in vocabulary and value as indexself.index_word — Dictionary with each key as index and value as word in vocabularyfor loop to append one-hot representation for each target and its context words to training_data using word2onehot function. self.v_count — Length of vocabulary (note that vocabulary refers to the number of unique words in the corpus) self.words_list — List of words in vocabulary self.word_index — Dictionary with each key as word in vocabulary and value as index self.index_word — Dictionary with each key as index and value as word in vocabulary for loop to append one-hot representation for each target and its context words to training_data using word2onehot function. With our training_data, we are now ready to train our model. Training starts with w2v.train(training_data) where we pass in the training data and call the function train. The Word2Vec model consists of 2 weight matrices (w1 and w2) and for demo purposes, we have initialised the values to a shape of (9x10) and (10x9) respectively. This facilitates the calculation of backpropagation error which will be covered later in the article. In the actual training, you should randomly initialise the weights (e.g. using np.random.uniform()). To do that, comment line 9 and 10 and uncomment line 11 and 12. Next, we start training our first epoch using the first training example by passing in w_t which represents the one-hot vector for target word to theforward_pass function. In the forward_pass function, we perform a dot product between w1 and w_t to produce h(Line 24). Then, we perform another dot product using w2 and h to produce the output layer u(Line 26). Lastly, we run u through softmax to force each element to the range of 0 and 1 to give us the probabilities for prediction (Line 28) before returning the vector for predictiony_pred, hidden layer h and output layer u. I have attached some screenshots to show the calculation for the first training sample in the first window (#1) where the target word is ‘natural’ and context words are ‘language’ and ‘processing’. Feel free to look into the formula in the Google Sheet here. Error — With y_pred, h and u, we proceed to calculate the error for this particular set of target and context words. This is done by summing up the difference between y_pred and each of the context words inw_c. Backpropagation — Next, we use the backpropagation function, backprop, to calculate the amount of adjustment we need to alter the weights using the function backprop by passing in error EI, hidden layer h and vector for target word w_t. To update the weights, we multiply the weights to be adjusted (dl_dw1 and dl_dw2) with learning rate and then subtract it from the current weights (w1 and w2). Loss — Lastly, we compute the overall loss after finishing each training sample according to the loss function. Take note that the loss function comprises of 2 parts. The first part is the negative of the sum for all the elements in the output layer (before softmax). The second part takes the number of the context words and multiplies the log of sum for all elements (after exponential) in the output layer. Now that we have completed training for 50 epochs, both weights (w1 and w2) are now ready to perform inference. With a trained set of weights, the first thing we can do is to look at the word vector for a word in the vocabulary. We can simply do this by looking up the index of the word against the trained weight (w1). In the following example, we look up the vector for the word “machine”. > print(w2v.word_vec("machine"))[ 0.76702922 -0.95673743 0.49207258 0.16240808 -0.4538815 -0.74678226 0.42072706 -0.04147312 0.08947326 -0.24245257] Another thing we can do is to find similar words. Even though our vocabulary is small, we can still implement the function vec_sim by computing the cosine similarity between words. > w2v.vec_sim("machine", 3)machine 1.0fun 0.6223490454018772and 0.5190154215400249 If you are still reading the article, well done and thank you! But this is not the end. As you might have noticed in the backpropagation step above, we are required to adjust the weights for all other words that were not involved in the training sample. This process can take up a long time if the size of your vocabulary is large (e.g. tens of thousands). To solve this, below are the two features in Word2Vec you can implement to speed things up: Skip-gram Negative Sampling (SGNS) helps to speed up training time and improve quality of resulting word vectors. This is done by training the network to only modify a small percentage of the weights rather than all of them. Recall in our example above, we update the weights for every other word and this can take a very long time if the vocab size is large. With SGNS, we only need to update the weights for the target word and a small number (e.g. 5 to 20) of random ‘negative’ words. Hierarchical Softmax is also another trick to speed up training time replacing the original softmax. The main idea is that instead of evaluating all the output nodes to obtain the probability distribution, we only need to evaluate about log (based 2) of it. It uses a binary tree (Huffman coding tree) representation where the nodes in the output layer are represented as leaves and its nodes are represented in relative probabilities to its child nodes. Beyond that, why not try tweaking the code to implement the Continuous Bag-of-Words (CBOW) architecture? 😃 This article is an introduction to Word2Vec and into the world of word embedding. It is also worth noting that there are pre-trained embeddings available such as GloVe, fastText and ELMo where you can download and use directly. There are also extensions of Word2Vec such as Doc2Vec and the most recent Code2Vec where documents and codes are turned into vectors. 😉 Lastly, I want to thank to Ren Jie Tan, Raimi and Yuxin for taking time to comment and read the drafts of this. 💪 Note: This article first appeared at my blog https://derekchia.com/an-implementation-guide-to-word2vec-using-numpy-and-google-sheets/
[ { "code": null, "e": 340, "s": 171, "text": "This article is an implementation guide to Word2Vec using NumPy and Google Sheets. If you you have trouble reading this, consider subscribing to Medium Membership here!" }, { "code": null, "e": 777, "s": 340, "text": "Word2Vec is touted as one of the biggest, most recent breakthrough in the field of Natural Language Processing (NLP). The concept is simple, elegant and (relatively) easy to grasp. A quick Google search returns multiple results on how to use them with standard libraries such as Gensim and TensorFlow. Also, for the curious minds, check out the original implementation using C by Tomas Mikolov. The original paper can be found here too." }, { "code": null, "e": 1047, "s": 777, "text": "The main focus on this article is to present Word2Vec in detail. For that, I implemented Word2Vec on Python using NumPy (with much help from other tutorials) and also prepared a Google Sheet to showcase the calculations. Here are the links to the code and Google Sheet." }, { "code": null, "e": 1453, "s": 1047, "text": "The objective of Word2Vec is to generate vector representations of words that carry semantic meanings for further NLP tasks. Each word vector is typically several hundred dimensions and each unique word in the corpus is assigned a vector in the space. For example, the word “happy” can be represented as a vector of 4 dimensions [0.24, 0.45, 0.11, 0.49] and “sad” has a vector of [0.88, 0.78, 0.45, 0.91]." }, { "code": null, "e": 1680, "s": 1453, "text": "The transformation from words to vectors is also known as word embedding. The reason for this transformation is so that machine learning algorithm can perform linear algebra operations on numbers (in vectors) instead of words." }, { "code": null, "e": 2184, "s": 1680, "text": "To implement Word2Vec, there are two flavors to choose from — Continuous Bag-Of-Words (CBOW) or continuous Skip-gram (SG). In short, CBOW attempts to guess the output (target word) from its neighbouring words (context words) whereas continuous Skip-Gram guesses the context words from a target word. Effectively, Word2Vec is based on distributional hypothesis where the context for each word is in its nearby words. Hence, by looking at its neighbouring words, we can attempt to predict the target word." }, { "code": null, "e": 2282, "s": 2184, "text": "According to Mikolov (quoted in this article), here is the difference between Skip-gram and CBOW:" }, { "code": null, "e": 2387, "s": 2282, "text": "Skip-gram: works well with small amount of the training data, represents well even rare words or phrases" }, { "code": null, "e": 2491, "s": 2387, "text": "CBOW: several times faster to train than the skip-gram, slightly better accuracy for the frequent words" }, { "code": null, "e": 3033, "s": 2491, "text": "To elaborate further, since Skip-gram learns to predict the context words from a given word, in case where two words (one appearing infrequently and the other more frequently) are placed side-by-side, both will have the same treatment when it comes to minimising loss since each word will be treated as both the target word and context word. Comparing that to CBOW, the infrequent word will only be part of a collection of context words used to predict the target word. Therefore, the model will assign the infrequent word a low probability." }, { "code": null, "e": 3172, "s": 3033, "text": "In this article, we will be implementing the Skip-gram architecture. The content is broken down into the following parts for easy reading:" }, { "code": null, "e": 3730, "s": 3172, "text": "Data Preparation — Define corpus, clean, normalise and tokenise wordsHyperparameters — Learning rate, epochs, window size, embedding sizeGenerate Training Data — Build vocabulary, one-hot encoding for words, build dictionaries that map id to word and vice versaModel Training — Pass encoded words through forward pass, calculate error rate, adjust weights using backpropagation and compute lossInference — Get word vector and find similar wordsFurther improvements — Speeding up training time with Skip-gram Negative Sampling (SGNS) and Hierarchical Softmax" }, { "code": null, "e": 3800, "s": 3730, "text": "Data Preparation — Define corpus, clean, normalise and tokenise words" }, { "code": null, "e": 3869, "s": 3800, "text": "Hyperparameters — Learning rate, epochs, window size, embedding size" }, { "code": null, "e": 3994, "s": 3869, "text": "Generate Training Data — Build vocabulary, one-hot encoding for words, build dictionaries that map id to word and vice versa" }, { "code": null, "e": 4128, "s": 3994, "text": "Model Training — Pass encoded words through forward pass, calculate error rate, adjust weights using backpropagation and compute loss" }, { "code": null, "e": 4179, "s": 4128, "text": "Inference — Get word vector and find similar words" }, { "code": null, "e": 4293, "s": 4179, "text": "Further improvements — Speeding up training time with Skip-gram Negative Sampling (SGNS) and Hierarchical Softmax" }, { "code": null, "e": 4339, "s": 4293, "text": "To begin, we start with the following corpus:" }, { "code": null, "e": 4408, "s": 4339, "text": "natural language processing and machine learning is fun and exciting" }, { "code": null, "e": 4541, "s": 4408, "text": "For simplicity, we have chosen a sentence without punctuation and capitalisation. Also, we did not remove stop words “and” and “is”." }, { "code": null, "e": 5045, "s": 4541, "text": "In reality, text data are unstructured and can be “dirty”. Cleaning them will involve steps such as removing stop words, punctuations, convert text to lowercase (actually depends on your use-case), replacing digits, etc. KDnuggets has an excellent article on this process. Alternatively, Gensim also provides a function to perform simple text preprocessing using gensim.utils.simple_preprocess where it converts a document into a list of lowercase tokens, ignoring tokens that are too short or too long." }, { "code": null, "e": 5186, "s": 5045, "text": "After preprocessing, we then move on to tokenising the corpus. Here, we tokenise our corpus on whitespace and the result is a list of words:" }, { "code": null, "e": 5292, "s": 5186, "text": "[“natural”, “language”, “processing”, “ and”, “ machine”, “ learning”, “ is”, “ fun”, “and”, “ exciting”]" }, { "code": null, "e": 5396, "s": 5292, "text": "Before we jump into the actual implementation, let us define some of the hyperparameters we need later." }, { "code": null, "e": 5841, "s": 5396, "text": "[window_size]: As mentioned above, context words are words that are neighbouring the target word. But how far or near should these words be in order to be considered neighbour? This is where we define the window_sizeto be 2 which means that words that are 2 to the left and right of the target words are considered context words. Referencing Figure 3 below, notice that each of the word in the corpus will be a target word as the window slides." }, { "code": null, "e": 6120, "s": 5841, "text": "[n]: This is the dimension of the word embedding and it typically ranges from 100 to 300 depending on your vocabulary size. Dimension size beyond 300 tends to have diminishing benefit (see page 1538 Figure 2 (a)). Do note that the dimension is also the size of the hidden layer." }, { "code": null, "e": 6223, "s": 6120, "text": "[epochs]: This is the number of training epochs. In each epoch, we cycle through all training samples." }, { "code": null, "e": 6347, "s": 6223, "text": "[learning_rate]: The learning rate controls the amount of adjustment made to the weights with respect to the loss gradient." }, { "code": null, "e": 6681, "s": 6347, "text": "In this section, our main objective is to turn our corpus into a one-hot encoded representation for the Word2Vec model to train on. From our corpus, Figure 4 zooms into each of the 10 windows (#1 to #10) as shown below. Each window consists of both the target word and its context words, highlighted in orange and green respectively." }, { "code": null, "e": 6773, "s": 6681, "text": "Example of the first and last element in the first and last training window is shown below:" }, { "code": null, "e": 6930, "s": 6773, "text": "# 1 [Target (natural)], [Context (language, processing)][list([1, 0, 0, 0, 0, 0, 0, 0, 0]) list([[0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0]])]" }, { "code": null, "e": 6956, "s": 6930, "text": "*****#2 to #9 removed****" }, { "code": null, "e": 7102, "s": 6956, "text": "#10 [Target (exciting)], [Context (fun, and)][list([0, 0, 0, 0, 0, 0, 0, 0, 1]) list([[0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0]])]" }, { "code": null, "e": 7302, "s": 7102, "text": "To generate the one-hot training data, we first initialise the word2vec() object and then using the object w2v to call the function generate_training_data by passing settings and corpus as arguments." }, { "code": null, "e": 7385, "s": 7302, "text": "Inside the function generate_training_data, we performed the following operations:" }, { "code": null, "e": 7830, "s": 7385, "text": "self.v_count — Length of vocabulary (note that vocabulary refers to the number of unique words in the corpus)self.words_list — List of words in vocabularyself.word_index — Dictionary with each key as word in vocabulary and value as indexself.index_word — Dictionary with each key as index and value as word in vocabularyfor loop to append one-hot representation for each target and its context words to training_data using word2onehot function." }, { "code": null, "e": 7940, "s": 7830, "text": "self.v_count — Length of vocabulary (note that vocabulary refers to the number of unique words in the corpus)" }, { "code": null, "e": 7986, "s": 7940, "text": "self.words_list — List of words in vocabulary" }, { "code": null, "e": 8070, "s": 7986, "text": "self.word_index — Dictionary with each key as word in vocabulary and value as index" }, { "code": null, "e": 8154, "s": 8070, "text": "self.index_word — Dictionary with each key as index and value as word in vocabulary" }, { "code": null, "e": 8279, "s": 8154, "text": "for loop to append one-hot representation for each target and its context words to training_data using word2onehot function." }, { "code": null, "e": 8450, "s": 8279, "text": "With our training_data, we are now ready to train our model. Training starts with w2v.train(training_data) where we pass in the training data and call the function train." }, { "code": null, "e": 8878, "s": 8450, "text": "The Word2Vec model consists of 2 weight matrices (w1 and w2) and for demo purposes, we have initialised the values to a shape of (9x10) and (10x9) respectively. This facilitates the calculation of backpropagation error which will be covered later in the article. In the actual training, you should randomly initialise the weights (e.g. using np.random.uniform()). To do that, comment line 9 and 10 and uncomment line 11 and 12." }, { "code": null, "e": 9457, "s": 8878, "text": "Next, we start training our first epoch using the first training example by passing in w_t which represents the one-hot vector for target word to theforward_pass function. In the forward_pass function, we perform a dot product between w1 and w_t to produce h(Line 24). Then, we perform another dot product using w2 and h to produce the output layer u(Line 26). Lastly, we run u through softmax to force each element to the range of 0 and 1 to give us the probabilities for prediction (Line 28) before returning the vector for predictiony_pred, hidden layer h and output layer u." }, { "code": null, "e": 9716, "s": 9457, "text": "I have attached some screenshots to show the calculation for the first training sample in the first window (#1) where the target word is ‘natural’ and context words are ‘language’ and ‘processing’. Feel free to look into the formula in the Google Sheet here." }, { "code": null, "e": 9927, "s": 9716, "text": "Error — With y_pred, h and u, we proceed to calculate the error for this particular set of target and context words. This is done by summing up the difference between y_pred and each of the context words inw_c." }, { "code": null, "e": 10164, "s": 9927, "text": "Backpropagation — Next, we use the backpropagation function, backprop, to calculate the amount of adjustment we need to alter the weights using the function backprop by passing in error EI, hidden layer h and vector for target word w_t." }, { "code": null, "e": 10324, "s": 10164, "text": "To update the weights, we multiply the weights to be adjusted (dl_dw1 and dl_dw2) with learning rate and then subtract it from the current weights (w1 and w2)." }, { "code": null, "e": 10734, "s": 10324, "text": "Loss — Lastly, we compute the overall loss after finishing each training sample according to the loss function. Take note that the loss function comprises of 2 parts. The first part is the negative of the sum for all the elements in the output layer (before softmax). The second part takes the number of the context words and multiplies the log of sum for all elements (after exponential) in the output layer." }, { "code": null, "e": 10846, "s": 10734, "text": "Now that we have completed training for 50 epochs, both weights (w1 and w2) are now ready to perform inference." }, { "code": null, "e": 11126, "s": 10846, "text": "With a trained set of weights, the first thing we can do is to look at the word vector for a word in the vocabulary. We can simply do this by looking up the index of the word against the trained weight (w1). In the following example, we look up the vector for the word “machine”." }, { "code": null, "e": 11280, "s": 11126, "text": "> print(w2v.word_vec(\"machine\"))[ 0.76702922 -0.95673743 0.49207258 0.16240808 -0.4538815 -0.74678226 0.42072706 -0.04147312 0.08947326 -0.24245257]" }, { "code": null, "e": 11461, "s": 11280, "text": "Another thing we can do is to find similar words. Even though our vocabulary is small, we can still implement the function vec_sim by computing the cosine similarity between words." }, { "code": null, "e": 11544, "s": 11461, "text": "> w2v.vec_sim(\"machine\", 3)machine 1.0fun 0.6223490454018772and 0.5190154215400249" }, { "code": null, "e": 11901, "s": 11544, "text": "If you are still reading the article, well done and thank you! But this is not the end. As you might have noticed in the backpropagation step above, we are required to adjust the weights for all other words that were not involved in the training sample. This process can take up a long time if the size of your vocabulary is large (e.g. tens of thousands)." }, { "code": null, "e": 11993, "s": 11901, "text": "To solve this, below are the two features in Word2Vec you can implement to speed things up:" }, { "code": null, "e": 12481, "s": 11993, "text": "Skip-gram Negative Sampling (SGNS) helps to speed up training time and improve quality of resulting word vectors. This is done by training the network to only modify a small percentage of the weights rather than all of them. Recall in our example above, we update the weights for every other word and this can take a very long time if the vocab size is large. With SGNS, we only need to update the weights for the target word and a small number (e.g. 5 to 20) of random ‘negative’ words." }, { "code": null, "e": 12936, "s": 12481, "text": "Hierarchical Softmax is also another trick to speed up training time replacing the original softmax. The main idea is that instead of evaluating all the output nodes to obtain the probability distribution, we only need to evaluate about log (based 2) of it. It uses a binary tree (Huffman coding tree) representation where the nodes in the output layer are represented as leaves and its nodes are represented in relative probabilities to its child nodes." }, { "code": null, "e": 13043, "s": 12936, "text": "Beyond that, why not try tweaking the code to implement the Continuous Bag-of-Words (CBOW) architecture? 😃" }, { "code": null, "e": 13407, "s": 13043, "text": "This article is an introduction to Word2Vec and into the world of word embedding. It is also worth noting that there are pre-trained embeddings available such as GloVe, fastText and ELMo where you can download and use directly. There are also extensions of Word2Vec such as Doc2Vec and the most recent Code2Vec where documents and codes are turned into vectors. 😉" }, { "code": null, "e": 13521, "s": 13407, "text": "Lastly, I want to thank to Ren Jie Tan, Raimi and Yuxin for taking time to comment and read the drafts of this. 💪" } ]
RENAME (ρ) Operation in Relational Algebra - GeeksforGeeks
05 Oct, 2020 Prerequisites – Introduction of Relational Algebra in DBMS, Basic Operators in Relational Algebra The RENAME operation is used to rename the output of a relation. Sometimes it is simple and suitable to break a complicated sequence of operations and rename it as a relation with different names. Reasons to rename a relation can be many, like – We may want to save the result of a relational algebra expression as a relation so that we can use it later. We may want to join a relation with itself, in that case, it becomes too confusing to specify which one of the tables we are talking about, in that case, we rename one of the tables and perform join operations on them. Notation: ρ X (R) where the symbol ‘ρ’ is used to denote the RENAME operator and R is the result of the sequence of operation or expression which is saved with the name X. Example-1: Query to rename the relation Student as Male Student and the attributes of Student – RollNo, SName as (Sno, Name). ρ MaleStudent(Sno, Name) πRollNo, SName(σCondition(Student)) Example-2: Query to rename the attributes Name, Age of table Department to A,B. ρ (A, B) (Department) Example-3: Query to rename the table name Project to Pro and its attributes to P, Q, R. ρ Pro(P, Q, R) (Project) Example-4: Query to rename the first attribute of the table Student with attributes A, B, C to P. ρ (P, B, C) (Student) adarshpro43 DBMS-Relational Model DBMS GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Clustered and Non-clustered index SQL | Views Difference between DDL and DML in DBMS Third Normal Form (3NF) Second Normal Form (2NF) Layers of OSI Model Types of Operating Systems Page Replacement Algorithms in Operating Systems TCP/IP Model Differences between TCP and UDP
[ { "code": null, "e": 24710, "s": 24682, "text": "\n05 Oct, 2020" }, { "code": null, "e": 24809, "s": 24710, "text": "Prerequisites – Introduction of Relational Algebra in DBMS, Basic Operators in Relational Algebra " }, { "code": null, "e": 24875, "s": 24809, "text": "The RENAME operation is used to rename the output of a relation. " }, { "code": null, "e": 25058, "s": 24875, "text": "Sometimes it is simple and suitable to break a complicated sequence of operations and rename it as a relation with different names. Reasons to rename a relation can be many, like – " }, { "code": null, "e": 25168, "s": 25058, "text": "We may want to save the result of a relational algebra expression as a relation so that we can use it later. " }, { "code": null, "e": 25388, "s": 25168, "text": "We may want to join a relation with itself, in that case, it becomes too confusing to specify which one of the tables we are talking about, in that case, we rename one of the tables and perform join operations on them. " }, { "code": null, "e": 25399, "s": 25388, "text": "Notation: " }, { "code": null, "e": 25408, "s": 25399, "text": "ρ X (R)\n" }, { "code": null, "e": 25564, "s": 25408, "text": "where the symbol ‘ρ’ is used to denote the RENAME operator and R is the result of the sequence of operation or expression which is saved with the name X. " }, { "code": null, "e": 25691, "s": 25564, "text": "Example-1: Query to rename the relation Student as Male Student and the attributes of Student – RollNo, SName as (Sno, Name)." }, { "code": null, "e": 25753, "s": 25691, "text": "ρ MaleStudent(Sno, Name) πRollNo, SName(σCondition(Student))\n" }, { "code": null, "e": 25835, "s": 25753, "text": "Example-2: Query to rename the attributes Name, Age of table Department to A,B. " }, { "code": null, "e": 25858, "s": 25835, "text": "ρ (A, B) (Department)\n" }, { "code": null, "e": 25947, "s": 25858, "text": "Example-3: Query to rename the table name Project to Pro and its attributes to P, Q, R. " }, { "code": null, "e": 25973, "s": 25947, "text": "ρ Pro(P, Q, R) (Project)\n" }, { "code": null, "e": 26072, "s": 25973, "text": "Example-4: Query to rename the first attribute of the table Student with attributes A, B, C to P. " }, { "code": null, "e": 26094, "s": 26072, "text": "ρ (P, B, C) (Student)" }, { "code": null, "e": 26106, "s": 26094, "text": "adarshpro43" }, { "code": null, "e": 26128, "s": 26106, "text": "DBMS-Relational Model" }, { "code": null, "e": 26133, "s": 26128, "text": "DBMS" }, { "code": null, "e": 26141, "s": 26133, "text": "GATE CS" }, { "code": null, "e": 26146, "s": 26141, "text": "DBMS" }, { "code": null, "e": 26244, "s": 26146, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26253, "s": 26244, "text": "Comments" }, { "code": null, "e": 26266, "s": 26253, "text": "Old Comments" }, { "code": null, "e": 26319, "s": 26266, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 26331, "s": 26319, "text": "SQL | Views" }, { "code": null, "e": 26370, "s": 26331, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 26394, "s": 26370, "text": "Third Normal Form (3NF)" }, { "code": null, "e": 26419, "s": 26394, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 26439, "s": 26419, "text": "Layers of OSI Model" }, { "code": null, "e": 26466, "s": 26439, "text": "Types of Operating Systems" }, { "code": null, "e": 26515, "s": 26466, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 26528, "s": 26515, "text": "TCP/IP Model" } ]
Beyond Linear Regression: An Introduction to GLMs | by Genevieve Hayes | Towards Data Science
Coming from a statistics background, my first foray into data science and machine learning was via linear regression. At the time, I genuinely believed there was no statistical modelling problem so complex it couldn’t be solved using a linear regression model that was appropriately defined. At that same time, I also believed that a dataset containing 5000 data points was “big”; that learning SAS was more valuable to my career than learning R; and that Buffy the Vampire Slayer was the greatest television show ever made. I was an undergraduate and my world view was extremely narrow. Yet, in the universe defined by my second-year undergraduate statistics class, I was actually right. There really was no problem so complex that it couldn’t be modelled using a linear regression model. Any problem that was too complex for a linear regression modelling was conveniently hidden from us, so for all practical purposes, didn’t exist within that world. This highlights the trap a lot of data scientists, particularly those early in their careers, risk falling into. A lot of introductory machine learning courses only teach students a certain finite set of possible models (usually linear and logistic regression, decision trees, naïve Bayes, support vector machines and neural networks) and only provide examples using datasets where one or more of these models is appropriate. This can lead data scientists to the mistaken belief that all supervised learning problems can be solved with one of a small set of machine learning models. But the models taught in introductory machine learning courses are certainly not the only statistical or machine learning models out there. One such model, which is rarely taught in machine learning MOOCs or university Data Science degrees, is the generalized linear model or GLM. GLMs are frequently used in insurance premium setting and have proven to be one of the most useful statistical models I have encountered in my career to date. In this article, we take a closer look at this highly versatile, yet too often ignored, model. A (multiple) linear regression model is made up of three components: An output (or response/dependent) variable, Y, where all observations of this variable are assumed to be independently drawn from a normal distribution with constant variance, s2;A vector of k input (or explanatory/independent) variables, X1, X2, ..., Xk; andA vector of k+1 parameters, b0, b1,..., bk, which allow us to express the mean of Y as a linear combination of our input variables: An output (or response/dependent) variable, Y, where all observations of this variable are assumed to be independently drawn from a normal distribution with constant variance, s2; A vector of k input (or explanatory/independent) variables, X1, X2, ..., Xk; and A vector of k+1 parameters, b0, b1,..., bk, which allow us to express the mean of Y as a linear combination of our input variables: Together, these three components define the probability distribution of Y as Yi ~ iid N(mi, s2), and our aim in fitting a linear regression model is to determine the parameter values that will optimally define that distribution for our data. This can be done using several different methods, including ordinary least squares (typically used for smaller datasets) and gradient descent (typically used for larger datasets). The key strengths of linear regression are that linear regression models are: fast to train and query; not prone to overfitting and make efficient use of data, so can be applied to relatively small datasets; and are easy to explain, even to people from a non-technical background. However, a key weakness of linear regression is the restrictive assumptions that underlie it, which must hold for the model to provide a good fit to the data. In particular, the normality assumption. By definition, normally distributed data is continuous, symmetrical and defined over the entire number line. That means that any data which is either discrete, asymmetrical, or can take on values only within a limited range, really shouldn’t be modelled using a linear regression. As anyone who’s taken undergraduate statistics will know, there are certain work arounds you can use if your data doesn’t exhibit one or more of these characteristics. For example, if our data is skewed, we can transform it by taking the log or square root of our outputs. However, this can be seen as a classic case of fitting our data to our model, which is never the best solution to a problem. An alternative approach is to use a different type of regression model, which is specifically designed for use with non-normal data. This is where generalized linear models come in. Generalized linear models (GLMs) can be thought of as a generalization of the multiple linear regression model. GLMs are also made up of three components, which are similar to the components of a linear regression model, but slightly different. Specifically, GLMs are made up of: An output variable, Y, where all observations of this variable are assumed to be independently drawn from an exponential family distribution;A vector of k input variables, X1, X2, ..., Xk; andA vector of k+1 parameters, b0, b1,..., bk, and a link function g(), which allow us to write g(E(Y)) as a linear combination of our input variables. That is: An output variable, Y, where all observations of this variable are assumed to be independently drawn from an exponential family distribution; A vector of k input variables, X1, X2, ..., Xk; and A vector of k+1 parameters, b0, b1,..., bk, and a link function g(), which allow us to write g(E(Y)) as a linear combination of our input variables. That is: where m = E(Y). Again, our goal is to determine the optimal parameter values to define the probability distribution of Y, but we are now no longer constrained to Y only following a normal distribution. Under the GLM assumptions, Y can now follow any probability distribution within the “exponential family”, which includes not only the exponential distribution, but also the normal, gamma, chi-squared, Poisson, binomial (for a fixed number of trails), negative binomial (for a fixed number of failures), beta and lognormal distributions, among others. Pretty much every probability distribution that is commonly taught in undergraduate and Masters level statistics courses is a member of the exponential family. The purpose of our link function is to transform our output variable, so that we can express it as a linear combination of our input variables (it is, NOT, to transform our output variable to normality, as is often mistakenly believed to be the case). Depending on the probability distribution from which we assume our output distribution to be drawn, there are certain link functions that are commonly used. For example: When specifying a GLM, it is therefore, necessary to specify the output probability distribution function and the link function. A standard linear regression model is a special case of a GLM where we assume a normal probability distribution and an identity link. GLMs typically outperform linear regression models in cases where the normality assumption is violated. Three situations in which this can occur are the cases of: count data; skewed data; and binary data. Let’s look at how GLMs can be used in each of these situations. Count data is any data that can only take on non-negative integer values. As the name suggests, it typically arises when counting observations of a particular type of event over a set period of time. For example, the number of car accidents at an intersection per year; or the number of times a process fails each day. In order to fit a GLM to count data, we need to assume a probability distribution and link function for our model. Since count data is discrete, the probability distribution must also be discrete. The most common choice in this situation is a Poisson or negative binomial distribution, with a log link function. To fit a Poisson or negative binomial GLM to our data, we can use Python’s statsmodels package, using syntax similar to the following: import pandas as pd import statsmodels.api as sm count_model = sm.GLM(count_data['Y'], sm.add_constant(count_data[['X1', 'X2']]), family=sm.families.Poisson(sm.genmod.families.links.log)).fit() This syntax assumes our dataset is in the form of a Pandas dataframe called count_data, with output variable Y and input variables X1 and X2, and that we want to fit a Poisson GLM. To fit a negative binomial GLM, instead of a Poisson GLM, all we need to do is change sm.families.Poisson to sm.families.NegativeBinomial. Although asymmetric data can be skewed in either direction. In practice, most asymmetric data you will encounter is right or positive skewed, such as the dataset plotted below. As before, to fit a GLM to this data, we need to select a probability distribution and link function. Our probability function needs to be positively skewed, and the most common choice in such a situation is a gamma distribution with a log link. To fit a gamma distribution with a log link to our data, using the statsmodels package, we can use the same syntax as for the Poisson GLM, but replace sm.families.Poisson with sm.families.Gamma The gamma distribution is only defined for values greater than 0. Therefore, if our output variable Y can take on negative or zero, then it may be necessary to transform our data, by adding a sufficiently large constant to the output variable, prior to fitting the model. For example, if our output variable could take on any non-negative value, including zero, we could transform it by adding 0.01 to all Y values prior to fitting our model, shifting the minimum value to 0.01. As with the previous two examples, the abovedescribed GLM can be fitted using the statsmodels package, using the same syntax as before, but replacing sm.families.Poisson with sm.families.Binomial, and sm.genmod.families.links.log with sm.genmod.families.links.logit. That is, if we assume our dataset is called binary_data, and our input and output variables are as previously defined, using the command: binary_model = sm.GLM(binary_data['Y'], sm.add_constant(binary _data[['X1', 'X2']]), family=sm.families.Binomial(sm.genmod.families.links.logit)).fit() Alternatively, we could also fit this model using the Python scikit-learn package’s sklearn.linear_model.LogisticRegression function. To quote Shakespeare, “there are more things in heaven and earth, than are dreamt of in your philosophy,” and there is a lot more to data science and machine learning than just the contents of your average introductory MOOC. In this article, we introduced one type of model that many early career data scientists are unfamiliar with, but this is just the tip of the iceberg, and there are many more where that came from. That isn’t to say that every data scientist needs to know everything there is to know about every statistical or machine learning model in existence. However, by just being aware of there being more to data science than just the basic models, you are less likely to make the mistake of fitting the data to the model, when you really should be fitting the model to the data.
[ { "code": null, "e": 464, "s": 172, "text": "Coming from a statistics background, my first foray into data science and machine learning was via linear regression. At the time, I genuinely believed there was no statistical modelling problem so complex it couldn’t be solved using a linear regression model that was appropriately defined." }, { "code": null, "e": 697, "s": 464, "text": "At that same time, I also believed that a dataset containing 5000 data points was “big”; that learning SAS was more valuable to my career than learning R; and that Buffy the Vampire Slayer was the greatest television show ever made." }, { "code": null, "e": 760, "s": 697, "text": "I was an undergraduate and my world view was extremely narrow." }, { "code": null, "e": 1125, "s": 760, "text": "Yet, in the universe defined by my second-year undergraduate statistics class, I was actually right. There really was no problem so complex that it couldn’t be modelled using a linear regression model. Any problem that was too complex for a linear regression modelling was conveniently hidden from us, so for all practical purposes, didn’t exist within that world." }, { "code": null, "e": 1238, "s": 1125, "text": "This highlights the trap a lot of data scientists, particularly those early in their careers, risk falling into." }, { "code": null, "e": 1552, "s": 1238, "text": "A lot of introductory machine learning courses only teach students a certain finite set of possible models (usually linear and logistic regression, decision trees, naïve Bayes, support vector machines and neural networks) and only provide examples using datasets where one or more of these models is appropriate." }, { "code": null, "e": 1709, "s": 1552, "text": "This can lead data scientists to the mistaken belief that all supervised learning problems can be solved with one of a small set of machine learning models." }, { "code": null, "e": 1849, "s": 1709, "text": "But the models taught in introductory machine learning courses are certainly not the only statistical or machine learning models out there." }, { "code": null, "e": 2149, "s": 1849, "text": "One such model, which is rarely taught in machine learning MOOCs or university Data Science degrees, is the generalized linear model or GLM. GLMs are frequently used in insurance premium setting and have proven to be one of the most useful statistical models I have encountered in my career to date." }, { "code": null, "e": 2244, "s": 2149, "text": "In this article, we take a closer look at this highly versatile, yet too often ignored, model." }, { "code": null, "e": 2313, "s": 2244, "text": "A (multiple) linear regression model is made up of three components:" }, { "code": null, "e": 2704, "s": 2313, "text": "An output (or response/dependent) variable, Y, where all observations of this variable are assumed to be independently drawn from a normal distribution with constant variance, s2;A vector of k input (or explanatory/independent) variables, X1, X2, ..., Xk; andA vector of k+1 parameters, b0, b1,..., bk, which allow us to express the mean of Y as a linear combination of our input variables:" }, { "code": null, "e": 2884, "s": 2704, "text": "An output (or response/dependent) variable, Y, where all observations of this variable are assumed to be independently drawn from a normal distribution with constant variance, s2;" }, { "code": null, "e": 2965, "s": 2884, "text": "A vector of k input (or explanatory/independent) variables, X1, X2, ..., Xk; and" }, { "code": null, "e": 3097, "s": 2965, "text": "A vector of k+1 parameters, b0, b1,..., bk, which allow us to express the mean of Y as a linear combination of our input variables:" }, { "code": null, "e": 3339, "s": 3097, "text": "Together, these three components define the probability distribution of Y as Yi ~ iid N(mi, s2), and our aim in fitting a linear regression model is to determine the parameter values that will optimally define that distribution for our data." }, { "code": null, "e": 3519, "s": 3339, "text": "This can be done using several different methods, including ordinary least squares (typically used for smaller datasets) and gradient descent (typically used for larger datasets)." }, { "code": null, "e": 3597, "s": 3519, "text": "The key strengths of linear regression are that linear regression models are:" }, { "code": null, "e": 3622, "s": 3597, "text": "fast to train and query;" }, { "code": null, "e": 3731, "s": 3622, "text": "not prone to overfitting and make efficient use of data, so can be applied to relatively small datasets; and" }, { "code": null, "e": 3800, "s": 3731, "text": "are easy to explain, even to people from a non-technical background." }, { "code": null, "e": 4000, "s": 3800, "text": "However, a key weakness of linear regression is the restrictive assumptions that underlie it, which must hold for the model to provide a good fit to the data. In particular, the normality assumption." }, { "code": null, "e": 4281, "s": 4000, "text": "By definition, normally distributed data is continuous, symmetrical and defined over the entire number line. That means that any data which is either discrete, asymmetrical, or can take on values only within a limited range, really shouldn’t be modelled using a linear regression." }, { "code": null, "e": 4554, "s": 4281, "text": "As anyone who’s taken undergraduate statistics will know, there are certain work arounds you can use if your data doesn’t exhibit one or more of these characteristics. For example, if our data is skewed, we can transform it by taking the log or square root of our outputs." }, { "code": null, "e": 4861, "s": 4554, "text": "However, this can be seen as a classic case of fitting our data to our model, which is never the best solution to a problem. An alternative approach is to use a different type of regression model, which is specifically designed for use with non-normal data. This is where generalized linear models come in." }, { "code": null, "e": 5141, "s": 4861, "text": "Generalized linear models (GLMs) can be thought of as a generalization of the multiple linear regression model. GLMs are also made up of three components, which are similar to the components of a linear regression model, but slightly different. Specifically, GLMs are made up of:" }, { "code": null, "e": 5491, "s": 5141, "text": "An output variable, Y, where all observations of this variable are assumed to be independently drawn from an exponential family distribution;A vector of k input variables, X1, X2, ..., Xk; andA vector of k+1 parameters, b0, b1,..., bk, and a link function g(), which allow us to write g(E(Y)) as a linear combination of our input variables. That is:" }, { "code": null, "e": 5633, "s": 5491, "text": "An output variable, Y, where all observations of this variable are assumed to be independently drawn from an exponential family distribution;" }, { "code": null, "e": 5685, "s": 5633, "text": "A vector of k input variables, X1, X2, ..., Xk; and" }, { "code": null, "e": 5843, "s": 5685, "text": "A vector of k+1 parameters, b0, b1,..., bk, and a link function g(), which allow us to write g(E(Y)) as a linear combination of our input variables. That is:" }, { "code": null, "e": 5859, "s": 5843, "text": "where m = E(Y)." }, { "code": null, "e": 6045, "s": 5859, "text": "Again, our goal is to determine the optimal parameter values to define the probability distribution of Y, but we are now no longer constrained to Y only following a normal distribution." }, { "code": null, "e": 6396, "s": 6045, "text": "Under the GLM assumptions, Y can now follow any probability distribution within the “exponential family”, which includes not only the exponential distribution, but also the normal, gamma, chi-squared, Poisson, binomial (for a fixed number of trails), negative binomial (for a fixed number of failures), beta and lognormal distributions, among others." }, { "code": null, "e": 6556, "s": 6396, "text": "Pretty much every probability distribution that is commonly taught in undergraduate and Masters level statistics courses is a member of the exponential family." }, { "code": null, "e": 6808, "s": 6556, "text": "The purpose of our link function is to transform our output variable, so that we can express it as a linear combination of our input variables (it is, NOT, to transform our output variable to normality, as is often mistakenly believed to be the case)." }, { "code": null, "e": 6965, "s": 6808, "text": "Depending on the probability distribution from which we assume our output distribution to be drawn, there are certain link functions that are commonly used." }, { "code": null, "e": 6978, "s": 6965, "text": "For example:" }, { "code": null, "e": 7107, "s": 6978, "text": "When specifying a GLM, it is therefore, necessary to specify the output probability distribution function and the link function." }, { "code": null, "e": 7241, "s": 7107, "text": "A standard linear regression model is a special case of a GLM where we assume a normal probability distribution and an identity link." }, { "code": null, "e": 7446, "s": 7241, "text": "GLMs typically outperform linear regression models in cases where the normality assumption is violated. Three situations in which this can occur are the cases of: count data; skewed data; and binary data." }, { "code": null, "e": 7510, "s": 7446, "text": "Let’s look at how GLMs can be used in each of these situations." }, { "code": null, "e": 7829, "s": 7510, "text": "Count data is any data that can only take on non-negative integer values. As the name suggests, it typically arises when counting observations of a particular type of event over a set period of time. For example, the number of car accidents at an intersection per year; or the number of times a process fails each day." }, { "code": null, "e": 8026, "s": 7829, "text": "In order to fit a GLM to count data, we need to assume a probability distribution and link function for our model. Since count data is discrete, the probability distribution must also be discrete." }, { "code": null, "e": 8141, "s": 8026, "text": "The most common choice in this situation is a Poisson or negative binomial distribution, with a log link function." }, { "code": null, "e": 8276, "s": 8141, "text": "To fit a Poisson or negative binomial GLM to our data, we can use Python’s statsmodels package, using syntax similar to the following:" }, { "code": null, "e": 8470, "s": 8276, "text": "import pandas as pd import statsmodels.api as sm count_model = sm.GLM(count_data['Y'], sm.add_constant(count_data[['X1', 'X2']]), family=sm.families.Poisson(sm.genmod.families.links.log)).fit()" }, { "code": null, "e": 8651, "s": 8470, "text": "This syntax assumes our dataset is in the form of a Pandas dataframe called count_data, with output variable Y and input variables X1 and X2, and that we want to fit a Poisson GLM." }, { "code": null, "e": 8790, "s": 8651, "text": "To fit a negative binomial GLM, instead of a Poisson GLM, all we need to do is change sm.families.Poisson to sm.families.NegativeBinomial." }, { "code": null, "e": 8967, "s": 8790, "text": "Although asymmetric data can be skewed in either direction. In practice, most asymmetric data you will encounter is right or positive skewed, such as the dataset plotted below." }, { "code": null, "e": 9213, "s": 8967, "text": "As before, to fit a GLM to this data, we need to select a probability distribution and link function. Our probability function needs to be positively skewed, and the most common choice in such a situation is a gamma distribution with a log link." }, { "code": null, "e": 9407, "s": 9213, "text": "To fit a gamma distribution with a log link to our data, using the statsmodels package, we can use the same syntax as for the Poisson GLM, but replace sm.families.Poisson with sm.families.Gamma" }, { "code": null, "e": 9679, "s": 9407, "text": "The gamma distribution is only defined for values greater than 0. Therefore, if our output variable Y can take on negative or zero, then it may be necessary to transform our data, by adding a sufficiently large constant to the output variable, prior to fitting the model." }, { "code": null, "e": 9886, "s": 9679, "text": "For example, if our output variable could take on any non-negative value, including zero, we could transform it by adding 0.01 to all Y values prior to fitting our model, shifting the minimum value to 0.01." }, { "code": null, "e": 10153, "s": 9886, "text": "As with the previous two examples, the abovedescribed GLM can be fitted using the statsmodels package, using the same syntax as before, but replacing sm.families.Poisson with sm.families.Binomial, and sm.genmod.families.links.log with sm.genmod.families.links.logit." }, { "code": null, "e": 10291, "s": 10153, "text": "That is, if we assume our dataset is called binary_data, and our input and output variables are as previously defined, using the command:" }, { "code": null, "e": 10443, "s": 10291, "text": "binary_model = sm.GLM(binary_data['Y'], sm.add_constant(binary _data[['X1', 'X2']]), family=sm.families.Binomial(sm.genmod.families.links.logit)).fit()" }, { "code": null, "e": 10577, "s": 10443, "text": "Alternatively, we could also fit this model using the Python scikit-learn package’s sklearn.linear_model.LogisticRegression function." }, { "code": null, "e": 10802, "s": 10577, "text": "To quote Shakespeare, “there are more things in heaven and earth, than are dreamt of in your philosophy,” and there is a lot more to data science and machine learning than just the contents of your average introductory MOOC." }, { "code": null, "e": 10998, "s": 10802, "text": "In this article, we introduced one type of model that many early career data scientists are unfamiliar with, but this is just the tip of the iceberg, and there are many more where that came from." }, { "code": null, "e": 11148, "s": 10998, "text": "That isn’t to say that every data scientist needs to know everything there is to know about every statistical or machine learning model in existence." } ]
Angular Material 7 - SnackBar
The <MatSnackBar>, an Angular Directive, is used to show a notification bar to show on mobile devices as an alternative of dialogs/popups. In this chapter, we will showcase the configuration required to show a snack bar using Angular Material. 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 {MatButtonModule,MatSnackBarModule} from '@angular/material' import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MatButtonModule,MatSnackBarModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Following is the content of the modified HTML host file app.component.html. <button mat-button (click)="openSnackBar('Party', 'act')">Show snack-bar</button> Following is the content of the modified ts file app.component.ts. import {Component, Injectable} from '@angular/core'; import { MatSnackBar } from "@angular/material"; @Component({ selector: 'app-root', templateUrl: 'app.component.html', styleUrls: ['app.component.css'] }) export class AppComponent { constructor(public snackBar: MatSnackBar) {} openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); } } Verify the result. Here, we've created a button using mat-button on whose click we shows the snack bar. 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": 2894, "s": 2755, "text": "The <MatSnackBar>, an Angular Directive, is used to show a notification bar to show on mobile devices as an alternative of dialogs/popups." }, { "code": null, "e": 2999, "s": 2894, "text": "In this chapter, we will showcase the configuration required to show a snack bar using Angular Material." }, { "code": null, "e": 3073, "s": 2999, "text": "Following is the content of the modified module descriptor app.module.ts." }, { "code": null, "e": 3724, "s": 3073, "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 {MatButtonModule,MatSnackBarModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatButtonModule,MatSnackBarModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 3800, "s": 3724, "text": "Following is the content of the modified HTML host file app.component.html." }, { "code": null, "e": 3882, "s": 3800, "text": "<button mat-button (click)=\"openSnackBar('Party', 'act')\">Show snack-bar</button>" }, { "code": null, "e": 3949, "s": 3882, "text": "Following is the content of the modified ts file app.component.ts." }, { "code": null, "e": 4383, "s": 3949, "text": "import {Component, Injectable} from '@angular/core';\nimport { MatSnackBar } from \"@angular/material\";\n@Component({\n selector: 'app-root',\n templateUrl: 'app.component.html',\n styleUrls: ['app.component.css']\n})\nexport class AppComponent {\n constructor(public snackBar: MatSnackBar) {}\n openSnackBar(message: string, action: string) {\n this.snackBar.open(message, action, {\n duration: 2000,\n });\n } \n} " }, { "code": null, "e": 4402, "s": 4383, "text": "Verify the result." }, { "code": null, "e": 4487, "s": 4402, "text": "Here, we've created a button using mat-button on whose click we shows the snack bar." }, { "code": null, "e": 4522, "s": 4487, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4536, "s": 4522, "text": " Anadi Sharma" }, { "code": null, "e": 4571, "s": 4536, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4585, "s": 4571, "text": " Anadi Sharma" }, { "code": null, "e": 4620, "s": 4585, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4640, "s": 4620, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4675, "s": 4640, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4692, "s": 4675, "text": " Frahaan Hussain" }, { "code": null, "e": 4725, "s": 4692, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4737, "s": 4725, "text": " Senol Atac" }, { "code": null, "e": 4772, "s": 4737, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4784, "s": 4772, "text": " Senol Atac" }, { "code": null, "e": 4791, "s": 4784, "text": " Print" }, { "code": null, "e": 4802, "s": 4791, "text": " Add Notes" } ]
Calculating Sales Conversion using Bayesian Probability | by Adnan Gillani | Towards Data Science
The article published below takes motivation and reference from Rasmus Bååth tutorials on Bayesian Statistics. Below, I have tried to explain how Bayesian Statistics can be applied to answer questions that someone in the analytics department at any company may be faced with. Background A successful business is often looking to expand on its customer base by trying to acquire new customers through various marketing strategies. Depending on the company’s business model, they may choose from various marketing strategy methods. Therefore, it is imperative to understand which strategy works best in terms of generating success backed by evidence, not intuition. Penetrating a New Market Seeder is a company that sells electric scooters in California and operates as one of the most successful producers of electric scooters in the country. They are trying to tap the Texas region by selling electric scooters in Texas. The marketing team at Seeder employs the use of print media and designs a brochure to attract new customers. They distribute the brochure to 23 Texans and end up making 9 sales. The Question What Seeder management wants to know is how good is print media to market the new electric scooter? If the company went on to produce a large number of brochures, say in quantity of hundreds of thousands, what percentage of conversion should they expect to see? The answer to the question seems pretty easy at first. Using the data collected by the marketing team, calculating the probability of success by dividing number of sales by the total number of brochures distributed. brochures_distributed = 23new_sales = 9conversion_rate = new_sales/brochures_distributedconversion_rate We can see that the probability of making a sale is approximately 39%. This means that for every 100 brochures distributed, Seeder should expect to sell 39 electric scooters. This may seem like a good estimation given the data we have present to us, but it is highly uncertain. We have no information on which people were shown the brochure, what was the motivation behind their decision to buy the electric scooter and a plethora of information which may be deemed as significantly affecting their decision to purchase the electric scooter. The small sample size also raises a red flag regarding the accuracy of the conversion estimate. Using Bayesian Probability to Quantify Uncertainty Bayesian probability allows us to quantify the unknown information using probability distributions. In order to be able to quantify the uncertainty in our study, we require three things. DataGenerative ModelPriors Data Generative Model Priors Data Data in our case will come from the pilot study we conducted. We know that out of the 23 Texans that were shown the brochure, 9 of them were converted into customers. Generative Model A generative model can be termed as a set of instructions that we pass to some parameter(s), say an underlying percentage of conversion, so that the model simulates data based on the parameter(s). For instance, we may assume that there is an underlying conversion of 40% and we show the brochure to randomly selected 50 Texans. Based on our assumed conversion rate, the generative model would estimate 20 sales to be made. Based on the generative model assumed above, we have information regarding the number of sales we are likely to make but we are interested in the percentage at which the sales are likely to be made. Our generative model is simulating data but we already know what our data is. We need to reverse solve the generative model so that it outputs the conversion rate. In order to achieve this, what we need is the third item Priors. Priors Prior is the information the model has before seeing any data. In Bayesian terms, priors is a probability distribution used to represent the uncertainty in the model. In order to create Priors for our model, we will use the uniform probability distribution. By using the uniform probability distribution from 0 to 1, we are stating that before seeing any data, the model assumes that any rate of conversion between 0 and 1 (0% to 100%)is equally likely. Fitting the Model Following is the basic flow of how the model works. From our prior distribution, we draw a random sample for the parameter value. Parameter value in our case is the conversion rate. # number of samples to draw from the prior distributionn_size <- 100000# drawing sample from the prior distribution - which in our case is uniform distributionprior_dist <- runif(n_size, 0, 1)# peeking at the histogram to verify the random sample was generated correctly.hist(prior_dist, main = "Histogram of Prior Distribution", xlab = "Prior on the Conversion Rate", ylab = "Frequency") We take the parameter value from step 1, plug it into our generative model so that the model simulates some data. We repeat this process multiple times using a for loop. # defining the generative model - a model or set of rules that we feed to parameters so that it simulates data based on those set of rulesgenerative_model <- function(rate) { sales <- rbinom(1, size = 23, prob = rate) sales}# simulating the data through our generative modelsales <- rep(NA, n_size)for(i in 1:n_size) { sales[i] <- generative_model(prior_dist[i])} Filter out all sample draws that are consistent with our data, i.e. conversion rate of 0.3913 or total sales equaling 9. # filtering out values from the model that do not match our observed resultspost_rate <- prior_dist[sales == 9] What we are doing here is repeating the sampling process multiple times and generating a random conversion rate after each iteration. The reason for filtering out the sample draws is that we want to keep the data that we observed in reality. Which is, when the marketing team did the process, they generated the conversion rate of 0.3913 by making 9 sales. What is the Real Conversion Rate? The answer to this question is not a single number. It is a probability distribution of possible rates of conversion. The distribution of these possible conversion rates is presented below. #plotting the posterior distributionpost_rate_hist = hist(post_rate, xlim = c(0,1), main = "Histogram of Posterior Distribution")post_rate_hist From the observed distribution of possible conversion rates, we can see that the most likely conversion rate should exist between 35 & 45 percent. We can also see, that the probability of conversion rate over 60% or below 20% is highly unlikely. We can calculate the probabilities of the possible conversion rates by counting the frequency of each bar and dividing it by the total number of draws. To calculate the probability of conversion rate between 40% and 45%, we do the following math # sum of frequency of draws between 0.40 and 0.45 divided by total drawspost_rate_hist$counts[8]/length(post_rate) Here, we have a 20% probability that the conversion rate would fall between 40–45 percent. Answering Some More Questions Which Strategy is Better? We can use the model we created to answer comparative questions regarding marketing strategies. For instance, we can compare conversion rates for two marketing strategies. Say, the marketing team tells that the rate of conversion was 20% when they deployed email marketing. The management now wants to know the probability that print media marketing is better than email marketing. From our probability distribution, we can calculate the frequency of the percentage of conversions greater than 20%, divide it by the total number of draws to get the probability of print media marketing achieving a conversion rate greater than 20%. sum(post_rate > 0.20) / length(post_rate) Here, we can say that there is a 98% probability that print media will achieve over 20% conversion Using the Confidence Interval We can use confidence interval to calculate the conversion rates that cover 95% of the overall distribution. quantile(post_rate, c(0.025, 0.975)) Here, it implies that we are 95% confident that the true conversion rate falls somewhere between 22% and 60%. Conclusion Bayesian probability allows us to distinguish truth from noise by taking into account all of the information that we have prior to running a test. This is exactly what we did here. We took into account the fact that the probability of conversion from 0 to 1 had equal chance of occurring. We then ran a simulation and kept the results that were in accordance with the data that we observed when we distributed brochures. The end result was not a single number, rather a distribution of probabilities. Such distributions allow the stakeholders to input their domain knowledge and try to estimate what the right answer to their question could be under the influence of uncertainty.
[ { "code": null, "e": 449, "s": 171, "text": "The article published below takes motivation and reference from Rasmus Bååth tutorials on Bayesian Statistics. Below, I have tried to explain how Bayesian Statistics can be applied to answer questions that someone in the analytics department at any company may be faced with." }, { "code": null, "e": 460, "s": 449, "text": "Background" }, { "code": null, "e": 837, "s": 460, "text": "A successful business is often looking to expand on its customer base by trying to acquire new customers through various marketing strategies. Depending on the company’s business model, they may choose from various marketing strategy methods. Therefore, it is imperative to understand which strategy works best in terms of generating success backed by evidence, not intuition." }, { "code": null, "e": 862, "s": 837, "text": "Penetrating a New Market" }, { "code": null, "e": 1094, "s": 862, "text": "Seeder is a company that sells electric scooters in California and operates as one of the most successful producers of electric scooters in the country. They are trying to tap the Texas region by selling electric scooters in Texas." }, { "code": null, "e": 1272, "s": 1094, "text": "The marketing team at Seeder employs the use of print media and designs a brochure to attract new customers. They distribute the brochure to 23 Texans and end up making 9 sales." }, { "code": null, "e": 1285, "s": 1272, "text": "The Question" }, { "code": null, "e": 1547, "s": 1285, "text": "What Seeder management wants to know is how good is print media to market the new electric scooter? If the company went on to produce a large number of brochures, say in quantity of hundreds of thousands, what percentage of conversion should they expect to see?" }, { "code": null, "e": 1763, "s": 1547, "text": "The answer to the question seems pretty easy at first. Using the data collected by the marketing team, calculating the probability of success by dividing number of sales by the total number of brochures distributed." }, { "code": null, "e": 1867, "s": 1763, "text": "brochures_distributed = 23new_sales = 9conversion_rate = new_sales/brochures_distributedconversion_rate" }, { "code": null, "e": 2042, "s": 1867, "text": "We can see that the probability of making a sale is approximately 39%. This means that for every 100 brochures distributed, Seeder should expect to sell 39 electric scooters." }, { "code": null, "e": 2505, "s": 2042, "text": "This may seem like a good estimation given the data we have present to us, but it is highly uncertain. We have no information on which people were shown the brochure, what was the motivation behind their decision to buy the electric scooter and a plethora of information which may be deemed as significantly affecting their decision to purchase the electric scooter. The small sample size also raises a red flag regarding the accuracy of the conversion estimate." }, { "code": null, "e": 2556, "s": 2505, "text": "Using Bayesian Probability to Quantify Uncertainty" }, { "code": null, "e": 2743, "s": 2556, "text": "Bayesian probability allows us to quantify the unknown information using probability distributions. In order to be able to quantify the uncertainty in our study, we require three things." }, { "code": null, "e": 2770, "s": 2743, "text": "DataGenerative ModelPriors" }, { "code": null, "e": 2775, "s": 2770, "text": "Data" }, { "code": null, "e": 2792, "s": 2775, "text": "Generative Model" }, { "code": null, "e": 2799, "s": 2792, "text": "Priors" }, { "code": null, "e": 2804, "s": 2799, "text": "Data" }, { "code": null, "e": 2971, "s": 2804, "text": "Data in our case will come from the pilot study we conducted. We know that out of the 23 Texans that were shown the brochure, 9 of them were converted into customers." }, { "code": null, "e": 2988, "s": 2971, "text": "Generative Model" }, { "code": null, "e": 3411, "s": 2988, "text": "A generative model can be termed as a set of instructions that we pass to some parameter(s), say an underlying percentage of conversion, so that the model simulates data based on the parameter(s). For instance, we may assume that there is an underlying conversion of 40% and we show the brochure to randomly selected 50 Texans. Based on our assumed conversion rate, the generative model would estimate 20 sales to be made." }, { "code": null, "e": 3839, "s": 3411, "text": "Based on the generative model assumed above, we have information regarding the number of sales we are likely to make but we are interested in the percentage at which the sales are likely to be made. Our generative model is simulating data but we already know what our data is. We need to reverse solve the generative model so that it outputs the conversion rate. In order to achieve this, what we need is the third item Priors." }, { "code": null, "e": 3846, "s": 3839, "text": "Priors" }, { "code": null, "e": 4300, "s": 3846, "text": "Prior is the information the model has before seeing any data. In Bayesian terms, priors is a probability distribution used to represent the uncertainty in the model. In order to create Priors for our model, we will use the uniform probability distribution. By using the uniform probability distribution from 0 to 1, we are stating that before seeing any data, the model assumes that any rate of conversion between 0 and 1 (0% to 100%)is equally likely." }, { "code": null, "e": 4318, "s": 4300, "text": "Fitting the Model" }, { "code": null, "e": 4370, "s": 4318, "text": "Following is the basic flow of how the model works." }, { "code": null, "e": 4500, "s": 4370, "text": "From our prior distribution, we draw a random sample for the parameter value. Parameter value in our case is the conversion rate." }, { "code": null, "e": 4889, "s": 4500, "text": "# number of samples to draw from the prior distributionn_size <- 100000# drawing sample from the prior distribution - which in our case is uniform distributionprior_dist <- runif(n_size, 0, 1)# peeking at the histogram to verify the random sample was generated correctly.hist(prior_dist, main = \"Histogram of Prior Distribution\", xlab = \"Prior on the Conversion Rate\", ylab = \"Frequency\")" }, { "code": null, "e": 5059, "s": 4889, "text": "We take the parameter value from step 1, plug it into our generative model so that the model simulates some data. We repeat this process multiple times using a for loop." }, { "code": null, "e": 5426, "s": 5059, "text": "# defining the generative model - a model or set of rules that we feed to parameters so that it simulates data based on those set of rulesgenerative_model <- function(rate) { sales <- rbinom(1, size = 23, prob = rate) sales}# simulating the data through our generative modelsales <- rep(NA, n_size)for(i in 1:n_size) { sales[i] <- generative_model(prior_dist[i])}" }, { "code": null, "e": 5547, "s": 5426, "text": "Filter out all sample draws that are consistent with our data, i.e. conversion rate of 0.3913 or total sales equaling 9." }, { "code": null, "e": 5659, "s": 5547, "text": "# filtering out values from the model that do not match our observed resultspost_rate <- prior_dist[sales == 9]" }, { "code": null, "e": 6016, "s": 5659, "text": "What we are doing here is repeating the sampling process multiple times and generating a random conversion rate after each iteration. The reason for filtering out the sample draws is that we want to keep the data that we observed in reality. Which is, when the marketing team did the process, they generated the conversion rate of 0.3913 by making 9 sales." }, { "code": null, "e": 6050, "s": 6016, "text": "What is the Real Conversion Rate?" }, { "code": null, "e": 6240, "s": 6050, "text": "The answer to this question is not a single number. It is a probability distribution of possible rates of conversion. The distribution of these possible conversion rates is presented below." }, { "code": null, "e": 6384, "s": 6240, "text": "#plotting the posterior distributionpost_rate_hist = hist(post_rate, xlim = c(0,1), main = \"Histogram of Posterior Distribution\")post_rate_hist" }, { "code": null, "e": 6630, "s": 6384, "text": "From the observed distribution of possible conversion rates, we can see that the most likely conversion rate should exist between 35 & 45 percent. We can also see, that the probability of conversion rate over 60% or below 20% is highly unlikely." }, { "code": null, "e": 6782, "s": 6630, "text": "We can calculate the probabilities of the possible conversion rates by counting the frequency of each bar and dividing it by the total number of draws." }, { "code": null, "e": 6876, "s": 6782, "text": "To calculate the probability of conversion rate between 40% and 45%, we do the following math" }, { "code": null, "e": 6991, "s": 6876, "text": "# sum of frequency of draws between 0.40 and 0.45 divided by total drawspost_rate_hist$counts[8]/length(post_rate)" }, { "code": null, "e": 7082, "s": 6991, "text": "Here, we have a 20% probability that the conversion rate would fall between 40–45 percent." }, { "code": null, "e": 7112, "s": 7082, "text": "Answering Some More Questions" }, { "code": null, "e": 7138, "s": 7112, "text": "Which Strategy is Better?" }, { "code": null, "e": 7310, "s": 7138, "text": "We can use the model we created to answer comparative questions regarding marketing strategies. For instance, we can compare conversion rates for two marketing strategies." }, { "code": null, "e": 7520, "s": 7310, "text": "Say, the marketing team tells that the rate of conversion was 20% when they deployed email marketing. The management now wants to know the probability that print media marketing is better than email marketing." }, { "code": null, "e": 7770, "s": 7520, "text": "From our probability distribution, we can calculate the frequency of the percentage of conversions greater than 20%, divide it by the total number of draws to get the probability of print media marketing achieving a conversion rate greater than 20%." }, { "code": null, "e": 7812, "s": 7770, "text": "sum(post_rate > 0.20) / length(post_rate)" }, { "code": null, "e": 7911, "s": 7812, "text": "Here, we can say that there is a 98% probability that print media will achieve over 20% conversion" }, { "code": null, "e": 7941, "s": 7911, "text": "Using the Confidence Interval" }, { "code": null, "e": 8050, "s": 7941, "text": "We can use confidence interval to calculate the conversion rates that cover 95% of the overall distribution." }, { "code": null, "e": 8087, "s": 8050, "text": "quantile(post_rate, c(0.025, 0.975))" }, { "code": null, "e": 8197, "s": 8087, "text": "Here, it implies that we are 95% confident that the true conversion rate falls somewhere between 22% and 60%." }, { "code": null, "e": 8208, "s": 8197, "text": "Conclusion" }, { "code": null, "e": 8709, "s": 8208, "text": "Bayesian probability allows us to distinguish truth from noise by taking into account all of the information that we have prior to running a test. This is exactly what we did here. We took into account the fact that the probability of conversion from 0 to 1 had equal chance of occurring. We then ran a simulation and kept the results that were in accordance with the data that we observed when we distributed brochures. The end result was not a single number, rather a distribution of probabilities." } ]
Implementing YOLO on a custom dataset | by Renu Khandelwal | Towards Data Science
In this article we will learn step by step implementation of YOLO v2 using keras on a custom data set and some common issues and their solutions From CNN to Mask R-CNN and Yolo Part 1 From CNN to Mask R-CNN and Yolo Part 2 Object detection using Yolov3 Orignal paper on Yolo I will use Kangaroo dataset as my custom dataset Python 3.5 or higher Tensorflow :I have used CPU version OpenCV VC++ build 14 We will be using DarkFlow repo which can be downloaded from here : https://github.com/thtrieu/darkflow Weight can be downloaded from https://pjreddie.com/darknet/yolov2/ I created a new folder called bin and placed the downloaded weights there as shown below If the configuration(cfg) file and weights are not matching then we get below error Darkflow loads the weights by reading the .cfg file layer by layer, reading corresponding chunk of bytes from .weights. When there is a mismatch between the layers between weights and configuartion file. Configuration file may still have layers to read while the weights parser has already reach the end of .weights. This generates the over read assertion error. There are three options to build the code. Option 1: python setup.py build_ext --inplace Option 2: pip install darkflow globally in dev mode pip install -e . Option 3: Install pip globally pip install . For me option 2 and 3 worked well. We are now ready to process images or video file. Importing required libraries import cv2from darkflow.net.build import TFNetimport matplotlib.pyplot as plt%config InlineBackend.figure_format = 'svg' To define the model we can use the following options 1. model: configuration file (*.cfg) contains the details of the model 2. load: pre-trained weight file 3. batch: number of data to train per a batch 4. epoch: number of iterations to train 5. gpu: set 1.0 if you want to fully utilize the GPU hardware. If you need to use cpu then exclude this option 6. train: use this option when training a dataset 7. annotation: directory where the annotation files are stored 8. dataset: directory where the image files are stored options = { 'model': 'cfg/yolo.cfg', 'load': 'bin/yolov2.weights', 'threshold': 0.3}tfnet = TFNet(options) # read the color image and covert to RGBimg = cv2.imread(‘sample_img\sample_dog.jpg’, cv2.IMREAD_COLOR)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)# use YOLO to predict the imageresult = tfnet.return_predict(img)result # pull out some info from the resultsfor i in range(0, len(result)): tl = (result[i]['topleft']['x'], result[i]['topleft']['y']) br = (result[i]['bottomright']['x'], result[i]['bottomright']['y']) label = result[i]['label']# add the box and label and display it img = cv2.rectangle(img, tl, br, (0, 255, 0), 7) img = cv2.putText(img, label, tl, cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2) plt.imshow(img)plt.show() I am using Kangaroo dataset as my custom dataset. Annotations should be Pascal VOC(Visual Object classification) compliant. This format provides standardized image data sets for object class recognition. Create a folder under darkflow folder and store the images and annotations. I have created a new folder new_data and created images and annots folder under it as shown below Darkflow loads object classes from a custom labels file using labels option. When the lables flag is not set, darkflow will load from labels.txt by default. We update the model in the .cfg file. We need to update the number of classes and the filters in the last convolution layer in the ,cfg file. No. of filters= (5 + no. of classes)*5 In our case since we have only one class kangaroo, we will have 5*(5+1)=30 filters as highlighted below Darkflow tries to load the labels from labels.txt by default. The below error occurs when the the model finds wrong number of labels in labels.txt when compared to the classes in the .cfg file options = {"model": "cfg/yolo.cfg", "load": "bin/yolov2.weights", "batch": 2, "epoch": 5, "train": True, "annotation": "new_data/annots/", "dataset": "new_data/images/"} from darkflow.net.build import TFNettfnet = TFNet(options) tfnet.train() We can also train the custom dataset using command line with the following command python flow --model cfg/yolo.cfg --load bin/yolov2.weights --train --annotation new_data\annots --dataset new_data\images --epoch 1 options = { 'model': 'cfg/yolo-1c.cfg', 'load': 50, 'threshold': 0.3, 'backup':'ckpt/' }tfnet2 = TFNet(options) This loads pre-trained parameters from the checkpoint that we just specified in options. tfnet2.load_from_ckpt() We will take one of the images that has not been used for training to predict the class, bounding box and confidence original_img = cv2.imread(“new_data/images/00001.jpg”)original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)results = tfnet2.return_predict(original_img)print(results) one error that I encountered during my experimentation was Assertion error with four byte size difference when converting. The solution was to change the file loader.py in in utils folder weights_walker.__init__() method change self.offset = 16 to self.offset = 20 based on the byte error, you may need to make the adjustment to the offset. a general formula will be old_offset_value in the file is 16. Error will giv you the value for found _value and expected_value
[ { "code": null, "e": 317, "s": 172, "text": "In this article we will learn step by step implementation of YOLO v2 using keras on a custom data set and some common issues and their solutions" }, { "code": null, "e": 356, "s": 317, "text": "From CNN to Mask R-CNN and Yolo Part 1" }, { "code": null, "e": 395, "s": 356, "text": "From CNN to Mask R-CNN and Yolo Part 2" }, { "code": null, "e": 425, "s": 395, "text": "Object detection using Yolov3" }, { "code": null, "e": 447, "s": 425, "text": "Orignal paper on Yolo" }, { "code": null, "e": 496, "s": 447, "text": "I will use Kangaroo dataset as my custom dataset" }, { "code": null, "e": 517, "s": 496, "text": "Python 3.5 or higher" }, { "code": null, "e": 553, "s": 517, "text": "Tensorflow :I have used CPU version" }, { "code": null, "e": 560, "s": 553, "text": "OpenCV" }, { "code": null, "e": 574, "s": 560, "text": "VC++ build 14" }, { "code": null, "e": 677, "s": 574, "text": "We will be using DarkFlow repo which can be downloaded from here : https://github.com/thtrieu/darkflow" }, { "code": null, "e": 744, "s": 677, "text": "Weight can be downloaded from https://pjreddie.com/darknet/yolov2/" }, { "code": null, "e": 833, "s": 744, "text": "I created a new folder called bin and placed the downloaded weights there as shown below" }, { "code": null, "e": 917, "s": 833, "text": "If the configuration(cfg) file and weights are not matching then we get below error" }, { "code": null, "e": 1280, "s": 917, "text": "Darkflow loads the weights by reading the .cfg file layer by layer, reading corresponding chunk of bytes from .weights. When there is a mismatch between the layers between weights and configuartion file. Configuration file may still have layers to read while the weights parser has already reach the end of .weights. This generates the over read assertion error." }, { "code": null, "e": 1323, "s": 1280, "text": "There are three options to build the code." }, { "code": null, "e": 1333, "s": 1323, "text": "Option 1:" }, { "code": null, "e": 1369, "s": 1333, "text": "python setup.py build_ext --inplace" }, { "code": null, "e": 1421, "s": 1369, "text": "Option 2: pip install darkflow globally in dev mode" }, { "code": null, "e": 1438, "s": 1421, "text": "pip install -e ." }, { "code": null, "e": 1469, "s": 1438, "text": "Option 3: Install pip globally" }, { "code": null, "e": 1483, "s": 1469, "text": "pip install ." }, { "code": null, "e": 1518, "s": 1483, "text": "For me option 2 and 3 worked well." }, { "code": null, "e": 1568, "s": 1518, "text": "We are now ready to process images or video file." }, { "code": null, "e": 1597, "s": 1568, "text": "Importing required libraries" }, { "code": null, "e": 1718, "s": 1597, "text": "import cv2from darkflow.net.build import TFNetimport matplotlib.pyplot as plt%config InlineBackend.figure_format = 'svg'" }, { "code": null, "e": 1771, "s": 1718, "text": "To define the model we can use the following options" }, { "code": null, "e": 1842, "s": 1771, "text": "1. model: configuration file (*.cfg) contains the details of the model" }, { "code": null, "e": 1875, "s": 1842, "text": "2. load: pre-trained weight file" }, { "code": null, "e": 1921, "s": 1875, "text": "3. batch: number of data to train per a batch" }, { "code": null, "e": 1961, "s": 1921, "text": "4. epoch: number of iterations to train" }, { "code": null, "e": 2072, "s": 1961, "text": "5. gpu: set 1.0 if you want to fully utilize the GPU hardware. If you need to use cpu then exclude this option" }, { "code": null, "e": 2122, "s": 2072, "text": "6. train: use this option when training a dataset" }, { "code": null, "e": 2185, "s": 2122, "text": "7. annotation: directory where the annotation files are stored" }, { "code": null, "e": 2240, "s": 2185, "text": "8. dataset: directory where the image files are stored" }, { "code": null, "e": 2347, "s": 2240, "text": "options = { 'model': 'cfg/yolo.cfg', 'load': 'bin/yolov2.weights', 'threshold': 0.3}tfnet = TFNet(options)" }, { "code": null, "e": 2564, "s": 2347, "text": "# read the color image and covert to RGBimg = cv2.imread(‘sample_img\\sample_dog.jpg’, cv2.IMREAD_COLOR)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)# use YOLO to predict the imageresult = tfnet.return_predict(img)result" }, { "code": null, "e": 2996, "s": 2564, "text": "# pull out some info from the resultsfor i in range(0, len(result)): tl = (result[i]['topleft']['x'], result[i]['topleft']['y']) br = (result[i]['bottomright']['x'], result[i]['bottomright']['y']) label = result[i]['label']# add the box and label and display it img = cv2.rectangle(img, tl, br, (0, 255, 0), 7) img = cv2.putText(img, label, tl, cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2) plt.imshow(img)plt.show()" }, { "code": null, "e": 3046, "s": 2996, "text": "I am using Kangaroo dataset as my custom dataset." }, { "code": null, "e": 3200, "s": 3046, "text": "Annotations should be Pascal VOC(Visual Object classification) compliant. This format provides standardized image data sets for object class recognition." }, { "code": null, "e": 3374, "s": 3200, "text": "Create a folder under darkflow folder and store the images and annotations. I have created a new folder new_data and created images and annots folder under it as shown below" }, { "code": null, "e": 3531, "s": 3374, "text": "Darkflow loads object classes from a custom labels file using labels option. When the lables flag is not set, darkflow will load from labels.txt by default." }, { "code": null, "e": 3673, "s": 3531, "text": "We update the model in the .cfg file. We need to update the number of classes and the filters in the last convolution layer in the ,cfg file." }, { "code": null, "e": 3712, "s": 3673, "text": "No. of filters= (5 + no. of classes)*5" }, { "code": null, "e": 3816, "s": 3712, "text": "In our case since we have only one class kangaroo, we will have 5*(5+1)=30 filters as highlighted below" }, { "code": null, "e": 4009, "s": 3816, "text": "Darkflow tries to load the labels from labels.txt by default. The below error occurs when the the model finds wrong number of labels in labels.txt when compared to the classes in the .cfg file" }, { "code": null, "e": 4240, "s": 4009, "text": "options = {\"model\": \"cfg/yolo.cfg\", \"load\": \"bin/yolov2.weights\", \"batch\": 2, \"epoch\": 5, \"train\": True, \"annotation\": \"new_data/annots/\", \"dataset\": \"new_data/images/\"}" }, { "code": null, "e": 4299, "s": 4240, "text": "from darkflow.net.build import TFNettfnet = TFNet(options)" }, { "code": null, "e": 4313, "s": 4299, "text": "tfnet.train()" }, { "code": null, "e": 4396, "s": 4313, "text": "We can also train the custom dataset using command line with the following command" }, { "code": null, "e": 4528, "s": 4396, "text": "python flow --model cfg/yolo.cfg --load bin/yolov2.weights --train --annotation new_data\\annots --dataset new_data\\images --epoch 1" }, { "code": null, "e": 4640, "s": 4528, "text": "options = { 'model': 'cfg/yolo-1c.cfg', 'load': 50, 'threshold': 0.3, 'backup':'ckpt/' }tfnet2 = TFNet(options)" }, { "code": null, "e": 4729, "s": 4640, "text": "This loads pre-trained parameters from the checkpoint that we just specified in options." }, { "code": null, "e": 4753, "s": 4729, "text": "tfnet2.load_from_ckpt()" }, { "code": null, "e": 4870, "s": 4753, "text": "We will take one of the images that has not been used for training to predict the class, bounding box and confidence" }, { "code": null, "e": 5044, "s": 4870, "text": "original_img = cv2.imread(“new_data/images/00001.jpg”)original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)results = tfnet2.return_predict(original_img)print(results)" }, { "code": null, "e": 5103, "s": 5044, "text": "one error that I encountered during my experimentation was" }, { "code": null, "e": 5167, "s": 5103, "text": "Assertion error with four byte size difference when converting." }, { "code": null, "e": 5265, "s": 5167, "text": "The solution was to change the file loader.py in in utils folder weights_walker.__init__() method" }, { "code": null, "e": 5311, "s": 5265, "text": " change self.offset = 16 to self.offset = 20 " }, { "code": null, "e": 5413, "s": 5311, "text": "based on the byte error, you may need to make the adjustment to the offset. a general formula will be" } ]
Python Set | difference_update() - GeeksforGeeks
30 Jun, 2021 The difference_update() method helps in an in-place way of differentiating the set. The previously discussed set difference() helps to find out the difference between two sets and returns a new set with the difference value, but the difference_update() updates the existing caller set.If A and B are two sets. The set difference() method will get the (A – B) and will return a new set. The set difference_update() method modifies the existing set. If (A – B) is performed, then A gets modified into (A – B), and if (B – A) is performed, then B gets modified into (B – A).Syntax: A.difference_update(B) for (A - B) B.difference_update(A) for (B - A) The function returns None and changes the value of the existing set. In this example, we will get the difference between two sets and show how the difference_update works. Python3 # Python code to get the difference between two sets# using difference_update() between set A and set B # Driver CodeA = {10, 20, 30, 40, 80}B = {100, 30, 80, 40, 60} # Modifies A and returns NoneA.difference_update(B) # Prints the modified setprint (A) Output: {20, 10} surindertarika1234 python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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 Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 22731, "s": 22703, "text": "\n30 Jun, 2021" }, { "code": null, "e": 23312, "s": 22731, "text": "The difference_update() method helps in an in-place way of differentiating the set. The previously discussed set difference() helps to find out the difference between two sets and returns a new set with the difference value, but the difference_update() updates the existing caller set.If A and B are two sets. The set difference() method will get the (A – B) and will return a new set. The set difference_update() method modifies the existing set. If (A – B) is performed, then A gets modified into (A – B), and if (B – A) is performed, then B gets modified into (B – A).Syntax: " }, { "code": null, "e": 23382, "s": 23312, "text": "A.difference_update(B) for (A - B)\nB.difference_update(A) for (B - A)" }, { "code": null, "e": 23557, "s": 23384, "text": "The function returns None and changes the value of the existing set. In this example, we will get the difference between two sets and show how the difference_update works. " }, { "code": null, "e": 23565, "s": 23557, "text": "Python3" }, { "code": "# Python code to get the difference between two sets# using difference_update() between set A and set B # Driver CodeA = {10, 20, 30, 40, 80}B = {100, 30, 80, 40, 60} # Modifies A and returns NoneA.difference_update(B) # Prints the modified setprint (A)", "e": 23819, "s": 23565, "text": null }, { "code": null, "e": 23829, "s": 23819, "text": "Output: " }, { "code": null, "e": 23838, "s": 23829, "text": "{20, 10}" }, { "code": null, "e": 23859, "s": 23840, "text": "surindertarika1234" }, { "code": null, "e": 23870, "s": 23859, "text": "python-set" }, { "code": null, "e": 23877, "s": 23870, "text": "Python" }, { "code": null, "e": 23888, "s": 23877, "text": "python-set" }, { "code": null, "e": 23986, "s": 23888, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23995, "s": 23986, "text": "Comments" }, { "code": null, "e": 24008, "s": 23995, "text": "Old Comments" }, { "code": null, "e": 24036, "s": 24008, "text": "Read JSON file using Python" }, { "code": null, "e": 24086, "s": 24036, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 24108, "s": 24086, "text": "Python map() function" }, { "code": null, "e": 24152, "s": 24108, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 24170, "s": 24152, "text": "Python Dictionary" }, { "code": null, "e": 24193, "s": 24170, "text": "Taking input in Python" }, { "code": null, "e": 24228, "s": 24193, "text": "Read a file line by line in Python" }, { "code": null, "e": 24250, "s": 24228, "text": "Enumerate() in Python" }, { "code": null, "e": 24282, "s": 24250, "text": "How to Install PIP on Windows ?" } ]
SQLite - LIKE Clause
SQLite LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. There are two wildcards used in conjunction with the LIKE operator − The percent sign (%) The underscore (_) The percent sign represents zero, one, or multiple numbers or characters. The underscore represents a single number or character. These symbols can be used in combinations. Following is the basic syntax of % and _. SELECT FROM table_name WHERE column LIKE 'XXXX%' or SELECT FROM table_name WHERE column LIKE '%XXXX%' or SELECT FROM table_name WHERE column LIKE 'XXXX_' or SELECT FROM table_name WHERE column LIKE '_XXXX' or SELECT FROM table_name WHERE column LIKE '_XXXX_' You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value. Following table lists a number of examples showing WHERE part having different LIKE clause with '%' and '_' operators. WHERE SALARY LIKE '200%' Finds any values that start with 200 WHERE SALARY LIKE '%200%' Finds any values that have 200 in any position WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third positions WHERE SALARY LIKE '2_%_%' Finds any values that start with 2 and are at least 3 characters in length WHERE SALARY LIKE '%2' Finds any values that end with 2 WHERE SALARY LIKE '_2%3' Finds any values that has a 2 in the second position and ends with a 3 WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that starts with 2 and ends with 3 Let us take a real example, consider COMPANY table with the following records. ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 Following is an example, which will display all the records from COMPANY table where AGE starts with 2. sqlite> SELECT * FROM COMPANY WHERE AGE LIKE '2%'; This will produce the following result. ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text. sqlite> SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%'; This will produce the following result. ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 6 Kim 22 South-Hall 45000.0 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": 2907, "s": 2638, "text": "SQLite LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. There are two wildcards used in conjunction with the LIKE operator −" }, { "code": null, "e": 2928, "s": 2907, "text": "The percent sign (%)" }, { "code": null, "e": 2947, "s": 2928, "text": "The underscore (_)" }, { "code": null, "e": 3120, "s": 2947, "text": "The percent sign represents zero, one, or multiple numbers or characters. The underscore represents a single number or character. These symbols can be used in combinations." }, { "code": null, "e": 3162, "s": 3120, "text": "Following is the basic syntax of % and _." }, { "code": null, "e": 3423, "s": 3162, "text": "SELECT FROM table_name\nWHERE column LIKE 'XXXX%'\nor \nSELECT FROM table_name\nWHERE column LIKE '%XXXX%'\nor\nSELECT FROM table_name\nWHERE column LIKE 'XXXX_'\nor\nSELECT FROM table_name\nWHERE column LIKE '_XXXX'\nor\nSELECT FROM table_name\nWHERE column LIKE '_XXXX_'\n" }, { "code": null, "e": 3538, "s": 3423, "text": "You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value." }, { "code": null, "e": 3657, "s": 3538, "text": "Following table lists a number of examples showing WHERE part having different LIKE clause with '%' and '_' operators." }, { "code": null, "e": 3682, "s": 3657, "text": "WHERE SALARY LIKE '200%'" }, { "code": null, "e": 3719, "s": 3682, "text": "Finds any values that start with 200" }, { "code": null, "e": 3745, "s": 3719, "text": "WHERE SALARY LIKE '%200%'" }, { "code": null, "e": 3792, "s": 3745, "text": "Finds any values that have 200 in any position" }, { "code": null, "e": 3817, "s": 3792, "text": "WHERE SALARY LIKE '_00%'" }, { "code": null, "e": 3881, "s": 3817, "text": "Finds any values that have 00 in the second and third positions" }, { "code": null, "e": 3907, "s": 3881, "text": "WHERE SALARY LIKE '2_%_%'" }, { "code": null, "e": 3982, "s": 3907, "text": "Finds any values that start with 2 and are at least 3 characters in length" }, { "code": null, "e": 4005, "s": 3982, "text": "WHERE SALARY LIKE '%2'" }, { "code": null, "e": 4038, "s": 4005, "text": "Finds any values that end with 2" }, { "code": null, "e": 4063, "s": 4038, "text": "WHERE SALARY LIKE '_2%3'" }, { "code": null, "e": 4134, "s": 4063, "text": "Finds any values that has a 2 in the second position and ends with a 3" }, { "code": null, "e": 4160, "s": 4134, "text": "WHERE SALARY LIKE '2___3'" }, { "code": null, "e": 4235, "s": 4160, "text": "Finds any values in a five-digit number that starts with 2 and ends with 3" }, { "code": null, "e": 4314, "s": 4235, "text": "Let us take a real example, consider COMPANY table with the following records." }, { "code": null, "e": 4820, "s": 4314, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0" }, { "code": null, "e": 4924, "s": 4820, "text": "Following is an example, which will display all the records from COMPANY table where AGE starts with 2." }, { "code": null, "e": 4975, "s": 4924, "text": "sqlite> SELECT * FROM COMPANY WHERE AGE LIKE '2%';" }, { "code": null, "e": 5015, "s": 4975, "text": "This will produce the following result." }, { "code": null, "e": 5466, "s": 5015, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n" }, { "code": null, "e": 5599, "s": 5466, "text": "Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text." }, { "code": null, "e": 5656, "s": 5599, "text": "sqlite> SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%';" }, { "code": null, "e": 5696, "s": 5656, "text": "This will produce the following result." }, { "code": null, "e": 5923, "s": 5696, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n6 Kim 22 South-Hall 45000.0\n" }, { "code": null, "e": 5958, "s": 5923, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5979, "s": 5958, "text": " Sandip Bhattacharya" }, { "code": null, "e": 6012, "s": 5979, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 6029, "s": 6012, "text": " Laurence Svekis" }, { "code": null, "e": 6060, "s": 6029, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 6073, "s": 6060, "text": " Vinay Kumar" }, { "code": null, "e": 6080, "s": 6073, "text": " Print" }, { "code": null, "e": 6091, "s": 6080, "text": " Add Notes" } ]
Minimum swaps to balance the given brackets at any index - GeeksforGeeks
12 Oct, 2021 Given a balanced string of even length consisting of equal number of opening brackets ‘[‘ and closing brackets ‘]’ , Calculate the minimum number of swaps to make string balanced. An unbalanced string can be made balanced by swapping any two brackets. A string is called balanced if it can be represented in the form of “[S1]” where S1 is a balanced string Example: Input: s= “] ] ] [ [ [“Output: 2Explanation: First swap: Position 0 and 5 = [ ] ] [ [ ] Second swap: Position 2 and 3 = [][][] Input: s= “] ] ] ] [ ] [ [ [ [“Output: 2Explanation: first swap for brackets at position 2 and 5, second swap for brackets at position 0 and 7 Approach: Given problem can be solved by iterating through the string and following the steps below: All the balanced brackets are removed as they do not require any swaps for balancing the string Since, the number of opening bracket ‘[‘ and closing bracket is same ‘]’, After removing balanced components , remaining string becomes like ] ] ].....[ [ The optimal approach is to balance two sets of brackets in one swap For every two pairs of square brackets, a swap will make them balanced. If number of unbalanced pairs are odd, then one more swap is needed. If p is the number of unbalanced pairs then minimum number of swaps = (p + 1) / 2 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 balance the given bracket by swapint BalancedStringBySwapping(string s){ // To count the number of uunbalanced pairs int unbalancedPair = 0; for (int i = 0; i < s.length(); ++i) { // if there is an opening bracket and // we encounter closing bracket then it will // decrement the count of unbalanced bracket. if (unbalancedPair > 0 && s[i] == ']') { --unbalancedPair; } // else it will increment unbalanced pair count else if (s[i] == '[') { ++unbalancedPair; } } return (unbalancedPair + 1) / 2;} // Driver codeint main(){ string s = "]]][[["; cout << (BalancedStringBySwapping(s)); return 0;} // This code is contributed by Potta Lokesh // Java implementation for the above approach import java.io.*;import java.util.*; class GFG { // Function to balance the given bracket by swap static int BalancedStringBySwapping(String s) { // To count the number of uunbalanced pairs int unbalancedPair = 0; for (int i = 0; i < s.length(); ++i) { // if there is an opening bracket and // we encounter closing bracket then it will // decrement the count of unbalanced bracket. if (unbalancedPair > 0 && s.charAt(i) == ']') { --unbalancedPair; } // else it will increment unbalanced pair count else if (s.charAt(i) == '[') { ++unbalancedPair; } } return (unbalancedPair + 1) / 2; } // Driver code public static void main(String[] args) { String s = "]]][[["; System.out.println(BalancedStringBySwapping(s)); } } # Python3 implementation for the above approach # Function to balance the given bracket by swapdef BalancedStringBySwapping(s) : # To count the number of uunbalanced pairs unbalancedPair = 0; for i in range(len(s)) : # if there is an opening bracket and # we encounter closing bracket then it will # decrement the count of unbalanced bracket. if (unbalancedPair > 0 and s[i] == ']') : unbalancedPair -= 1; # else it will increment unbalanced pair count elif (s[i] == '[') : unbalancedPair += 1; return (unbalancedPair + 1) // 2; # Driver codeif __name__ == "__main__" : s = "]]][[["; print(BalancedStringBySwapping(s)); # This code is contributed by AnkThon. // C# implementation for the above approachusing System; class GFG{ // Function to balance the given bracket by swap static int BalancedStringBySwapping(String s) { // To count the number of uunbalanced pairs int unbalancedPair = 0; for (int i = 0; i < s.Length; ++i) { // if there is an opening bracket and // we encounter closing bracket then it will // decrement the count of unbalanced bracket. if (unbalancedPair > 0 && s[i] == ']') { --unbalancedPair; } // else it will increment unbalanced pair count else if (s[i] == '[') { ++unbalancedPair; } } return (unbalancedPair + 1) / 2; } // Driver code public static void Main(String[] args) { String s = "]]][[["; Console.Write(BalancedStringBySwapping(s)); } } // This code is contributed by shivanisinghss2110 <script>// javaScript implementation for the above approach // Function to balance the given bracket by swapfunction BalancedStringBySwapping(s){ // To count the number of uunbalanced pairs var unbalancedPair = 0; for (var i = 0; i < s.length; ++i) { // if there is an opening bracket and // we encounter closing bracket then it will // decrement the count of unbalanced bracket. if (unbalancedPair > 0 && s[i] == ']') { --unbalancedPair; } // else it will increment unbalanced pair count else if (s[i] == '[') { ++unbalancedPair; } } return (unbalancedPair + 1) / 2;} // Driver code var s = "]]][[["; document.write(BalancedStringBySwapping(s)); // This code is contributed by AnkThon</script> 2 Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 shivanisinghss2110 ankthon surindertarika1234 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 String Coding Problems for Interviews Vigenère Cipher How to Append a Character to a String in C Convert character array to string in C++ Naive algorithm for Pattern Searching Return maximum occurring character in an input string Hill Cipher sprintf() in C A Program to check if strings are rotations of each other or not Print all the duplicates in the input string
[ { "code": null, "e": 24461, "s": 24433, "text": "\n12 Oct, 2021" }, { "code": null, "e": 24714, "s": 24461, "text": "Given a balanced string of even length consisting of equal number of opening brackets ‘[‘ and closing brackets ‘]’ , Calculate the minimum number of swaps to make string balanced. An unbalanced string can be made balanced by swapping any two brackets. " }, { "code": null, "e": 24819, "s": 24714, "text": "A string is called balanced if it can be represented in the form of “[S1]” where S1 is a balanced string" }, { "code": null, "e": 24828, "s": 24819, "text": "Example:" }, { "code": null, "e": 24955, "s": 24828, "text": "Input: s= “] ] ] [ [ [“Output: 2Explanation: First swap: Position 0 and 5 = [ ] ] [ [ ] Second swap: Position 2 and 3 = [][][]" }, { "code": null, "e": 25098, "s": 24955, "text": "Input: s= “] ] ] ] [ ] [ [ [ [“Output: 2Explanation: first swap for brackets at position 2 and 5, second swap for brackets at position 0 and 7" }, { "code": null, "e": 25199, "s": 25098, "text": "Approach: Given problem can be solved by iterating through the string and following the steps below:" }, { "code": null, "e": 25295, "s": 25199, "text": "All the balanced brackets are removed as they do not require any swaps for balancing the string" }, { "code": null, "e": 25451, "s": 25295, "text": "Since, the number of opening bracket ‘[‘ and closing bracket is same ‘]’, After removing balanced components , remaining string becomes like ] ] ].....[ [" }, { "code": null, "e": 25519, "s": 25451, "text": "The optimal approach is to balance two sets of brackets in one swap" }, { "code": null, "e": 25591, "s": 25519, "text": "For every two pairs of square brackets, a swap will make them balanced." }, { "code": null, "e": 25660, "s": 25591, "text": "If number of unbalanced pairs are odd, then one more swap is needed." }, { "code": null, "e": 25706, "s": 25660, "text": "If p is the number of unbalanced pairs then " }, { "code": null, "e": 25746, "s": 25706, "text": "minimum number of swaps = (p + 1) / 2 " }, { "code": null, "e": 25800, "s": 25748, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 25804, "s": 25800, "text": "C++" }, { "code": null, "e": 25809, "s": 25804, "text": "Java" }, { "code": null, "e": 25817, "s": 25809, "text": "Python3" }, { "code": null, "e": 25820, "s": 25817, "text": "C#" }, { "code": null, "e": 25831, "s": 25820, "text": "Javascript" }, { "code": "// C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // Function to balance the given bracket by swapint BalancedStringBySwapping(string s){ // To count the number of uunbalanced pairs int unbalancedPair = 0; for (int i = 0; i < s.length(); ++i) { // if there is an opening bracket and // we encounter closing bracket then it will // decrement the count of unbalanced bracket. if (unbalancedPair > 0 && s[i] == ']') { --unbalancedPair; } // else it will increment unbalanced pair count else if (s[i] == '[') { ++unbalancedPair; } } return (unbalancedPair + 1) / 2;} // Driver codeint main(){ string s = \"]]][[[\"; cout << (BalancedStringBySwapping(s)); return 0;} // This code is contributed by Potta Lokesh", "e": 26699, "s": 25831, "text": null }, { "code": "// Java implementation for the above approach import java.io.*;import java.util.*; class GFG { // Function to balance the given bracket by swap static int BalancedStringBySwapping(String s) { // To count the number of uunbalanced pairs int unbalancedPair = 0; for (int i = 0; i < s.length(); ++i) { // if there is an opening bracket and // we encounter closing bracket then it will // decrement the count of unbalanced bracket. if (unbalancedPair > 0 && s.charAt(i) == ']') { --unbalancedPair; } // else it will increment unbalanced pair count else if (s.charAt(i) == '[') { ++unbalancedPair; } } return (unbalancedPair + 1) / 2; } // Driver code public static void main(String[] args) { String s = \"]]][[[\"; System.out.println(BalancedStringBySwapping(s)); } }", "e": 27651, "s": 26699, "text": null }, { "code": "# Python3 implementation for the above approach # Function to balance the given bracket by swapdef BalancedStringBySwapping(s) : # To count the number of uunbalanced pairs unbalancedPair = 0; for i in range(len(s)) : # if there is an opening bracket and # we encounter closing bracket then it will # decrement the count of unbalanced bracket. if (unbalancedPair > 0 and s[i] == ']') : unbalancedPair -= 1; # else it will increment unbalanced pair count elif (s[i] == '[') : unbalancedPair += 1; return (unbalancedPair + 1) // 2; # Driver codeif __name__ == \"__main__\" : s = \"]]][[[\"; print(BalancedStringBySwapping(s)); # This code is contributed by AnkThon.", "e": 28420, "s": 27651, "text": null }, { "code": "// C# implementation for the above approachusing System; class GFG{ // Function to balance the given bracket by swap static int BalancedStringBySwapping(String s) { // To count the number of uunbalanced pairs int unbalancedPair = 0; for (int i = 0; i < s.Length; ++i) { // if there is an opening bracket and // we encounter closing bracket then it will // decrement the count of unbalanced bracket. if (unbalancedPair > 0 && s[i] == ']') { --unbalancedPair; } // else it will increment unbalanced pair count else if (s[i] == '[') { ++unbalancedPair; } } return (unbalancedPair + 1) / 2; } // Driver code public static void Main(String[] args) { String s = \"]]][[[\"; Console.Write(BalancedStringBySwapping(s)); } } // This code is contributed by shivanisinghss2110", "e": 29274, "s": 28420, "text": null }, { "code": "<script>// javaScript implementation for the above approach // Function to balance the given bracket by swapfunction BalancedStringBySwapping(s){ // To count the number of uunbalanced pairs var unbalancedPair = 0; for (var i = 0; i < s.length; ++i) { // if there is an opening bracket and // we encounter closing bracket then it will // decrement the count of unbalanced bracket. if (unbalancedPair > 0 && s[i] == ']') { --unbalancedPair; } // else it will increment unbalanced pair count else if (s[i] == '[') { ++unbalancedPair; } } return (unbalancedPair + 1) / 2;} // Driver code var s = \"]]][[[\"; document.write(BalancedStringBySwapping(s)); // This code is contributed by AnkThon</script>", "e": 30093, "s": 29274, "text": null }, { "code": null, "e": 30095, "s": 30093, "text": "2" }, { "code": null, "e": 30138, "s": 30095, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 30152, "s": 30138, "text": "lokeshpotta20" }, { "code": null, "e": 30171, "s": 30152, "text": "shivanisinghss2110" }, { "code": null, "e": 30179, "s": 30171, "text": "ankthon" }, { "code": null, "e": 30198, "s": 30179, "text": "surindertarika1234" }, { "code": null, "e": 30206, "s": 30198, "text": "Strings" }, { "code": null, "e": 30214, "s": 30206, "text": "Strings" }, { "code": null, "e": 30312, "s": 30214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30321, "s": 30312, "text": "Comments" }, { "code": null, "e": 30334, "s": 30321, "text": "Old Comments" }, { "code": null, "e": 30379, "s": 30334, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 30396, "s": 30379, "text": "Vigenère Cipher" }, { "code": null, "e": 30439, "s": 30396, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 30480, "s": 30439, "text": "Convert character array to string in C++" }, { "code": null, "e": 30518, "s": 30480, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 30572, "s": 30518, "text": "Return maximum occurring character in an input string" }, { "code": null, "e": 30584, "s": 30572, "text": "Hill Cipher" }, { "code": null, "e": 30599, "s": 30584, "text": "sprintf() in C" }, { "code": null, "e": 30664, "s": 30599, "text": "A Program to check if strings are rotations of each other or not" } ]